diff --git a/.agents/skills/document-component/SKILL.md b/.agents/skills/document-component/SKILL.md deleted file mode 100644 index bae55d7774..0000000000 --- a/.agents/skills/document-component/SKILL.md +++ /dev/null @@ -1,22 +0,0 @@ -# Document Component - -Steps to add a new component to the SST docs. - -1. Register in docs generator - - Add the component `.ts` path to `entryPoints` in `www/generate.ts` - -2. Add matching public getters - - Ensure every property returned by `getSSTLink()` has a corresponding public getter on the class - - The generator crashes otherwise because `renderLinks()` looks for a getter with the same name - -3. Analyze docs for relevant places to link the component - - Search existing guides (e.g. `cloudflare.mdx`) and component overviews for lists of related components - - Add the new component link where appropriate - -4. Add to Astro sidebar - - Add the generated doc slug to the appropriate section in `www/astro.config.mjs` - - Follow the existing visual ordering: components are sorted from shortest to longest name (least to most characters) - -5. Generate docs - - Run `bun run docs:generate` - diff --git a/.air.toml b/.air.toml deleted file mode 100644 index f76accf02d..0000000000 --- a/.air.toml +++ /dev/null @@ -1,51 +0,0 @@ -root = "." -testdata_dir = "testdata" -tmp_dir = "tmp" - -[build] - args_bin = [] - bin = "./dist/sst" - cmd = "go build -o ./dist/sst ./cmd/sst" - delay = 1000 - exclude_dir = ["assets", "tmp", "vendor", "testdata", "node_modules", "examples"] - exclude_file = [] - exclude_regex = ["_test.go"] - exclude_unchanged = false - follow_symlink = false - full_bin = "" - include_dir = [] - include_ext = ["go", "tpl", "tmpl", "html"] - include_file = [] - kill_delay = "0s" - log = "build-errors.log" - poll = false - poll_interval = 0 - post_cmd = [] - pre_cmd = [] - rerun = false - rerun_delay = 500 - send_interrupt = false - stop_on_error = false - -[color] - app = "" - build = "yellow" - main = "magenta" - runner = "green" - watcher = "cyan" - -[log] - main_only = false - time = false - -[misc] - clean_on_exit = false - -[proxy] - app_port = 0 - enabled = false - proxy_port = 0 - -[screen] - clear_on_rebuild = false - keep_scroll = true diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000..b9ad94b4a0 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,42 @@ +# Don't ever lint node_modules +node_modules + +# Don't lint build output (make sure it's set to your correct build folder name) +dist + +# Don't lint nyc coverage output +coverage + +# Don't lint cdk.out +cdk.out + +# Don't lint build outputs in test +/packages/cli/test/*/.build/** +/packages/cli/test/*/cdk.out/** + +# Don't lint templates +/packages/create-serverless-stack/templates/** + +# Don't lint browser console +/packages/cli/assets/console/** + +# Don't lint eslint tests that need to fail +/packages/cli/test/eslint-cdk-js/** +/packages/cli/test/eslint-cdk-ts/** +/packages/cli/test/eslint-lambda-js/** +/packages/cli/test/eslint-lambda-ts/** +/packages/cli/test/eslint-disabled-js/** +/packages/cli/test/eslint-disabled-ts/** +/packages/cli/test/eslint-ignore-rule-js/** +/packages/cli/test/eslint-ignore-rule-ts/** +/packages/cli/test/eslint-ignore-patterns/** +/packages/cli/test/eslint-lambda-override-eslintrc/** +/packages/cli/test/lambda-override-tsconfig/** +/packages/cli/test/start/src/** +/packages/cli/test/playground/src/sites/** + +# Docs build files +/www/build/** + +# Example React apps +/examples/**/frontend/ diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000000..60a9c6bc66 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,55 @@ +{ + "root": true, + "env": { + "commonjs": true, + "es6": true, + "node": true, + "jest": true + }, + "globals": { + "Atomics": "readonly", + "SharedArrayBuffer": "readonly" + }, + "parser": "@babel/eslint-parser", + "parserOptions": { + "requireConfigFile": false, + "babelOptions": { + "presets": [ + "@babel/preset-react", + [ + "@babel/preset-env", + { + "targets": { + "node": "10" + } + } + ] + ] + } + }, + "plugins": ["@babel", "react"], + "extends": "eslint:recommended", + "rules": { + "react/jsx-uses-react": "error", + "react/jsx-uses-vars": "error" + }, + "overrides": [ + { + "files": ["**/*.ts", "**/*.tsx"], + "env": { "browser": true, "es6": true, "node": true }, + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended" + ], + "globals": { "Atomics": "readonly", "SharedArrayBuffer": "readonly" }, + "parser": "@typescript-eslint/parser", + "plugins": ["@typescript-eslint"], + "rules": { + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/ban-ts-comment": "off" + } + } + ] +} diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..42be01f41f --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Prettier bulk format +1a2f103016036a9fc99c37f252abc765c2256964 diff --git a/.github/workflows/assign-issues.yml b/.github/workflows/assign-issues.yml new file mode 100644 index 0000000000..44f94a018c --- /dev/null +++ b/.github/workflows/assign-issues.yml @@ -0,0 +1,20 @@ +name: Assign New Issues to Project + +on: + issues: + types: [opened, reopened] + +jobs: + issue_opened_or_reopened: + name: issue_opened_or_reopened + runs-on: ubuntu-latest + if: github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'reopened') + steps: + - name: Move issue to project + uses: leonsteinhaeuser/project-beta-automations@v1.2.0 + with: + gh_token: ${{ secrets.FWANG_ASSIGN_ISSUES_TO_PROJECT_TOKEN }} + organization: serverless-stack + project_id: 1 + resource_node_id: ${{ github.event.issue.node_id }} + status_value: Triage diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml deleted file mode 100644 index 128a071211..0000000000 --- a/.github/workflows/check.yml +++ /dev/null @@ -1,70 +0,0 @@ -name: check - -on: - pull_request: - branches: - - dev - types: [opened, synchronize, reopened] - -permissions: - contents: read - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - check: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup Bun - uses: oven-sh/setup-bun@v1 - with: - bun-version: latest - - - name: Setup Go - uses: actions/setup-go@v5 - with: - go-version: ">=1.23.2" - cache: true - - - name: Setup QEMU - uses: docker/setup-qemu-action@v3 - - - name: Setup Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Install dependencies - run: bun install --frozen-lockfile - - - name: Download Go modules - run: go mod download - - - name: Check types - run: cd platform && bun tsc --noEmit - - - name: Build platform - run: ./platform/scripts/build - env: - DOCKER_PUSH: false - - - name: Setup uv - uses: astral-sh/setup-uv@v4 - with: - version: "latest" - - - name: Run Go tests - run: go test -vet=all ./... - - - name: Build CLI - run: go build -o sst ./cmd/sst - - - name: Build docs - run: cd www && bun run build - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..72eda9c9cf --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: CI + +on: + push: + branches: [master, alpha] + paths-ignore: + - "www/**" + - "examples/**" + - "packages/console/**" + pull_request: + branches: [master] + +jobs: + build: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + node-version: [14.x, 16.8] + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + - uses: actions/cache@v2 + with: + path: '**/node_modules' + key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install dependencies + run: yarn --frozen-lockfile + - name: Lint + run: yarn run lint + - name: Test + run: yarn run test --bail diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 553257d0dd..0000000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,135 +0,0 @@ -name: release - -on: - workflow_dispatch: - push: - tags: - - "*" - -concurrency: ${{ github.workflow }}-${{ github.ref }} - -permissions: - id-token: write - contents: write - packages: write - -jobs: - goreleaser: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - name: Setup Bun - uses: oven-sh/setup-bun@v1 - with: - bun-version: latest - - - name: Setup Node - uses: actions/setup-node@v4 - with: - node-version: "24" - registry-url: "https://registry.npmjs.org" - - - name: Login to GHCR - uses: docker/login-action@v2 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Fetch tags - run: git fetch --force --tags - - - name: Setup Go - uses: actions/setup-go@v5 - with: - go-version: ">=1.23.2" - cache: true - - - name: Setup QEMU - uses: docker/setup-qemu-action@v3 - - - name: Setup Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Download Go modules - run: go mod download - - - name: Install dependencies - run: bun i --frozen-lockfile - - - name: TypeScript check - run: cd platform && bun tsc --noEmit - - - name: Build platform - run: ./platform/scripts/build - env: - DOCKER_PUSH: true - - - name: Setup uv - uses: astral-sh/setup-uv@v4 - with: - version: "latest" - - - name: Run Go tests - run: go test -vet=all ./... - - - name: Release CLI - uses: goreleaser/goreleaser-action@v6 - with: - distribution: goreleaser - version: latest - args: release --clean - env: - GITHUB_TOKEN: ${{ secrets.SST_GITHUB_TOKEN }} - AUR_KEY: ${{ secrets.AUR_KEY }} - - - name: Release JS SDK - run: | - cd sdk/js - bun run release - - - name: Authenticate crates.io - id: crates-auth - uses: rust-lang/crates-io-auth-action@v1 - - - name: Release Rust SDK - run: | - VERSION=$(jq -r .version dist/metadata.json) - cd sdk/rust - sed -i "s/^version = \".*\"/version = \"$VERSION\"/" Cargo.toml - cargo publish --allow-dirty - env: - CARGO_REGISTRY_TOKEN: ${{ steps.crates-auth.outputs.token }} - - - name: Build Python SDK - run: | - VERSION=$(jq -r .version dist/metadata.json) - cd sdk/python - sed -i "s/^version = \".*\"/version = \"$VERSION\"/" pyproject.toml - uv build - - - name: Publish Python SDK - uses: pypa/gh-action-pypi-publish@release/v1 - with: - packages-dir: sdk/python/dist/ - - - name: Announce on Discord - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }} - TAG: ${{ github.ref_name }} - run: | - RELEASE_URL="https://github.com/${{ github.repository }}/releases/tag/$TAG" - NOTES=$(gh release view "$TAG" --json body --jq .body \ - | sed -E "s|\(#([0-9]+)\)|([#\1](https://github.com/${{ github.repository }}/pull/\1))|g" \ - | sed -E 's|^\* \[[a-f0-9]+\]\([^)]+\): ||' \ - | sed '/^## Changelog$/d' \ - | sed -E 's|^(.+)$|- \1|') - CONTENT=$(printf '🏷️ [**Release - %s**](%s)\n%s' "$TAG" "$RELEASE_URL" "$NOTES") - PAYLOAD=$(jq -n --arg c "$CONTENT" '{content:$c, flags:4}') - curl -fsS -X POST -H "Content-Type: application/json" \ - -d "$PAYLOAD" "$DISCORD_WEBHOOK_URL" diff --git a/.github/workflows/require-labels.yml b/.github/workflows/require-labels.yml new file mode 100644 index 0000000000..21e6ad3454 --- /dev/null +++ b/.github/workflows/require-labels.yml @@ -0,0 +1,13 @@ +name: Label +on: + pull_request: + types: [opened, labeled, unlabeled, synchronize] +jobs: + required: + runs-on: ubuntu-latest + steps: + - uses: mheap/github-action-required-labels@v1.1.2 + with: + mode: exactly + count: 1 + labels: "breaking, enhancement, bug, documentation, internal, skip changelog" diff --git a/.gitignore b/.gitignore index bdfb61622e..c1e8880e28 100644 --- a/.gitignore +++ b/.gitignore @@ -1,40 +1,115 @@ -.sst -sst +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +#.env +#.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt dist -/sst -s -node_modules -# pulumi -Pulumi.*.yaml -Pulumi.yaml +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and *not* Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public -# osx -.DS_Store +# vuepress build output +.vuepress/dist -.netlify -.env -tmp - -# coding agents -.termai -.opencode -.idea -.kiro - -# python -__pycache__ -uv.lock - -examples/**/sst-env.d.ts -examples/**/sst.pyi -www/src/content/docs/docs/examples.mdx -www/src/data/changelog.json -examples/**/bun.lock -examples/**/bun.lockb -examples/**/pnpm-lock.yaml -examples/**/package-lock.json -examples/**/uv.lock -examples/**/deno.lock -examples/**/Cargo.lock -examples/**/.env.* +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# CDK +cdk.out + +# Vim +.*.sw* + +# OSX +.DS_Store +yarn.lock +yarn.lock diff --git a/.goreleaser.yml b/.goreleaser.yml deleted file mode 100644 index 67a7c25fc9..0000000000 --- a/.goreleaser.yml +++ /dev/null @@ -1,67 +0,0 @@ -version: 2 -project_name: sst -builds: - - env: - - CGO_ENABLED=0 - goos: - - linux - - darwin - - windows - main: ./cmd/sst - -archives: - - formats: - - tar.gz - name_template: >- - sst- - {{- if eq .Os "darwin" }}mac- - {{- else if eq .Os "windows" }}windows- - {{- else if eq .Os "linux" }}linux-{{end}} - {{- if eq .Arch "amd64" }}x86_64 - {{- else if eq .Arch "#86" }}i386 - {{- else }}{{ .Arch }}{{ end }} - {{- if .Arm }}v{{ .Arm }}{{ end }} - format_overrides: - - goos: windows - formats: - - zip -checksum: - name_template: "checksums.txt" -snapshot: - version_template: "0.0.0-{{ .Timestamp }}" -aurs: - - homepage: "https://github.com/sst/sst" - description: "Deploy anything" - private_key: "{{ .Env.AUR_KEY }}" - git_url: "ssh://aur@aur.archlinux.org/sst-bin.git" - license: "MIT" - package: |- - install -Dm755 ./sst "${pkgdir}/usr/bin/sst" -brews: - - repository: - owner: sst - name: homebrew-tap -nfpms: - - maintainer: sst - description: the sst cli - formats: - - deb - - rpm - file_name_template: >- - {{ .ProjectName }}- - {{- if eq .Os "darwin" }}mac - {{- else }}{{ .Os }}{{ end }}-{{ .Arch }} - -changelog: - use: git - format: "[{{ .SHA }}](https://github.com/anomalyco/sst/commit/{{ .SHA }}): {{ .Message }}" - sort: asc - filters: - exclude: - - "^docs:" - - "^doc:" - - "^test:" - - "^ci:" - - "^ignore:" - - "^example:" - - "^wip:" diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000000..5fca0d518b --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +scripts-prepend-node-path=true diff --git a/.nvim.lua b/.nvim.lua deleted file mode 100644 index a50b3f4caa..0000000000 --- a/.nvim.lua +++ /dev/null @@ -1,5 +0,0 @@ -local opts = { noremap = true, silent = true } - -vim.keymap.set("n", "tb", function() - vim.cmd("!go build -o ./dist/sst ./cmd/sst && ./dist/sst") -end, opts) diff --git a/.prettierignore b/.prettierignore index 6d05b4987d..87f80aafa2 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +1,17 @@ +# Ignore CDK outputs +cdk.out +# Ignore SST outputs +.build +# Ignore package lockfile +package-lock.json +# Ignore templates +/packages/create-serverless-stack/templates/** # Ignore markdown files in the docs -/www/src/content/docs/docs/**/*.mdx \ No newline at end of file +# it breaks the formatting +/www/docs/**/*.md +# Ignore React outputs +/examples/**/build/**/*.* +/www/.docusaurus/**/*.* +/www/build/*.* +# Ignore Next.js outputs +/examples/**/.next/**/*.* diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 23830fb423..0000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "git.ignoreLimitWarning": true -} diff --git a/.yarn/releases/yarn-1.19.0.cjs b/.yarn/releases/yarn-1.19.0.cjs new file mode 100755 index 0000000000..b1a221dd68 --- /dev/null +++ b/.yarn/releases/yarn-1.19.0.cjs @@ -0,0 +1,147191 @@ +#!/usr/bin/env node +module.exports = +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 549); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +module.exports = require("path"); + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = __extends; +/* unused harmony export __assign */ +/* unused harmony export __rest */ +/* unused harmony export __decorate */ +/* unused harmony export __param */ +/* unused harmony export __metadata */ +/* unused harmony export __awaiter */ +/* unused harmony export __generator */ +/* unused harmony export __exportStar */ +/* unused harmony export __values */ +/* unused harmony export __read */ +/* unused harmony export __spread */ +/* unused harmony export __await */ +/* unused harmony export __asyncGenerator */ +/* unused harmony export __asyncDelegator */ +/* unused harmony export __asyncValues */ +/* unused harmony export __makeTemplateObject */ +/* unused harmony export __importStar */ +/* unused harmony export __importDefault */ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +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 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __exportStar(m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} + +function __values(o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; + if (m) return m.call(o); + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.__esModule = true; + +var _promise = __webpack_require__(227); + +var _promise2 = _interopRequireDefault(_promise); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (fn) { + return function () { + var gen = fn.apply(this, arguments); + return new _promise2.default(function (resolve, reject) { + function step(key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + return _promise2.default.resolve(value).then(function (value) { + step("next", value); + }, function (err) { + step("throw", err); + }); + } + } + + return step("next"); + }); + }; +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + +module.exports = require("util"); + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getFirstSuitableFolder = exports.readFirstAvailableStream = exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.unlink = exports.glob = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.open = exports.readFileBuffer = exports.lockQueue = exports.constants = undefined; + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); +} + +let buildActionsForCopy = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { + + // + let build = (() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + const src = data.src, + dest = data.dest, + type = data.type; + + const onFresh = data.onFresh || noop; + const onDone = data.onDone || noop; + + // TODO https://github.com/yarnpkg/yarn/issues/3751 + // related to bundled dependencies handling + if (files.has(dest.toLowerCase())) { + reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`); + } else { + files.add(dest.toLowerCase()); + } + + if (type === 'symlink') { + yield mkdirp((_path || _load_path()).default.dirname(dest)); + onFresh(); + actions.symlink.push({ + dest, + linkname: src + }); + onDone(); + return; + } + + if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { + // ignored file + return; + } + + const srcStat = yield lstat(src); + let srcFiles; + + if (srcStat.isDirectory()) { + srcFiles = yield readdir(src); + } + + let destStat; + try { + // try accessing the destination + destStat = yield lstat(dest); + } catch (e) { + // proceed if destination doesn't exist, otherwise error + if (e.code !== 'ENOENT') { + throw e; + } + } + + // if destination exists + if (destStat) { + const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); + const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); + const bothFiles = srcStat.isFile() && destStat.isFile(); + + // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving + // us modes that aren't valid. investigate this, it's generally safe to proceed. + + /* if (srcStat.mode !== destStat.mode) { + try { + await access(dest, srcStat.mode); + } catch (err) {} + } */ + + if (bothFiles && artifactFiles.has(dest)) { + // this file gets changed during build, likely by a custom install script. Don't bother checking it. + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); + return; + } + + if (bothFiles && srcStat.size === destStat.size && (0, (_fsNormalized || _load_fsNormalized()).fileDatesEqual)(srcStat.mtime, destStat.mtime)) { + // we can safely assume this is the same file + onDone(); + reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime)); + return; + } + + if (bothSymlinks) { + const srcReallink = yield readlink(src); + if (srcReallink === (yield readlink(dest))) { + // if both symlinks are the same then we can continue on + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); + return; + } + } + + if (bothFolders) { + // mark files that aren't in this folder as possibly extraneous + const destFiles = yield readdir(dest); + invariant(srcFiles, 'src files not initialised'); + + for (var _iterator4 = destFiles, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { + var _ref6; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref6 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref6 = _i4.value; + } + + const file = _ref6; + + if (srcFiles.indexOf(file) < 0) { + const loc = (_path || _load_path()).default.join(dest, file); + possibleExtraneous.add(loc); + + if ((yield lstat(loc)).isDirectory()) { + for (var _iterator5 = yield readdir(loc), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { + var _ref7; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref7 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref7 = _i5.value; + } + + const file = _ref7; + + possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); + } + } + } + } + } + } + + if (destStat && destStat.isSymbolicLink()) { + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); + destStat = null; + } + + if (srcStat.isSymbolicLink()) { + onFresh(); + const linkname = yield readlink(src); + actions.symlink.push({ + dest, + linkname + }); + onDone(); + } else if (srcStat.isDirectory()) { + if (!destStat) { + reporter.verbose(reporter.lang('verboseFileFolder', dest)); + yield mkdirp(dest); + } + + const destParts = dest.split((_path || _load_path()).default.sep); + while (destParts.length) { + files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); + destParts.pop(); + } + + // push all files to queue + invariant(srcFiles, 'src files not initialised'); + let remaining = srcFiles.length; + if (!remaining) { + onDone(); + } + for (var _iterator6 = srcFiles, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { + var _ref8; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref8 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref8 = _i6.value; + } + + const file = _ref8; + + queue.push({ + dest: (_path || _load_path()).default.join(dest, file), + onFresh, + onDone: function (_onDone) { + function onDone() { + return _onDone.apply(this, arguments); + } + + onDone.toString = function () { + return _onDone.toString(); + }; + + return onDone; + }(function () { + if (--remaining === 0) { + onDone(); + } + }), + src: (_path || _load_path()).default.join(src, file) + }); + } + } else if (srcStat.isFile()) { + onFresh(); + actions.file.push({ + src, + dest, + atime: srcStat.atime, + mtime: srcStat.mtime, + mode: srcStat.mode + }); + onDone(); + } else { + throw new Error(`unsure how to copy this: ${src}`); + } + }); + + return function build(_x5) { + return _ref5.apply(this, arguments); + }; + })(); + + const artifactFiles = new Set(events.artifactFiles || []); + const files = new Set(); + + // initialise events + for (var _iterator = queue, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + const item = _ref2; + + const onDone = item.onDone; + item.onDone = function () { + events.onProgress(item.dest); + if (onDone) { + onDone(); + } + }; + } + events.onStart(queue.length); + + // start building actions + const actions = { + file: [], + symlink: [], + link: [] + }; + + // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items + // at a time due to the requirement to push items onto the queue + while (queue.length) { + const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); + yield Promise.all(items.map(build)); + } + + // simulate the existence of some files to prevent considering them extraneous + for (var _iterator2 = artifactFiles, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + const file = _ref3; + + if (possibleExtraneous.has(file)) { + reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); + possibleExtraneous.delete(file); + } + } + + for (var _iterator3 = possibleExtraneous, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + const loc = _ref4; + + if (files.has(loc.toLowerCase())) { + possibleExtraneous.delete(loc); + } + } + + return actions; + }); + + return function buildActionsForCopy(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); + +let buildActionsForHardlink = (() => { + var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { + + // + let build = (() => { + var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + const src = data.src, + dest = data.dest; + + const onFresh = data.onFresh || noop; + const onDone = data.onDone || noop; + if (files.has(dest.toLowerCase())) { + // Fixes issue https://github.com/yarnpkg/yarn/issues/2734 + // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1, + // package-linker passes that modules A1 and B1 need to be hardlinked, + // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case + // an exception. + onDone(); + return; + } + files.add(dest.toLowerCase()); + + if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { + // ignored file + return; + } + + const srcStat = yield lstat(src); + let srcFiles; + + if (srcStat.isDirectory()) { + srcFiles = yield readdir(src); + } + + const destExists = yield exists(dest); + if (destExists) { + const destStat = yield lstat(dest); + + const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); + const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); + const bothFiles = srcStat.isFile() && destStat.isFile(); + + if (srcStat.mode !== destStat.mode) { + try { + yield access(dest, srcStat.mode); + } catch (err) { + // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving + // us modes that aren't valid. investigate this, it's generally safe to proceed. + reporter.verbose(err); + } + } + + if (bothFiles && artifactFiles.has(dest)) { + // this file gets changed during build, likely by a custom install script. Don't bother checking it. + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); + return; + } + + // correct hardlink + if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) { + onDone(); + reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino)); + return; + } + + if (bothSymlinks) { + const srcReallink = yield readlink(src); + if (srcReallink === (yield readlink(dest))) { + // if both symlinks are the same then we can continue on + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); + return; + } + } + + if (bothFolders) { + // mark files that aren't in this folder as possibly extraneous + const destFiles = yield readdir(dest); + invariant(srcFiles, 'src files not initialised'); + + for (var _iterator10 = destFiles, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { + var _ref14; + + if (_isArray10) { + if (_i10 >= _iterator10.length) break; + _ref14 = _iterator10[_i10++]; + } else { + _i10 = _iterator10.next(); + if (_i10.done) break; + _ref14 = _i10.value; + } + + const file = _ref14; + + if (srcFiles.indexOf(file) < 0) { + const loc = (_path || _load_path()).default.join(dest, file); + possibleExtraneous.add(loc); + + if ((yield lstat(loc)).isDirectory()) { + for (var _iterator11 = yield readdir(loc), _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { + var _ref15; + + if (_isArray11) { + if (_i11 >= _iterator11.length) break; + _ref15 = _iterator11[_i11++]; + } else { + _i11 = _iterator11.next(); + if (_i11.done) break; + _ref15 = _i11.value; + } + + const file = _ref15; + + possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); + } + } + } + } + } + } + + if (srcStat.isSymbolicLink()) { + onFresh(); + const linkname = yield readlink(src); + actions.symlink.push({ + dest, + linkname + }); + onDone(); + } else if (srcStat.isDirectory()) { + reporter.verbose(reporter.lang('verboseFileFolder', dest)); + yield mkdirp(dest); + + const destParts = dest.split((_path || _load_path()).default.sep); + while (destParts.length) { + files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); + destParts.pop(); + } + + // push all files to queue + invariant(srcFiles, 'src files not initialised'); + let remaining = srcFiles.length; + if (!remaining) { + onDone(); + } + for (var _iterator12 = srcFiles, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { + var _ref16; + + if (_isArray12) { + if (_i12 >= _iterator12.length) break; + _ref16 = _iterator12[_i12++]; + } else { + _i12 = _iterator12.next(); + if (_i12.done) break; + _ref16 = _i12.value; + } + + const file = _ref16; + + queue.push({ + onFresh, + src: (_path || _load_path()).default.join(src, file), + dest: (_path || _load_path()).default.join(dest, file), + onDone: function (_onDone2) { + function onDone() { + return _onDone2.apply(this, arguments); + } + + onDone.toString = function () { + return _onDone2.toString(); + }; + + return onDone; + }(function () { + if (--remaining === 0) { + onDone(); + } + }) + }); + } + } else if (srcStat.isFile()) { + onFresh(); + actions.link.push({ + src, + dest, + removeDest: destExists + }); + onDone(); + } else { + throw new Error(`unsure how to copy this: ${src}`); + } + }); + + return function build(_x10) { + return _ref13.apply(this, arguments); + }; + })(); + + const artifactFiles = new Set(events.artifactFiles || []); + const files = new Set(); + + // initialise events + for (var _iterator7 = queue, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { + var _ref10; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref10 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref10 = _i7.value; + } + + const item = _ref10; + + const onDone = item.onDone || noop; + item.onDone = function () { + events.onProgress(item.dest); + onDone(); + }; + } + events.onStart(queue.length); + + // start building actions + const actions = { + file: [], + symlink: [], + link: [] + }; + + // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items + // at a time due to the requirement to push items onto the queue + while (queue.length) { + const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); + yield Promise.all(items.map(build)); + } + + // simulate the existence of some files to prevent considering them extraneous + for (var _iterator8 = artifactFiles, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { + var _ref11; + + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref11 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref11 = _i8.value; + } + + const file = _ref11; + + if (possibleExtraneous.has(file)) { + reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); + possibleExtraneous.delete(file); + } + } + + for (var _iterator9 = possibleExtraneous, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { + var _ref12; + + if (_isArray9) { + if (_i9 >= _iterator9.length) break; + _ref12 = _iterator9[_i9++]; + } else { + _i9 = _iterator9.next(); + if (_i9.done) break; + _ref12 = _i9.value; + } + + const loc = _ref12; + + if (files.has(loc.toLowerCase())) { + possibleExtraneous.delete(loc); + } + } + + return actions; + }); + + return function buildActionsForHardlink(_x6, _x7, _x8, _x9) { + return _ref9.apply(this, arguments); + }; +})(); + +let copyBulk = exports.copyBulk = (() => { + var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { + const events = { + onStart: _events && _events.onStart || noop, + onProgress: _events && _events.onProgress || noop, + possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), + ignoreBasenames: _events && _events.ignoreBasenames || [], + artifactFiles: _events && _events.artifactFiles || [] + }; + + const actions = yield buildActionsForCopy(queue, events, events.possibleExtraneous, reporter); + events.onStart(actions.file.length + actions.symlink.length + actions.link.length); + + const fileActions = actions.file; + + const currentlyWriting = new Map(); + + yield (_promise || _load_promise()).queue(fileActions, (() => { + var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + let writePromise; + while (writePromise = currentlyWriting.get(data.dest)) { + yield writePromise; + } + + reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest)); + const copier = (0, (_fsNormalized || _load_fsNormalized()).copyFile)(data, function () { + return currentlyWriting.delete(data.dest); + }); + currentlyWriting.set(data.dest, copier); + events.onProgress(data.dest); + return copier; + }); + + return function (_x14) { + return _ref18.apply(this, arguments); + }; + })(), CONCURRENT_QUEUE_ITEMS); + + // we need to copy symlinks last as they could reference files we were copying + const symlinkActions = actions.symlink; + yield (_promise || _load_promise()).queue(symlinkActions, function (data) { + const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); + reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); + return symlink(linkname, data.dest); + }); + }); + + return function copyBulk(_x11, _x12, _x13) { + return _ref17.apply(this, arguments); + }; +})(); + +let hardlinkBulk = exports.hardlinkBulk = (() => { + var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { + const events = { + onStart: _events && _events.onStart || noop, + onProgress: _events && _events.onProgress || noop, + possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), + artifactFiles: _events && _events.artifactFiles || [], + ignoreBasenames: [] + }; + + const actions = yield buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter); + events.onStart(actions.file.length + actions.symlink.length + actions.link.length); + + const fileActions = actions.link; + + yield (_promise || _load_promise()).queue(fileActions, (() => { + var _ref20 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest)); + if (data.removeDest) { + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(data.dest); + } + yield link(data.src, data.dest); + }); + + return function (_x18) { + return _ref20.apply(this, arguments); + }; + })(), CONCURRENT_QUEUE_ITEMS); + + // we need to copy symlinks last as they could reference files we were copying + const symlinkActions = actions.symlink; + yield (_promise || _load_promise()).queue(symlinkActions, function (data) { + const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); + reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); + return symlink(linkname, data.dest); + }); + }); + + return function hardlinkBulk(_x15, _x16, _x17) { + return _ref19.apply(this, arguments); + }; +})(); + +let readFileAny = exports.readFileAny = (() => { + var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) { + for (var _iterator13 = files, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { + var _ref22; + + if (_isArray13) { + if (_i13 >= _iterator13.length) break; + _ref22 = _iterator13[_i13++]; + } else { + _i13 = _iterator13.next(); + if (_i13.done) break; + _ref22 = _i13.value; + } + + const file = _ref22; + + if (yield exists(file)) { + return readFile(file); + } + } + return null; + }); + + return function readFileAny(_x19) { + return _ref21.apply(this, arguments); + }; +})(); + +let readJson = exports.readJson = (() => { + var _ref23 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + return (yield readJsonAndFile(loc)).object; + }); + + return function readJson(_x20) { + return _ref23.apply(this, arguments); + }; +})(); + +let readJsonAndFile = exports.readJsonAndFile = (() => { + var _ref24 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + const file = yield readFile(loc); + try { + return { + object: (0, (_map || _load_map()).default)(JSON.parse(stripBOM(file))), + content: file + }; + } catch (err) { + err.message = `${loc}: ${err.message}`; + throw err; + } + }); + + return function readJsonAndFile(_x21) { + return _ref24.apply(this, arguments); + }; +})(); + +let find = exports.find = (() => { + var _ref25 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) { + const parts = dir.split((_path || _load_path()).default.sep); + + while (parts.length) { + const loc = parts.concat(filename).join((_path || _load_path()).default.sep); + + if (yield exists(loc)) { + return loc; + } else { + parts.pop(); + } + } + + return false; + }); + + return function find(_x22, _x23) { + return _ref25.apply(this, arguments); + }; +})(); + +let symlink = exports.symlink = (() => { + var _ref26 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { + if (process.platform !== 'win32') { + // use relative paths otherwise which will be retained if the directory is moved + src = (_path || _load_path()).default.relative((_path || _load_path()).default.dirname(dest), src); + // When path.relative returns an empty string for the current directory, we should instead use + // '.', which is a valid fs.symlink target. + src = src || '.'; + } + + try { + const stats = yield lstat(dest); + if (stats.isSymbolicLink()) { + const resolved = dest; + if (resolved === src) { + return; + } + } + } catch (err) { + if (err.code !== 'ENOENT') { + throw err; + } + } + + // We use rimraf for unlink which never throws an ENOENT on missing target + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); + + if (process.platform === 'win32') { + // use directory junctions if possible on win32, this requires absolute paths + yield fsSymlink(src, dest, 'junction'); + } else { + yield fsSymlink(src, dest); + } + }); + + return function symlink(_x24, _x25) { + return _ref26.apply(this, arguments); + }; +})(); + +let walk = exports.walk = (() => { + var _ref27 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir, ignoreBasenames = new Set()) { + let files = []; + + let filenames = yield readdir(dir); + if (ignoreBasenames.size) { + filenames = filenames.filter(function (name) { + return !ignoreBasenames.has(name); + }); + } + + for (var _iterator14 = filenames, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { + var _ref28; + + if (_isArray14) { + if (_i14 >= _iterator14.length) break; + _ref28 = _iterator14[_i14++]; + } else { + _i14 = _iterator14.next(); + if (_i14.done) break; + _ref28 = _i14.value; + } + + const name = _ref28; + + const relative = relativeDir ? (_path || _load_path()).default.join(relativeDir, name) : name; + const loc = (_path || _load_path()).default.join(dir, name); + const stat = yield lstat(loc); + + files.push({ + relative, + basename: name, + absolute: loc, + mtime: +stat.mtime + }); + + if (stat.isDirectory()) { + files = files.concat((yield walk(loc, relative, ignoreBasenames))); + } + } + + return files; + }); + + return function walk(_x26, _x27) { + return _ref27.apply(this, arguments); + }; +})(); + +let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => { + var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + const stat = yield lstat(loc); + const size = stat.size, + blockSize = stat.blksize; + + + return Math.ceil(size / blockSize) * blockSize; + }); + + return function getFileSizeOnDisk(_x28) { + return _ref29.apply(this, arguments); + }; +})(); + +let getEolFromFile = (() => { + var _ref30 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) { + if (!(yield exists(path))) { + return undefined; + } + + const buffer = yield readFileBuffer(path); + + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] === cr) { + return '\r\n'; + } + if (buffer[i] === lf) { + return '\n'; + } + } + return undefined; + }); + + return function getEolFromFile(_x29) { + return _ref30.apply(this, arguments); + }; +})(); + +let writeFilePreservingEol = exports.writeFilePreservingEol = (() => { + var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) { + const eol = (yield getEolFromFile(path)) || (_os || _load_os()).default.EOL; + if (eol !== '\n') { + data = data.replace(/\n/g, eol); + } + yield writeFile(path, data); + }); + + return function writeFilePreservingEol(_x30, _x31) { + return _ref31.apply(this, arguments); + }; +})(); + +let hardlinksWork = exports.hardlinksWork = (() => { + var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { + const filename = 'test-file' + Math.random(); + const file = (_path || _load_path()).default.join(dir, filename); + const fileLink = (_path || _load_path()).default.join(dir, filename + '-link'); + try { + yield writeFile(file, 'test'); + yield link(file, fileLink); + } catch (err) { + return false; + } finally { + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(file); + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(fileLink); + } + return true; + }); + + return function hardlinksWork(_x32) { + return _ref32.apply(this, arguments); + }; +})(); + +// not a strict polyfill for Node's fs.mkdtemp + + +let makeTempDir = exports.makeTempDir = (() => { + var _ref33 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) { + const dir = (_path || _load_path()).default.join((_os || _load_os()).default.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`); + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dir); + yield mkdirp(dir); + return dir; + }); + + return function makeTempDir(_x33) { + return _ref33.apply(this, arguments); + }; +})(); + +let readFirstAvailableStream = exports.readFirstAvailableStream = (() => { + var _ref34 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths) { + for (var _iterator15 = paths, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { + var _ref35; + + if (_isArray15) { + if (_i15 >= _iterator15.length) break; + _ref35 = _iterator15[_i15++]; + } else { + _i15 = _iterator15.next(); + if (_i15.done) break; + _ref35 = _i15.value; + } + + const path = _ref35; + + try { + const fd = yield open(path, 'r'); + return (_fs || _load_fs()).default.createReadStream(path, { fd }); + } catch (err) { + // Try the next one + } + } + return null; + }); + + return function readFirstAvailableStream(_x34) { + return _ref34.apply(this, arguments); + }; +})(); + +let getFirstSuitableFolder = exports.getFirstSuitableFolder = (() => { + var _ref36 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths, mode = constants.W_OK | constants.X_OK) { + const result = { + skipped: [], + folder: null + }; + + for (var _iterator16 = paths, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : _iterator16[Symbol.iterator]();;) { + var _ref37; + + if (_isArray16) { + if (_i16 >= _iterator16.length) break; + _ref37 = _iterator16[_i16++]; + } else { + _i16 = _iterator16.next(); + if (_i16.done) break; + _ref37 = _i16.value; + } + + const folder = _ref37; + + try { + yield mkdirp(folder); + yield access(folder, mode); + + result.folder = folder; + + return result; + } catch (error) { + result.skipped.push({ + error, + folder + }); + } + } + return result; + }); + + return function getFirstSuitableFolder(_x35) { + return _ref36.apply(this, arguments); + }; +})(); + +exports.copy = copy; +exports.readFile = readFile; +exports.readFileRaw = readFileRaw; +exports.normalizeOS = normalizeOS; + +var _fs; + +function _load_fs() { + return _fs = _interopRequireDefault(__webpack_require__(5)); +} + +var _glob; + +function _load_glob() { + return _glob = _interopRequireDefault(__webpack_require__(99)); +} + +var _os; + +function _load_os() { + return _os = _interopRequireDefault(__webpack_require__(49)); +} + +var _path; + +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); +} + +var _blockingQueue; + +function _load_blockingQueue() { + return _blockingQueue = _interopRequireDefault(__webpack_require__(110)); +} + +var _promise; + +function _load_promise() { + return _promise = _interopRequireWildcard(__webpack_require__(50)); +} + +var _promise2; + +function _load_promise2() { + return _promise2 = __webpack_require__(50); +} + +var _map; + +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(29)); +} + +var _fsNormalized; + +function _load_fsNormalized() { + return _fsNormalized = __webpack_require__(218); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const constants = exports.constants = typeof (_fs || _load_fs()).default.constants !== 'undefined' ? (_fs || _load_fs()).default.constants : { + R_OK: (_fs || _load_fs()).default.R_OK, + W_OK: (_fs || _load_fs()).default.W_OK, + X_OK: (_fs || _load_fs()).default.X_OK +}; + +const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock'); + +const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readFile); +const open = exports.open = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.open); +const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.writeFile); +const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readlink); +const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.realpath); +const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readdir); +const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.rename); +const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.access); +const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.stat); +const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(145)); +const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.exists, true); +const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.lstat); +const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.chmod); +const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.link); +const glob = exports.glob = (0, (_promise2 || _load_promise2()).promisify)((_glob || _load_glob()).default); +exports.unlink = (_fsNormalized || _load_fsNormalized()).unlink; + +// fs.copyFile uses the native file copying instructions on the system, performing much better +// than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the +// concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD. + +const CONCURRENT_QUEUE_ITEMS = (_fs || _load_fs()).default.copyFile ? 128 : 4; + +const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.symlink); +const invariant = __webpack_require__(9); +const stripBOM = __webpack_require__(160); + +const noop = () => {}; + +function copy(src, dest, reporter) { + return copyBulk([{ src, dest }], reporter); +} + +function _readFile(loc, encoding) { + return new Promise((resolve, reject) => { + (_fs || _load_fs()).default.readFile(loc, encoding, function (err, content) { + if (err) { + reject(err); + } else { + resolve(content); + } + }); + }); +} + +function readFile(loc) { + return _readFile(loc, 'utf8').then(normalizeOS); +} + +function readFileRaw(loc) { + return _readFile(loc, 'binary'); +} + +function normalizeOS(body) { + return body.replace(/\r\n/g, '\n'); +} + +const cr = '\r'.charCodeAt(0); +const lf = '\n'.charCodeAt(0); + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +class MessageError extends Error { + constructor(msg, code) { + super(msg); + this.code = code; + } + +} + +exports.MessageError = MessageError; +class ProcessSpawnError extends MessageError { + constructor(msg, code, process) { + super(msg, code); + this.process = process; + } + +} + +exports.ProcessSpawnError = ProcessSpawnError; +class SecurityError extends MessageError {} + +exports.SecurityError = SecurityError; +class ProcessTermError extends MessageError {} + +exports.ProcessTermError = ProcessTermError; +class ResponseError extends Error { + constructor(msg, responseCode) { + super(msg); + this.responseCode = responseCode; + } + +} + +exports.ResponseError = ResponseError; +class OneTimePasswordError extends Error {} +exports.OneTimePasswordError = OneTimePasswordError; + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscriber; }); +/* unused harmony export SafeSubscriber */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_isFunction__ = __webpack_require__(154); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Observer__ = __webpack_require__(420); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Subscription__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__internal_symbol_rxSubscriber__ = __webpack_require__(321); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__config__ = __webpack_require__(185); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__util_hostReportError__ = __webpack_require__(323); +/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ + + + + + + + +var Subscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + _this._parentSubscription = null; + switch (arguments.length) { + case 0: + _this.destination = __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]; + break; + case 1: + if (!destinationOrNext) { + _this.destination = __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; + } + Subscriber.prototype[__WEBPACK_IMPORTED_MODULE_4__internal_symbol_rxSubscriber__["a" /* rxSubscriber */]] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _a = this, _parent = _a._parent, _parents = _a._parents; + this._parent = null; + this._parents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parent = _parent; + this._parents = _parents; + this._parentSubscription = null; + return this; + }; + return Subscriber; +}(__WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */])); + +var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isFunction__["a" /* isFunction */])(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]) { + context = Object.create(observerOrNext); + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isFunction__["a" /* isFunction */])(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = __WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; +}(Subscriber)); + +//# sourceMappingURL=Subscriber.js.map + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPathKey = getPathKey; +const os = __webpack_require__(49); +const path = __webpack_require__(0); +const userHome = __webpack_require__(67).default; + +var _require = __webpack_require__(225); + +const getCacheDir = _require.getCacheDir, + getConfigDir = _require.getConfigDir, + getDataDir = _require.getDataDir; + +const isWebpackBundle = __webpack_require__(278); + +const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']; +const OWNED_DEPENDENCY_TYPES = exports.OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies']; + +const RESOLUTIONS = exports.RESOLUTIONS = 'resolutions'; +const MANIFEST_FIELDS = exports.MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES]; + +const SUPPORTED_NODE_VERSIONS = exports.SUPPORTED_NODE_VERSIONS = '^4.8.0 || ^5.7.0 || ^6.2.2 || >=8.0.0'; + +const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com'; +const NPM_REGISTRY_RE = exports.NPM_REGISTRY_RE = /https?:\/\/registry\.npmjs\.org/g; + +const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/'; +const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh'; +const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi'; + +const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version'; + +// cache version, bump whenever we make backwards incompatible changes +const CACHE_VERSION = exports.CACHE_VERSION = 5; + +// lockfile version, bump whenever we make backwards incompatible changes +const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1; + +// max amount of network requests to perform concurrently +const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8; + +// HTTP timeout used when downloading packages +const NETWORK_TIMEOUT = exports.NETWORK_TIMEOUT = 30 * 1000; // in milliseconds + +// max amount of child processes to execute concurrently +const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5; + +const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid']; + +function getPreferredCacheDirectories() { + const preferredCacheDirectories = [getCacheDir()]; + + if (process.getuid) { + // $FlowFixMe: process.getuid exists, dammit + preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache-${process.getuid()}`)); + } + + preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache`)); + + return preferredCacheDirectories; +} + +const PREFERRED_MODULE_CACHE_DIRECTORIES = exports.PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories(); +const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getConfigDir(); +const DATA_DIRECTORY = exports.DATA_DIRECTORY = getDataDir(); +const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link'); +const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global'); + +const NODE_BIN_PATH = exports.NODE_BIN_PATH = process.execPath; +const YARN_BIN_PATH = exports.YARN_BIN_PATH = getYarnBinPath(); + +// Webpack needs to be configured with node.__dirname/__filename = false +function getYarnBinPath() { + if (isWebpackBundle) { + return __filename; + } else { + return path.join(__dirname, '..', 'bin', 'yarn.js'); + } +} + +const NODE_MODULES_FOLDER = exports.NODE_MODULES_FOLDER = 'node_modules'; +const NODE_PACKAGE_JSON = exports.NODE_PACKAGE_JSON = 'package.json'; + +const PNP_FILENAME = exports.PNP_FILENAME = '.pnp.js'; + +const POSIX_GLOBAL_PREFIX = exports.POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`; +const FALLBACK_GLOBAL_PREFIX = exports.FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.yarn'); + +const META_FOLDER = exports.META_FOLDER = '.yarn-meta'; +const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity'; +const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock'; +const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json'; +const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz'; +const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean'; + +const NPM_LOCK_FILENAME = exports.NPM_LOCK_FILENAME = 'package-lock.json'; +const NPM_SHRINKWRAP_FILENAME = exports.NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json'; + +const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' '; +const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997; +const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance'; + +const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env); + +function getPathKey(platform, env) { + let pathKey = 'PATH'; + + // windows calls its path "Path" usually, but this is not guaranteed. + if (platform === 'win32') { + pathKey = 'Path'; + + for (const key in env) { + if (key.toLowerCase() === 'path') { + pathKey = key; + } + } + } + + return pathKey; +} + +const VERSION_COLOR_SCHEME = exports.VERSION_COLOR_SCHEME = { + major: 'red', + premajor: 'red', + minor: 'yellow', + preminor: 'yellow', + patch: 'green', + prepatch: 'green', + prerelease: 'red', + unchanged: 'white', + unknown: 'red' +}; + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var NODE_ENV = process.env.NODE_ENV; + +var invariant = function(condition, format, a, b, c, d, e, f) { + if (NODE_ENV !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +}; + +module.exports = invariant; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var YAMLException = __webpack_require__(54); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + + +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Observable; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util_canReportError__ = __webpack_require__(322); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_toSubscriber__ = __webpack_require__(932); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__internal_symbol_observable__ = __webpack_require__(117); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util_pipe__ = __webpack_require__(324); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__config__ = __webpack_require__(185); +/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_internal_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ + + + + + +var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_toSubscriber__["a" /* toSubscriber */])(observerOrNext, error, complete); + if (operator) { + operator.call(sink, this.source); + } + else { + sink.add(this.source || (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__util_canReportError__["a" /* canReportError */])(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[__WEBPACK_IMPORTED_MODULE_2__internal_symbol_observable__["a" /* observable */]] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_pipe__["b" /* pipeFromArray */])(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; +}()); + +function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = __WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; +} +//# sourceMappingURL=Observable.js.map + + +/***/ }), +/* 12 */ +/***/ (function(module, exports) { + +module.exports = require("crypto"); + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OuterSubscriber; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Subscriber__ = __webpack_require__(7); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + + +var OuterSubscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](OuterSubscriber, _super); + function OuterSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + OuterSubscriber.prototype.notifyError = function (error, innerSub) { + this.destination.error(error); + }; + OuterSubscriber.prototype.notifyComplete = function (innerSub) { + this.destination.complete(); + }; + return OuterSubscriber; +}(__WEBPACK_IMPORTED_MODULE_1__Subscriber__["a" /* Subscriber */])); + +//# sourceMappingURL=OuterSubscriber.js.map + + +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = subscribeToResult; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__InnerSubscriber__ = __webpack_require__(84); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__subscribeTo__ = __webpack_require__(446); +/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo PURE_IMPORTS_END */ + + +function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { + if (destination === void 0) { + destination = new __WEBPACK_IMPORTED_MODULE_0__InnerSubscriber__["a" /* InnerSubscriber */](outerSubscriber, outerValue, outerIndex); + } + if (destination.closed) { + return; + } + return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__subscribeTo__["a" /* subscribeTo */])(result)(destination); +} +//# sourceMappingURL=subscribeToResult.js.map + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* eslint-disable node/no-deprecated-api */ + + + +var buffer = __webpack_require__(64) +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. + +var assert = __webpack_require__(28); +var Stream = __webpack_require__(23).Stream; +var util = __webpack_require__(3); + + +///--- Globals + +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; + + +///--- Internal + +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); +} + +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); +} + +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} + +function noop() { + // Why even bother with asserts? +} + + +///--- Exports + +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; + } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg); + } + }, + finite: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; + +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; + + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } + + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); + + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; + + return out; +} + +module.exports = _setExports(process.env.NODE_NDEBUG); + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sortAlpha = sortAlpha; +exports.sortOptionsByFlags = sortOptionsByFlags; +exports.entries = entries; +exports.removePrefix = removePrefix; +exports.removeSuffix = removeSuffix; +exports.addSuffix = addSuffix; +exports.hyphenate = hyphenate; +exports.camelCase = camelCase; +exports.compareSortedArrays = compareSortedArrays; +exports.sleep = sleep; +const _camelCase = __webpack_require__(230); + +function sortAlpha(a, b) { + // sort alphabetically in a deterministic way + const shortLen = Math.min(a.length, b.length); + for (let i = 0; i < shortLen; i++) { + const aChar = a.charCodeAt(i); + const bChar = b.charCodeAt(i); + if (aChar !== bChar) { + return aChar - bChar; + } + } + return a.length - b.length; +} + +function sortOptionsByFlags(a, b) { + const aOpt = a.flags.replace(/-/g, ''); + const bOpt = b.flags.replace(/-/g, ''); + return sortAlpha(aOpt, bOpt); +} + +function entries(obj) { + const entries = []; + if (obj) { + for (const key in obj) { + entries.push([key, obj[key]]); + } + } + return entries; +} + +function removePrefix(pattern, prefix) { + if (pattern.startsWith(prefix)) { + pattern = pattern.slice(prefix.length); + } + + return pattern; +} + +function removeSuffix(pattern, suffix) { + if (pattern.endsWith(suffix)) { + return pattern.slice(0, -suffix.length); + } + + return pattern; +} + +function addSuffix(pattern, suffix) { + if (!pattern.endsWith(suffix)) { + return pattern + suffix; + } + + return pattern; +} + +function hyphenate(str) { + return str.replace(/[A-Z]/g, match => { + return '-' + match.charAt(0).toLowerCase(); + }); +} + +function camelCase(str) { + if (/[A-Z]/.test(str)) { + return null; + } else { + return _camelCase(str); + } +} + +function compareSortedArrays(array1, array2) { + if (array1.length !== array2.length) { + return false; + } + for (let i = 0, len = array1.length; i < len; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; +} + +function sleep(ms) { + return new Promise(resolve => { + setTimeout(resolve, ms); + }); +} + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.stringify = exports.parse = undefined; + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); +} + +var _parse; + +function _load_parse() { + return _parse = __webpack_require__(105); +} + +Object.defineProperty(exports, 'parse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_parse || _load_parse()).default; + } +}); + +var _stringify; + +function _load_stringify() { + return _stringify = __webpack_require__(199); +} + +Object.defineProperty(exports, 'stringify', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_stringify || _load_stringify()).default; + } +}); +exports.implodeEntry = implodeEntry; +exports.explodeEntry = explodeEntry; + +var _misc; + +function _load_misc() { + return _misc = __webpack_require__(18); +} + +var _normalizePattern; + +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(37); +} + +var _parse2; + +function _load_parse2() { + return _parse2 = _interopRequireDefault(__webpack_require__(105)); +} + +var _constants; + +function _load_constants() { + return _constants = __webpack_require__(8); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(9); + +const path = __webpack_require__(0); +const ssri = __webpack_require__(65); + +function getName(pattern) { + return (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern).name; +} + +function blankObjectUndefined(obj) { + return obj && Object.keys(obj).length ? obj : undefined; +} + +function keyForRemote(remote) { + return remote.resolved || (remote.reference && remote.hash ? `${remote.reference}#${remote.hash}` : null); +} + +function serializeIntegrity(integrity) { + // We need this because `Integrity.toString()` does not use sorting to ensure a stable string output + // See https://git.io/vx2Hy + return integrity.toString().split(' ').sort().join(' '); +} + +function implodeEntry(pattern, obj) { + const inferredName = getName(pattern); + const integrity = obj.integrity ? serializeIntegrity(obj.integrity) : ''; + const imploded = { + name: inferredName === obj.name ? undefined : obj.name, + version: obj.version, + uid: obj.uid === obj.version ? undefined : obj.uid, + resolved: obj.resolved, + registry: obj.registry === 'npm' ? undefined : obj.registry, + dependencies: blankObjectUndefined(obj.dependencies), + optionalDependencies: blankObjectUndefined(obj.optionalDependencies), + permissions: blankObjectUndefined(obj.permissions), + prebuiltVariants: blankObjectUndefined(obj.prebuiltVariants) + }; + if (integrity) { + imploded.integrity = integrity; + } + return imploded; +} + +function explodeEntry(pattern, obj) { + obj.optionalDependencies = obj.optionalDependencies || {}; + obj.dependencies = obj.dependencies || {}; + obj.uid = obj.uid || obj.version; + obj.permissions = obj.permissions || {}; + obj.registry = obj.registry || 'npm'; + obj.name = obj.name || getName(pattern); + const integrity = obj.integrity; + if (integrity && integrity.isIntegrity) { + obj.integrity = ssri.parse(integrity); + } + return obj; +} + +class Lockfile { + constructor({ cache, source, parseResultType } = {}) { + this.source = source || ''; + this.cache = cache; + this.parseResultType = parseResultType; + } + + // source string if the `cache` was parsed + + + // if true, we're parsing an old yarn file and need to update integrity fields + hasEntriesExistWithoutIntegrity() { + if (!this.cache) { + return false; + } + + for (const key in this.cache) { + // $FlowFixMe - `this.cache` is clearly defined at this point + if (!/^.*@(file:|http)/.test(key) && this.cache[key] && !this.cache[key].integrity) { + return true; + } + } + + return false; + } + + static fromDirectory(dir, reporter) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // read the manifest in this directory + const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME); + + let lockfile; + let rawLockfile = ''; + let parseResult; + + if (yield (_fs || _load_fs()).exists(lockfileLoc)) { + rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc); + parseResult = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc); + + if (reporter) { + if (parseResult.type === 'merge') { + reporter.info(reporter.lang('lockfileMerged')); + } else if (parseResult.type === 'conflict') { + reporter.warn(reporter.lang('lockfileConflict')); + } + } + + lockfile = parseResult.object; + } else if (reporter) { + reporter.info(reporter.lang('noLockfileFound')); + } + + if (lockfile && lockfile.__metadata) { + const lockfilev2 = lockfile; + lockfile = {}; + } + + return new Lockfile({ cache: lockfile, source: rawLockfile, parseResultType: parseResult && parseResult.type }); + })(); + } + + getLocked(pattern) { + const cache = this.cache; + if (!cache) { + return undefined; + } + + const shrunk = pattern in cache && cache[pattern]; + + if (typeof shrunk === 'string') { + return this.getLocked(shrunk); + } else if (shrunk) { + explodeEntry(pattern, shrunk); + return shrunk; + } + + return undefined; + } + + removePattern(pattern) { + const cache = this.cache; + if (!cache) { + return; + } + delete cache[pattern]; + } + + getLockfile(patterns) { + const lockfile = {}; + const seen = new Map(); + + // order by name so that lockfile manifest is assigned to the first dependency with this manifest + // the others that have the same remoteKey will just refer to the first + // ordering allows for consistency in lockfile when it is serialized + const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha); + + for (var _iterator = sortedPatternsKeys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + const pattern = _ref; + + const pkg = patterns[pattern]; + const remote = pkg._remote, + ref = pkg._reference; + + invariant(ref, 'Package is missing a reference'); + invariant(remote, 'Package is missing a remote'); + + const remoteKey = keyForRemote(remote); + const seenPattern = remoteKey && seen.get(remoteKey); + if (seenPattern) { + // no point in duplicating it + lockfile[pattern] = seenPattern; + + // if we're relying on our name being inferred and two of the patterns have + // different inferred names then we need to set it + if (!seenPattern.name && getName(pattern) !== pkg.name) { + seenPattern.name = pkg.name; + } + continue; + } + const obj = implodeEntry(pattern, { + name: pkg.name, + version: pkg.version, + uid: pkg._uid, + resolved: remote.resolved, + integrity: remote.integrity, + registry: remote.registry, + dependencies: pkg.dependencies, + peerDependencies: pkg.peerDependencies, + optionalDependencies: pkg.optionalDependencies, + permissions: ref.permissions, + prebuiltVariants: pkg.prebuiltVariants + }); + + lockfile[pattern] = obj; + + if (remoteKey) { + seen.set(remoteKey, obj); + } + } + + return lockfile; + } +} +exports.default = Lockfile; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +var store = __webpack_require__(133)('wks'); +var uid = __webpack_require__(137); +var Symbol = __webpack_require__(17).Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); +}; + +$exports.store = store; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++; +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + +Comparator.prototype.intersects = function(comp, loose) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, loose); + return satisfies(this.value, rangeTmp, loose); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, loose); + return satisfies(comp.semver, rangeTmp, loose); + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, loose) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')); + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, loose) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')); + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; +}; + + +exports.Range = Range; +function Range(range, loose) { + if (range instanceof Range) { + if (range.loose === loose) { + return range; + } else { + return new Range(range.raw, loose); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, loose); + } + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +Range.prototype.intersects = function(range, loose) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function(thisComparators) { + return thisComparators.every(function(thisComparator) { + return range.set.some(function(rangeComparators) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, loose); + }); + }); + }); + }); +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) + max = v; + maxSV = new SemVer(max, loose); + } + } + }) + return max; +} + +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, loose) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!min || minSV.compare(v) === 1) { // compare(min, v, true) + min = v; + minSV = new SemVer(min, loose); + } + } + }) + return min; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +exports.prerelease = prerelease; +function prerelease(version, loose) { + var parsed = parse(version, loose); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} + +exports.intersects = intersects; +function intersects(r1, r2, loose) { + r1 = new Range(r1, loose) + r2 = new Range(r2, loose) + return r1.intersects(r2) +} + +exports.coerce = coerce; +function coerce(version) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + var match = version.match(re[COERCE]); + + if (match == null) + return null; + + return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); +} + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.__esModule = true; + +var _assign = __webpack_require__(591); + +var _assign2 = _interopRequireDefault(_assign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = _assign2.default || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; +}; + +/***/ }), +/* 23 */ +/***/ (function(module, exports) { + +module.exports = require("stream"); + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + +module.exports = require("url"); + +/***/ }), +/* 25 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscription; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util_isArray__ = __webpack_require__(41); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_isObject__ = __webpack_require__(444); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util_isFunction__ = __webpack_require__(154); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util_tryCatch__ = __webpack_require__(56); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__util_errorObject__ = __webpack_require__(47); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__ = __webpack_require__(441); +/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_tryCatch,_util_errorObject,_util_UnsubscriptionError PURE_IMPORTS_END */ + + + + + + +var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parent = null; + this._parents = null; + this._subscriptions = null; + if (unsubscribe) { + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var hasErrors = false; + var errors; + if (this.closed) { + return; + } + var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parent = null; + this._parents = null; + this._subscriptions = null; + var index = -1; + var len = _parents ? _parents.length : 0; + while (_parent) { + _parent.remove(this); + _parent = ++index < len && _parents[index] || null; + } + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util_isFunction__["a" /* isFunction */])(_unsubscribe)) { + var trial = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_tryCatch__["a" /* tryCatch */])(_unsubscribe).call(this); + if (trial === __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */]) { + hasErrors = true; + errors = errors || (__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */] ? + flattenUnsubscriptionErrors(__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e.errors) : [__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e]); + } + } + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__util_isArray__["a" /* isArray */])(_subscriptions)) { + index = -1; + len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isObject__["a" /* isObject */])(sub)) { + var trial = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_tryCatch__["a" /* tryCatch */])(sub.unsubscribe).call(sub); + if (trial === __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */]) { + hasErrors = true; + errors = errors || []; + var err = __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e; + if (err instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */]) { + errors = errors.concat(flattenUnsubscriptionErrors(err.errors)); + } + else { + errors.push(err); + } + } + } + } + } + if (hasErrors) { + throw new __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */](errors); + } + }; + Subscription.prototype.add = function (teardown) { + if (!teardown || (teardown === Subscription.EMPTY)) { + return Subscription.EMPTY; + } + if (teardown === this) { + return this; + } + var subscription = teardown; + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (typeof subscription._addParent !== 'function') { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + var subscriptions = this._subscriptions || (this._subscriptions = []); + subscriptions.push(subscription); + subscription._addParent(this); + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.prototype._addParent = function (parent) { + var _a = this, _parent = _a._parent, _parents = _a._parents; + if (!_parent || _parent === parent) { + this._parent = parent; + } + else if (!_parents) { + this._parents = [parent]; + } + else if (_parents.indexOf(parent) === -1) { + _parents.push(parent); + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; +}()); + +function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */]) ? err.errors : err); }, []); +} +//# sourceMappingURL=Subscription.js.map + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2015 Joyent, Inc. + +module.exports = { + bufferSplit: bufferSplit, + addRSAMissing: addRSAMissing, + calculateDSAPublic: calculateDSAPublic, + calculateED25519Public: calculateED25519Public, + calculateX25519Public: calculateX25519Public, + mpNormalize: mpNormalize, + mpDenormalize: mpDenormalize, + ecNormalize: ecNormalize, + countZeros: countZeros, + assertCompatible: assertCompatible, + isCompatible: isCompatible, + opensslKeyDeriv: opensslKeyDeriv, + opensshCipherInfo: opensshCipherInfo, + publicFromPrivateECDSA: publicFromPrivateECDSA, + zeroPadToLength: zeroPadToLength, + writeBitString: writeBitString, + readBitString: readBitString +}; + +var assert = __webpack_require__(16); +var Buffer = __webpack_require__(15).Buffer; +var PrivateKey = __webpack_require__(33); +var Key = __webpack_require__(27); +var crypto = __webpack_require__(12); +var algs = __webpack_require__(32); +var asn1 = __webpack_require__(66); + +var ec, jsbn; +var nacl; + +var MAX_CLASS_DEPTH = 3; + +function isCompatible(obj, klass, needVer) { + if (obj === null || typeof (obj) !== 'object') + return (false); + if (needVer === undefined) + needVer = klass.prototype._sshpkApiVersion; + if (obj instanceof klass && + klass.prototype._sshpkApiVersion[0] == needVer[0]) + return (true); + var proto = Object.getPrototypeOf(obj); + var depth = 0; + while (proto.constructor.name !== klass.name) { + proto = Object.getPrototypeOf(proto); + if (!proto || ++depth > MAX_CLASS_DEPTH) + return (false); + } + if (proto.constructor.name !== klass.name) + return (false); + var ver = proto._sshpkApiVersion; + if (ver === undefined) + ver = klass._oldVersionDetect(obj); + if (ver[0] != needVer[0] || ver[1] < needVer[1]) + return (false); + return (true); +} + +function assertCompatible(obj, klass, needVer, name) { + if (name === undefined) + name = 'object'; + assert.ok(obj, name + ' must not be null'); + assert.object(obj, name + ' must be an object'); + if (needVer === undefined) + needVer = klass.prototype._sshpkApiVersion; + if (obj instanceof klass && + klass.prototype._sshpkApiVersion[0] == needVer[0]) + return; + var proto = Object.getPrototypeOf(obj); + var depth = 0; + while (proto.constructor.name !== klass.name) { + proto = Object.getPrototypeOf(proto); + assert.ok(proto && ++depth <= MAX_CLASS_DEPTH, + name + ' must be a ' + klass.name + ' instance'); + } + assert.strictEqual(proto.constructor.name, klass.name, + name + ' must be a ' + klass.name + ' instance'); + var ver = proto._sshpkApiVersion; + if (ver === undefined) + ver = klass._oldVersionDetect(obj); + assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1], + name + ' must be compatible with ' + klass.name + ' klass ' + + 'version ' + needVer[0] + '.' + needVer[1]); +} + +var CIPHER_LEN = { + 'des-ede3-cbc': { key: 7, iv: 8 }, + 'aes-128-cbc': { key: 16, iv: 16 } +}; +var PKCS5_SALT_LEN = 8; + +function opensslKeyDeriv(cipher, salt, passphrase, count) { + assert.buffer(salt, 'salt'); + assert.buffer(passphrase, 'passphrase'); + assert.number(count, 'iteration count'); + + var clen = CIPHER_LEN[cipher]; + assert.object(clen, 'supported cipher'); + + salt = salt.slice(0, PKCS5_SALT_LEN); + + var D, D_prev, bufs; + var material = Buffer.alloc(0); + while (material.length < clen.key + clen.iv) { + bufs = []; + if (D_prev) + bufs.push(D_prev); + bufs.push(passphrase); + bufs.push(salt); + D = Buffer.concat(bufs); + for (var j = 0; j < count; ++j) + D = crypto.createHash('md5').update(D).digest(); + material = Buffer.concat([material, D]); + D_prev = D; + } + + return ({ + key: material.slice(0, clen.key), + iv: material.slice(clen.key, clen.key + clen.iv) + }); +} + +/* Count leading zero bits on a buffer */ +function countZeros(buf) { + var o = 0, obit = 8; + while (o < buf.length) { + var mask = (1 << obit); + if ((buf[o] & mask) === mask) + break; + obit--; + if (obit < 0) { + o++; + obit = 8; + } + } + return (o*8 + (8 - obit) - 1); +} + +function bufferSplit(buf, chr) { + assert.buffer(buf); + assert.string(chr); + + var parts = []; + var lastPart = 0; + var matches = 0; + for (var i = 0; i < buf.length; ++i) { + if (buf[i] === chr.charCodeAt(matches)) + ++matches; + else if (buf[i] === chr.charCodeAt(0)) + matches = 1; + else + matches = 0; + + if (matches >= chr.length) { + var newPart = i + 1; + parts.push(buf.slice(lastPart, newPart - matches)); + lastPart = newPart; + matches = 0; + } + } + if (lastPart <= buf.length) + parts.push(buf.slice(lastPart, buf.length)); + + return (parts); +} + +function ecNormalize(buf, addZero) { + assert.buffer(buf); + if (buf[0] === 0x00 && buf[1] === 0x04) { + if (addZero) + return (buf); + return (buf.slice(1)); + } else if (buf[0] === 0x04) { + if (!addZero) + return (buf); + } else { + while (buf[0] === 0x00) + buf = buf.slice(1); + if (buf[0] === 0x02 || buf[0] === 0x03) + throw (new Error('Compressed elliptic curve points ' + + 'are not supported')); + if (buf[0] !== 0x04) + throw (new Error('Not a valid elliptic curve point')); + if (!addZero) + return (buf); + } + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x0; + buf.copy(b, 1); + return (b); +} + +function readBitString(der, tag) { + if (tag === undefined) + tag = asn1.Ber.BitString; + var buf = der.readString(tag, true); + assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' + + 'not supported (0x' + buf[0].toString(16) + ')'); + return (buf.slice(1)); +} + +function writeBitString(der, buf, tag) { + if (tag === undefined) + tag = asn1.Ber.BitString; + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x00; + buf.copy(b, 1); + der.writeBuffer(b, tag); +} + +function mpNormalize(buf) { + assert.buffer(buf); + while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00) + buf = buf.slice(1); + if ((buf[0] & 0x80) === 0x80) { + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x00; + buf.copy(b, 1); + buf = b; + } + return (buf); +} + +function mpDenormalize(buf) { + assert.buffer(buf); + while (buf.length > 1 && buf[0] === 0x00) + buf = buf.slice(1); + return (buf); +} + +function zeroPadToLength(buf, len) { + assert.buffer(buf); + assert.number(len); + while (buf.length > len) { + assert.equal(buf[0], 0x00); + buf = buf.slice(1); + } + while (buf.length < len) { + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x00; + buf.copy(b, 1); + buf = b; + } + return (buf); +} + +function bigintToMpBuf(bigint) { + var buf = Buffer.from(bigint.toByteArray()); + buf = mpNormalize(buf); + return (buf); +} + +function calculateDSAPublic(g, p, x) { + assert.buffer(g); + assert.buffer(p); + assert.buffer(x); + try { + var bigInt = __webpack_require__(81).BigInteger; + } catch (e) { + throw (new Error('To load a PKCS#8 format DSA private key, ' + + 'the node jsbn library is required.')); + } + g = new bigInt(g); + p = new bigInt(p); + x = new bigInt(x); + var y = g.modPow(x, p); + var ybuf = bigintToMpBuf(y); + return (ybuf); +} + +function calculateED25519Public(k) { + assert.buffer(k); + + if (nacl === undefined) + nacl = __webpack_require__(76); + + var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k)); + return (Buffer.from(kp.publicKey)); +} + +function calculateX25519Public(k) { + assert.buffer(k); + + if (nacl === undefined) + nacl = __webpack_require__(76); + + var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k)); + return (Buffer.from(kp.publicKey)); +} + +function addRSAMissing(key) { + assert.object(key); + assertCompatible(key, PrivateKey, [1, 1]); + try { + var bigInt = __webpack_require__(81).BigInteger; + } catch (e) { + throw (new Error('To write a PEM private key from ' + + 'this source, the node jsbn lib is required.')); + } + + var d = new bigInt(key.part.d.data); + var buf; + + if (!key.part.dmodp) { + var p = new bigInt(key.part.p.data); + var dmodp = d.mod(p.subtract(1)); + + buf = bigintToMpBuf(dmodp); + key.part.dmodp = {name: 'dmodp', data: buf}; + key.parts.push(key.part.dmodp); + } + if (!key.part.dmodq) { + var q = new bigInt(key.part.q.data); + var dmodq = d.mod(q.subtract(1)); + + buf = bigintToMpBuf(dmodq); + key.part.dmodq = {name: 'dmodq', data: buf}; + key.parts.push(key.part.dmodq); + } +} + +function publicFromPrivateECDSA(curveName, priv) { + assert.string(curveName, 'curveName'); + assert.buffer(priv); + if (ec === undefined) + ec = __webpack_require__(139); + if (jsbn === undefined) + jsbn = __webpack_require__(81).BigInteger; + var params = algs.curves[curveName]; + var p = new jsbn(params.p); + var a = new jsbn(params.a); + var b = new jsbn(params.b); + var curve = new ec.ECCurveFp(p, a, b); + var G = curve.decodePointHex(params.G.toString('hex')); + + var d = new jsbn(mpNormalize(priv)); + var pub = G.multiply(d); + pub = Buffer.from(curve.encodePointHex(pub), 'hex'); + + var parts = []; + parts.push({name: 'curve', data: Buffer.from(curveName)}); + parts.push({name: 'Q', data: pub}); + + var key = new Key({type: 'ecdsa', curve: curve, parts: parts}); + return (key); +} + +function opensshCipherInfo(cipher) { + var inf = {}; + switch (cipher) { + case '3des-cbc': + inf.keySize = 24; + inf.blockSize = 8; + inf.opensslName = 'des-ede3-cbc'; + break; + case 'blowfish-cbc': + inf.keySize = 16; + inf.blockSize = 8; + inf.opensslName = 'bf-cbc'; + break; + case 'aes128-cbc': + case 'aes128-ctr': + case 'aes128-gcm@openssh.com': + inf.keySize = 16; + inf.blockSize = 16; + inf.opensslName = 'aes-128-' + cipher.slice(7, 10); + break; + case 'aes192-cbc': + case 'aes192-ctr': + case 'aes192-gcm@openssh.com': + inf.keySize = 24; + inf.blockSize = 16; + inf.opensslName = 'aes-192-' + cipher.slice(7, 10); + break; + case 'aes256-cbc': + case 'aes256-ctr': + case 'aes256-gcm@openssh.com': + inf.keySize = 32; + inf.blockSize = 16; + inf.opensslName = 'aes-256-' + cipher.slice(7, 10); + break; + default: + throw (new Error( + 'Unsupported openssl cipher "' + cipher + '"')); + } + return (inf); +} + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2017 Joyent, Inc. + +module.exports = Key; + +var assert = __webpack_require__(16); +var algs = __webpack_require__(32); +var crypto = __webpack_require__(12); +var Fingerprint = __webpack_require__(156); +var Signature = __webpack_require__(75); +var DiffieHellman = __webpack_require__(325).DiffieHellman; +var errs = __webpack_require__(74); +var utils = __webpack_require__(26); +var PrivateKey = __webpack_require__(33); +var edCompat; + +try { + edCompat = __webpack_require__(454); +} catch (e) { + /* Just continue through, and bail out if we try to use it. */ +} + +var InvalidAlgorithmError = errs.InvalidAlgorithmError; +var KeyParseError = errs.KeyParseError; + +var formats = {}; +formats['auto'] = __webpack_require__(455); +formats['pem'] = __webpack_require__(86); +formats['pkcs1'] = __webpack_require__(327); +formats['pkcs8'] = __webpack_require__(157); +formats['rfc4253'] = __webpack_require__(103); +formats['ssh'] = __webpack_require__(456); +formats['ssh-private'] = __webpack_require__(192); +formats['openssh'] = formats['ssh-private']; +formats['dnssec'] = __webpack_require__(326); + +function Key(opts) { + assert.object(opts, 'options'); + assert.arrayOfObject(opts.parts, 'options.parts'); + assert.string(opts.type, 'options.type'); + assert.optionalString(opts.comment, 'options.comment'); + + var algInfo = algs.info[opts.type]; + if (typeof (algInfo) !== 'object') + throw (new InvalidAlgorithmError(opts.type)); + + var partLookup = {}; + for (var i = 0; i < opts.parts.length; ++i) { + var part = opts.parts[i]; + partLookup[part.name] = part; + } + + this.type = opts.type; + this.parts = opts.parts; + this.part = partLookup; + this.comment = undefined; + this.source = opts.source; + + /* for speeding up hashing/fingerprint operations */ + this._rfc4253Cache = opts._rfc4253Cache; + this._hashCache = {}; + + var sz; + this.curve = undefined; + if (this.type === 'ecdsa') { + var curve = this.part.curve.data.toString(); + this.curve = curve; + sz = algs.curves[curve].size; + } else if (this.type === 'ed25519' || this.type === 'curve25519') { + sz = 256; + this.curve = 'curve25519'; + } else { + var szPart = this.part[algInfo.sizePart]; + sz = szPart.data.length; + sz = sz * 8 - utils.countZeros(szPart.data); + } + this.size = sz; +} + +Key.formats = formats; + +Key.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'ssh'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); + + if (format === 'rfc4253') { + if (this._rfc4253Cache === undefined) + this._rfc4253Cache = formats['rfc4253'].write(this); + return (this._rfc4253Cache); + } + + return (formats[format].write(this, options)); +}; + +Key.prototype.toString = function (format, options) { + return (this.toBuffer(format, options).toString()); +}; + +Key.prototype.hash = function (algo) { + assert.string(algo, 'algorithm'); + algo = algo.toLowerCase(); + if (algs.hashAlgs[algo] === undefined) + throw (new InvalidAlgorithmError(algo)); + + if (this._hashCache[algo]) + return (this._hashCache[algo]); + var hash = crypto.createHash(algo). + update(this.toBuffer('rfc4253')).digest(); + this._hashCache[algo] = hash; + return (hash); +}; + +Key.prototype.fingerprint = function (algo) { + if (algo === undefined) + algo = 'sha256'; + assert.string(algo, 'algorithm'); + var opts = { + type: 'key', + hash: this.hash(algo), + algorithm: algo + }; + return (new Fingerprint(opts)); +}; + +Key.prototype.defaultHashAlgorithm = function () { + var hashAlgo = 'sha1'; + if (this.type === 'rsa') + hashAlgo = 'sha256'; + if (this.type === 'dsa' && this.size > 1024) + hashAlgo = 'sha256'; + if (this.type === 'ed25519') + hashAlgo = 'sha512'; + if (this.type === 'ecdsa') { + if (this.size <= 256) + hashAlgo = 'sha256'; + else if (this.size <= 384) + hashAlgo = 'sha384'; + else + hashAlgo = 'sha512'; + } + return (hashAlgo); +}; + +Key.prototype.createVerify = function (hashAlgo) { + if (hashAlgo === undefined) + hashAlgo = this.defaultHashAlgorithm(); + assert.string(hashAlgo, 'hash algorithm'); + + /* ED25519 is not supported by OpenSSL, use a javascript impl. */ + if (this.type === 'ed25519' && edCompat !== undefined) + return (new edCompat.Verifier(this, hashAlgo)); + if (this.type === 'curve25519') + throw (new Error('Curve25519 keys are not suitable for ' + + 'signing or verification')); + + var v, nm, err; + try { + nm = hashAlgo.toUpperCase(); + v = crypto.createVerify(nm); + } catch (e) { + err = e; + } + if (v === undefined || (err instanceof Error && + err.message.match(/Unknown message digest/))) { + nm = 'RSA-'; + nm += hashAlgo.toUpperCase(); + v = crypto.createVerify(nm); + } + assert.ok(v, 'failed to create verifier'); + var oldVerify = v.verify.bind(v); + var key = this.toBuffer('pkcs8'); + var curve = this.curve; + var self = this; + v.verify = function (signature, fmt) { + if (Signature.isSignature(signature, [2, 0])) { + if (signature.type !== self.type) + return (false); + if (signature.hashAlgorithm && + signature.hashAlgorithm !== hashAlgo) + return (false); + if (signature.curve && self.type === 'ecdsa' && + signature.curve !== curve) + return (false); + return (oldVerify(key, signature.toBuffer('asn1'))); + + } else if (typeof (signature) === 'string' || + Buffer.isBuffer(signature)) { + return (oldVerify(key, signature, fmt)); + + /* + * Avoid doing this on valid arguments, walking the prototype + * chain can be quite slow. + */ + } else if (Signature.isSignature(signature, [1, 0])) { + throw (new Error('signature was created by too old ' + + 'a version of sshpk and cannot be verified')); + + } else { + throw (new TypeError('signature must be a string, ' + + 'Buffer, or Signature object')); + } + }; + return (v); +}; + +Key.prototype.createDiffieHellman = function () { + if (this.type === 'rsa') + throw (new Error('RSA keys do not support Diffie-Hellman')); + + return (new DiffieHellman(this)); +}; +Key.prototype.createDH = Key.prototype.createDiffieHellman; + +Key.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; + + assert.object(formats[format], 'formats[format]'); + + try { + var k = formats[format].read(data, options); + if (k instanceof PrivateKey) + k = k.toPublic(); + if (!k.comment) + k.comment = options.filename; + return (k); + } catch (e) { + if (e.name === 'KeyEncryptedError') + throw (e); + throw (new KeyParseError(options.filename, format, e)); + } +}; + +Key.isKey = function (obj, ver) { + return (utils.isCompatible(obj, Key, ver)); +}; + +/* + * API versions for Key: + * [1,0] -- initial ver, may take Signature for createVerify or may not + * [1,1] -- added pkcs1, pkcs8 formats + * [1,2] -- added auto, ssh-private, openssh formats + * [1,3] -- added defaultHashAlgorithm + * [1,4] -- added ed support, createDH + * [1,5] -- first explicitly tagged version + * [1,6] -- changed ed25519 part names + */ +Key.prototype._sshpkApiVersion = [1, 6]; + +Key._oldVersionDetect = function (obj) { + assert.func(obj.toBuffer); + assert.func(obj.fingerprint); + if (obj.createDH) + return ([1, 4]); + if (obj.defaultHashAlgorithm) + return ([1, 3]); + if (obj.formats['auto']) + return ([1, 2]); + if (obj.formats['pkcs1']) + return ([1, 1]); + return ([1, 0]); +}; + + +/***/ }), +/* 28 */ +/***/ (function(module, exports) { + +module.exports = require("assert"); + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = nullify; +function nullify(obj = {}) { + if (Array.isArray(obj)) { + for (var _iterator = obj, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + const item = _ref; + + nullify(item); + } + } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') { + Object.setPrototypeOf(obj, null); + + // for..in can only be applied to 'object', not 'function' + if (typeof obj === 'object') { + for (const key in obj) { + nullify(obj[key]); + } + } + } + + return obj; +} + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const escapeStringRegexp = __webpack_require__(388); +const ansiStyles = __webpack_require__(506); +const stdoutColor = __webpack_require__(598).stdout; + +const template = __webpack_require__(599); + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript + + +/***/ }), +/* 31 */ +/***/ (function(module, exports) { + +var core = module.exports = { version: '2.5.7' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2015 Joyent, Inc. + +var Buffer = __webpack_require__(15).Buffer; + +var algInfo = { + 'dsa': { + parts: ['p', 'q', 'g', 'y'], + sizePart: 'p' + }, + 'rsa': { + parts: ['e', 'n'], + sizePart: 'n' + }, + 'ecdsa': { + parts: ['curve', 'Q'], + sizePart: 'Q' + }, + 'ed25519': { + parts: ['A'], + sizePart: 'A' + } +}; +algInfo['curve25519'] = algInfo['ed25519']; + +var algPrivInfo = { + 'dsa': { + parts: ['p', 'q', 'g', 'y', 'x'] + }, + 'rsa': { + parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] + }, + 'ecdsa': { + parts: ['curve', 'Q', 'd'] + }, + 'ed25519': { + parts: ['A', 'k'] + } +}; +algPrivInfo['curve25519'] = algPrivInfo['ed25519']; + +var hashAlgs = { + 'md5': true, + 'sha1': true, + 'sha256': true, + 'sha384': true, + 'sha512': true +}; + +/* + * Taken from + * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf + */ +var curves = { + 'nistp256': { + size: 256, + pkcs8oid: '1.2.840.10045.3.1.7', + p: Buffer.from(('00' + + 'ffffffff 00000001 00000000 00000000' + + '00000000 ffffffff ffffffff ffffffff'). + replace(/ /g, ''), 'hex'), + a: Buffer.from(('00' + + 'FFFFFFFF 00000001 00000000 00000000' + + '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: Buffer.from(( + '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + + '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). + replace(/ /g, ''), 'hex'), + s: Buffer.from(('00' + + 'c49d3608 86e70493 6a6678e1 139d26b7' + + '819f7e90'). + replace(/ /g, ''), 'hex'), + n: Buffer.from(('00' + + 'ffffffff 00000000 ffffffff ffffffff' + + 'bce6faad a7179e84 f3b9cac2 fc632551'). + replace(/ /g, ''), 'hex'), + G: Buffer.from(('04' + + '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + + '77037d81 2deb33a0 f4a13945 d898c296' + + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + + '2bce3357 6b315ece cbb64068 37bf51f5'). + replace(/ /g, ''), 'hex') + }, + 'nistp384': { + size: 384, + pkcs8oid: '1.3.132.0.34', + p: Buffer.from(('00' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff fffffffe' + + 'ffffffff 00000000 00000000 ffffffff'). + replace(/ /g, ''), 'hex'), + a: Buffer.from(('00' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + + 'FFFFFFFF 00000000 00000000 FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: Buffer.from(( + 'b3312fa7 e23ee7e4 988e056b e3f82d19' + + '181d9c6e fe814112 0314088f 5013875a' + + 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). + replace(/ /g, ''), 'hex'), + s: Buffer.from(('00' + + 'a335926a a319a27a 1d00896a 6773a482' + + '7acdac73'). + replace(/ /g, ''), 'hex'), + n: Buffer.from(('00' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff c7634d81 f4372ddf' + + '581a0db2 48b0a77a ecec196a ccc52973'). + replace(/ /g, ''), 'hex'), + G: Buffer.from(('04' + + 'aa87ca22 be8b0537 8eb1c71e f320ad74' + + '6e1d3b62 8ba79b98 59f741e0 82542a38' + + '5502f25d bf55296c 3a545e38 72760ab7' + + '3617de4a 96262c6f 5d9e98bf 9292dc29' + + 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). + replace(/ /g, ''), 'hex') + }, + 'nistp521': { + size: 521, + pkcs8oid: '1.3.132.0.35', + p: Buffer.from(( + '01ffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffff').replace(/ /g, ''), 'hex'), + a: Buffer.from(('01FF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: Buffer.from(('51' + + '953eb961 8e1c9a1f 929a21a0 b68540ee' + + 'a2da725b 99b315f3 b8b48991 8ef109e1' + + '56193951 ec7e937b 1652c0bd 3bb1bf07' + + '3573df88 3d2c34f1 ef451fd4 6b503f00'). + replace(/ /g, ''), 'hex'), + s: Buffer.from(('00' + + 'd09e8800 291cb853 96cc6717 393284aa' + + 'a0da64ba').replace(/ /g, ''), 'hex'), + n: Buffer.from(('01ff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff fffffffa' + + '51868783 bf2f966b 7fcc0148 f709a5d0' + + '3bb5c9b8 899c47ae bb6fb71e 91386409'). + replace(/ /g, ''), 'hex'), + G: Buffer.from(('04' + + '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + + '9c648139 053fb521 f828af60 6b4d3dba' + + 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + + '3348b3c1 856a429b f97e7e31 c2e5bd66' + + '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + + '98f54449 579b4468 17afbd17 273e662c' + + '97ee7299 5ef42640 c550b901 3fad0761' + + '353c7086 a272c240 88be9476 9fd16650'). + replace(/ /g, ''), 'hex') + } +}; + +module.exports = { + info: algInfo, + privInfo: algPrivInfo, + hashAlgs: hashAlgs, + curves: curves +}; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2017 Joyent, Inc. + +module.exports = PrivateKey; + +var assert = __webpack_require__(16); +var Buffer = __webpack_require__(15).Buffer; +var algs = __webpack_require__(32); +var crypto = __webpack_require__(12); +var Fingerprint = __webpack_require__(156); +var Signature = __webpack_require__(75); +var errs = __webpack_require__(74); +var util = __webpack_require__(3); +var utils = __webpack_require__(26); +var dhe = __webpack_require__(325); +var generateECDSA = dhe.generateECDSA; +var generateED25519 = dhe.generateED25519; +var edCompat; +var nacl; + +try { + edCompat = __webpack_require__(454); +} catch (e) { + /* Just continue through, and bail out if we try to use it. */ +} + +var Key = __webpack_require__(27); + +var InvalidAlgorithmError = errs.InvalidAlgorithmError; +var KeyParseError = errs.KeyParseError; +var KeyEncryptedError = errs.KeyEncryptedError; + +var formats = {}; +formats['auto'] = __webpack_require__(455); +formats['pem'] = __webpack_require__(86); +formats['pkcs1'] = __webpack_require__(327); +formats['pkcs8'] = __webpack_require__(157); +formats['rfc4253'] = __webpack_require__(103); +formats['ssh-private'] = __webpack_require__(192); +formats['openssh'] = formats['ssh-private']; +formats['ssh'] = formats['ssh-private']; +formats['dnssec'] = __webpack_require__(326); + +function PrivateKey(opts) { + assert.object(opts, 'options'); + Key.call(this, opts); + + this._pubCache = undefined; +} +util.inherits(PrivateKey, Key); + +PrivateKey.formats = formats; + +PrivateKey.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'pkcs1'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); + + return (formats[format].write(this, options)); +}; + +PrivateKey.prototype.hash = function (algo) { + return (this.toPublic().hash(algo)); +}; + +PrivateKey.prototype.toPublic = function () { + if (this._pubCache) + return (this._pubCache); + + var algInfo = algs.info[this.type]; + var pubParts = []; + for (var i = 0; i < algInfo.parts.length; ++i) { + var p = algInfo.parts[i]; + pubParts.push(this.part[p]); + } + + this._pubCache = new Key({ + type: this.type, + source: this, + parts: pubParts + }); + if (this.comment) + this._pubCache.comment = this.comment; + return (this._pubCache); +}; + +PrivateKey.prototype.derive = function (newType) { + assert.string(newType, 'type'); + var priv, pub, pair; + + if (this.type === 'ed25519' && newType === 'curve25519') { + if (nacl === undefined) + nacl = __webpack_require__(76); + + priv = this.part.k.data; + if (priv[0] === 0x00) + priv = priv.slice(1); + + pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv)); + pub = Buffer.from(pair.publicKey); + + return (new PrivateKey({ + type: 'curve25519', + parts: [ + { name: 'A', data: utils.mpNormalize(pub) }, + { name: 'k', data: utils.mpNormalize(priv) } + ] + })); + } else if (this.type === 'curve25519' && newType === 'ed25519') { + if (nacl === undefined) + nacl = __webpack_require__(76); + + priv = this.part.k.data; + if (priv[0] === 0x00) + priv = priv.slice(1); + + pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv)); + pub = Buffer.from(pair.publicKey); + + return (new PrivateKey({ + type: 'ed25519', + parts: [ + { name: 'A', data: utils.mpNormalize(pub) }, + { name: 'k', data: utils.mpNormalize(priv) } + ] + })); + } + throw (new Error('Key derivation not supported from ' + this.type + + ' to ' + newType)); +}; + +PrivateKey.prototype.createVerify = function (hashAlgo) { + return (this.toPublic().createVerify(hashAlgo)); +}; + +PrivateKey.prototype.createSign = function (hashAlgo) { + if (hashAlgo === undefined) + hashAlgo = this.defaultHashAlgorithm(); + assert.string(hashAlgo, 'hash algorithm'); + + /* ED25519 is not supported by OpenSSL, use a javascript impl. */ + if (this.type === 'ed25519' && edCompat !== undefined) + return (new edCompat.Signer(this, hashAlgo)); + if (this.type === 'curve25519') + throw (new Error('Curve25519 keys are not suitable for ' + + 'signing or verification')); + + var v, nm, err; + try { + nm = hashAlgo.toUpperCase(); + v = crypto.createSign(nm); + } catch (e) { + err = e; + } + if (v === undefined || (err instanceof Error && + err.message.match(/Unknown message digest/))) { + nm = 'RSA-'; + nm += hashAlgo.toUpperCase(); + v = crypto.createSign(nm); + } + assert.ok(v, 'failed to create verifier'); + var oldSign = v.sign.bind(v); + var key = this.toBuffer('pkcs1'); + var type = this.type; + var curve = this.curve; + v.sign = function () { + var sig = oldSign(key); + if (typeof (sig) === 'string') + sig = Buffer.from(sig, 'binary'); + sig = Signature.parse(sig, type, 'asn1'); + sig.hashAlgorithm = hashAlgo; + sig.curve = curve; + return (sig); + }; + return (v); +}; + +PrivateKey.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; + + assert.object(formats[format], 'formats[format]'); + + try { + var k = formats[format].read(data, options); + assert.ok(k instanceof PrivateKey, 'key is not a private key'); + if (!k.comment) + k.comment = options.filename; + return (k); + } catch (e) { + if (e.name === 'KeyEncryptedError') + throw (e); + throw (new KeyParseError(options.filename, format, e)); + } +}; + +PrivateKey.isPrivateKey = function (obj, ver) { + return (utils.isCompatible(obj, PrivateKey, ver)); +}; + +PrivateKey.generate = function (type, options) { + if (options === undefined) + options = {}; + assert.object(options, 'options'); + + switch (type) { + case 'ecdsa': + if (options.curve === undefined) + options.curve = 'nistp256'; + assert.string(options.curve, 'options.curve'); + return (generateECDSA(options.curve)); + case 'ed25519': + return (generateED25519()); + default: + throw (new Error('Key generation not supported with key ' + + 'type "' + type + '"')); + } +}; + +/* + * API versions for PrivateKey: + * [1,0] -- initial ver + * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats + * [1,2] -- added defaultHashAlgorithm + * [1,3] -- added derive, ed, createDH + * [1,4] -- first tagged version + * [1,5] -- changed ed25519 part names and format + */ +PrivateKey.prototype._sshpkApiVersion = [1, 5]; + +PrivateKey._oldVersionDetect = function (obj) { + assert.func(obj.toPublic); + assert.func(obj.createSign); + if (obj.derive) + return ([1, 3]); + if (obj.defaultHashAlgorithm) + return ([1, 2]); + if (obj.formats['auto']) + return ([1, 1]); + return ([1, 0]); +}; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.wrapLifecycle = exports.run = exports.install = exports.Install = undefined; + +var _extends2; + +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(22)); +} + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); +} + +let install = exports.install = (() => { + var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, lockfile) { + yield wrapLifecycle(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const install = new Install(flags, config, reporter, lockfile); + yield install.init(); + })); + }); + + return function install(_x7, _x8, _x9, _x10) { + return _ref29.apply(this, arguments); + }; +})(); + +let run = exports.run = (() => { + var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let lockfile; + let error = 'installCommandRenamed'; + if (flags.lockfile === false) { + lockfile = new (_lockfile || _load_lockfile()).default(); + } else { + lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); + } + + if (args.length) { + const exampleArgs = args.slice(); + + if (flags.saveDev) { + exampleArgs.push('--dev'); + } + if (flags.savePeer) { + exampleArgs.push('--peer'); + } + if (flags.saveOptional) { + exampleArgs.push('--optional'); + } + if (flags.saveExact) { + exampleArgs.push('--exact'); + } + if (flags.saveTilde) { + exampleArgs.push('--tilde'); + } + let command = 'add'; + if (flags.global) { + error = 'globalFlagRemoved'; + command = 'global add'; + } + throw new (_errors || _load_errors()).MessageError(reporter.lang(error, `yarn ${command} ${exampleArgs.join(' ')}`)); + } + + yield install(config, reporter, flags, lockfile); + }); + + return function run(_x11, _x12, _x13, _x14) { + return _ref31.apply(this, arguments); + }; +})(); + +let wrapLifecycle = exports.wrapLifecycle = (() => { + var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags, factory) { + yield config.executeLifecycleScript('preinstall'); + + yield factory(); + + // npm behaviour, seems kinda funky but yay compatibility + yield config.executeLifecycleScript('install'); + yield config.executeLifecycleScript('postinstall'); + + if (!config.production) { + if (!config.disablePrepublish) { + yield config.executeLifecycleScript('prepublish'); + } + yield config.executeLifecycleScript('prepare'); + } + }); + + return function wrapLifecycle(_x15, _x16, _x17) { + return _ref32.apply(this, arguments); + }; +})(); + +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; + +var _objectPath; + +function _load_objectPath() { + return _objectPath = _interopRequireDefault(__webpack_require__(304)); +} + +var _hooks; + +function _load_hooks() { + return _hooks = __webpack_require__(374); +} + +var _index; + +function _load_index() { + return _index = _interopRequireDefault(__webpack_require__(220)); +} + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(6); +} + +var _integrityChecker; + +function _load_integrityChecker() { + return _integrityChecker = _interopRequireDefault(__webpack_require__(208)); +} + +var _lockfile; + +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(19)); +} + +var _lockfile2; + +function _load_lockfile2() { + return _lockfile2 = __webpack_require__(19); +} + +var _packageFetcher; + +function _load_packageFetcher() { + return _packageFetcher = _interopRequireWildcard(__webpack_require__(210)); +} + +var _packageInstallScripts; + +function _load_packageInstallScripts() { + return _packageInstallScripts = _interopRequireDefault(__webpack_require__(557)); +} + +var _packageCompatibility; + +function _load_packageCompatibility() { + return _packageCompatibility = _interopRequireWildcard(__webpack_require__(209)); +} + +var _packageResolver; + +function _load_packageResolver() { + return _packageResolver = _interopRequireDefault(__webpack_require__(366)); +} + +var _packageLinker; + +function _load_packageLinker() { + return _packageLinker = _interopRequireDefault(__webpack_require__(211)); +} + +var _index2; + +function _load_index2() { + return _index2 = __webpack_require__(57); +} + +var _index3; + +function _load_index3() { + return _index3 = __webpack_require__(78); +} + +var _autoclean; + +function _load_autoclean() { + return _autoclean = __webpack_require__(354); +} + +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(8)); +} + +var _normalizePattern; + +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(37); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +var _map; + +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(29)); +} + +var _yarnVersion; + +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(120); +} + +var _generatePnpMap; + +function _load_generatePnpMap() { + return _generatePnpMap = __webpack_require__(579); +} + +var _workspaceLayout; + +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(90)); +} + +var _resolutionMap; + +function _load_resolutionMap() { + return _resolutionMap = _interopRequireDefault(__webpack_require__(214)); +} + +var _guessName; + +function _load_guessName() { + return _guessName = _interopRequireDefault(__webpack_require__(169)); +} + +var _audit; + +function _load_audit() { + return _audit = _interopRequireDefault(__webpack_require__(353)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const deepEqual = __webpack_require__(631); + +const emoji = __webpack_require__(302); +const invariant = __webpack_require__(9); +const path = __webpack_require__(0); +const semver = __webpack_require__(21); +const uuid = __webpack_require__(119); +const ssri = __webpack_require__(65); + +const ONE_DAY = 1000 * 60 * 60 * 24; + +/** + * Try and detect the installation method for Yarn and provide a command to update it with. + */ + +function getUpdateCommand(installationMethod) { + if (installationMethod === 'tar') { + return `curl --compressed -o- -L ${(_constants || _load_constants()).YARN_INSTALLER_SH} | bash`; + } + + if (installationMethod === 'homebrew') { + return 'brew upgrade yarn'; + } + + if (installationMethod === 'deb') { + return 'sudo apt-get update && sudo apt-get install yarn'; + } + + if (installationMethod === 'rpm') { + return 'sudo yum install yarn'; + } + + if (installationMethod === 'npm') { + return 'npm install --global yarn'; + } + + if (installationMethod === 'chocolatey') { + return 'choco upgrade yarn'; + } + + if (installationMethod === 'apk') { + return 'apk update && apk add -u yarn'; + } + + if (installationMethod === 'portage') { + return 'sudo emerge --sync && sudo emerge -au sys-apps/yarn'; + } + + return null; +} + +function getUpdateInstaller(installationMethod) { + // Windows + if (installationMethod === 'msi') { + return (_constants || _load_constants()).YARN_INSTALLER_MSI; + } + + return null; +} + +function normalizeFlags(config, rawFlags) { + const flags = { + // install + har: !!rawFlags.har, + ignorePlatform: !!rawFlags.ignorePlatform, + ignoreEngines: !!rawFlags.ignoreEngines, + ignoreScripts: !!rawFlags.ignoreScripts, + ignoreOptional: !!rawFlags.ignoreOptional, + force: !!rawFlags.force, + flat: !!rawFlags.flat, + lockfile: rawFlags.lockfile !== false, + pureLockfile: !!rawFlags.pureLockfile, + updateChecksums: !!rawFlags.updateChecksums, + skipIntegrityCheck: !!rawFlags.skipIntegrityCheck, + frozenLockfile: !!rawFlags.frozenLockfile, + linkDuplicates: !!rawFlags.linkDuplicates, + checkFiles: !!rawFlags.checkFiles, + audit: !!rawFlags.audit, + + // add + peer: !!rawFlags.peer, + dev: !!rawFlags.dev, + optional: !!rawFlags.optional, + exact: !!rawFlags.exact, + tilde: !!rawFlags.tilde, + ignoreWorkspaceRootCheck: !!rawFlags.ignoreWorkspaceRootCheck, + + // outdated, update-interactive + includeWorkspaceDeps: !!rawFlags.includeWorkspaceDeps, + + // add, remove, update + workspaceRootIsCwd: rawFlags.workspaceRootIsCwd !== false + }; + + if (config.getOption('ignore-scripts')) { + flags.ignoreScripts = true; + } + + if (config.getOption('ignore-platform')) { + flags.ignorePlatform = true; + } + + if (config.getOption('ignore-engines')) { + flags.ignoreEngines = true; + } + + if (config.getOption('ignore-optional')) { + flags.ignoreOptional = true; + } + + if (config.getOption('force')) { + flags.force = true; + } + + return flags; +} + +class Install { + constructor(flags, config, reporter, lockfile) { + this.rootManifestRegistries = []; + this.rootPatternsToOrigin = (0, (_map || _load_map()).default)(); + this.lockfile = lockfile; + this.reporter = reporter; + this.config = config; + this.flags = normalizeFlags(config, flags); + this.resolutions = (0, (_map || _load_map()).default)(); // Legacy resolutions field used for flat install mode + this.resolutionMap = new (_resolutionMap || _load_resolutionMap()).default(config); // Selective resolutions for nested dependencies + this.resolver = new (_packageResolver || _load_packageResolver()).default(config, lockfile, this.resolutionMap); + this.integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); + this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); + this.scripts = new (_packageInstallScripts || _load_packageInstallScripts()).default(config, this.resolver, this.flags.force); + } + + /** + * Create a list of dependency requests from the current directories manifests. + */ + + fetchRequestFromCwd(excludePatterns = [], ignoreUnusedPatterns = false) { + var _this = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const patterns = []; + const deps = []; + let resolutionDeps = []; + const manifest = {}; + + const ignorePatterns = []; + const usedPatterns = []; + let workspaceLayout; + + // some commands should always run in the context of the entire workspace + const cwd = _this.flags.includeWorkspaceDeps || _this.flags.workspaceRootIsCwd ? _this.config.lockfileFolder : _this.config.cwd; + + // non-workspaces are always root, otherwise check for workspace root + const cwdIsRoot = !_this.config.workspaceRootFolder || _this.config.lockfileFolder === cwd; + + // exclude package names that are in install args + const excludeNames = []; + for (var _iterator = excludePatterns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + const pattern = _ref; + + if ((0, (_index3 || _load_index3()).getExoticResolver)(pattern)) { + excludeNames.push((0, (_guessName || _load_guessName()).default)(pattern)); + } else { + // extract the name + const parts = (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern); + excludeNames.push(parts.name); + } + } + + const stripExcluded = function stripExcluded(manifest) { + for (var _iterator2 = excludeNames, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + const exclude = _ref2; + + if (manifest.dependencies && manifest.dependencies[exclude]) { + delete manifest.dependencies[exclude]; + } + if (manifest.devDependencies && manifest.devDependencies[exclude]) { + delete manifest.devDependencies[exclude]; + } + if (manifest.optionalDependencies && manifest.optionalDependencies[exclude]) { + delete manifest.optionalDependencies[exclude]; + } + } + }; + + for (var _iterator3 = Object.keys((_index2 || _load_index2()).registries), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + const registry = _ref3; + + const filename = (_index2 || _load_index2()).registries[registry].filename; + + const loc = path.join(cwd, filename); + if (!(yield (_fs || _load_fs()).exists(loc))) { + continue; + } + + _this.rootManifestRegistries.push(registry); + + const projectManifestJson = yield _this.config.readJson(loc); + yield (0, (_index || _load_index()).default)(projectManifestJson, cwd, _this.config, cwdIsRoot); + + Object.assign(_this.resolutions, projectManifestJson.resolutions); + Object.assign(manifest, projectManifestJson); + + _this.resolutionMap.init(_this.resolutions); + for (var _iterator4 = Object.keys(_this.resolutionMap.resolutionsByPackage), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + const packageName = _ref4; + + const optional = (_objectPath || _load_objectPath()).default.has(manifest.optionalDependencies, packageName) && _this.flags.ignoreOptional; + for (var _iterator8 = _this.resolutionMap.resolutionsByPackage[packageName], _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { + var _ref9; + + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref9 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref9 = _i8.value; + } + + const _ref8 = _ref9; + const pattern = _ref8.pattern; + + resolutionDeps = [...resolutionDeps, { registry, pattern, optional, hint: 'resolution' }]; + } + } + + const pushDeps = function pushDeps(depType, manifest, { hint, optional }, isUsed) { + if (ignoreUnusedPatterns && !isUsed) { + return; + } + // We only take unused dependencies into consideration to get deterministic hoisting. + // Since flat mode doesn't care about hoisting and everything is top level and specified then we can safely + // leave these out. + if (_this.flags.flat && !isUsed) { + return; + } + const depMap = manifest[depType]; + for (const name in depMap) { + if (excludeNames.indexOf(name) >= 0) { + continue; + } + + let pattern = name; + if (!_this.lockfile.getLocked(pattern)) { + // when we use --save we save the dependency to the lockfile with just the name rather than the + // version combo + pattern += '@' + depMap[name]; + } + + // normalization made sure packages are mentioned only once + if (isUsed) { + usedPatterns.push(pattern); + } else { + ignorePatterns.push(pattern); + } + + _this.rootPatternsToOrigin[pattern] = depType; + patterns.push(pattern); + deps.push({ pattern, registry, hint, optional, workspaceName: manifest.name, workspaceLoc: manifest._loc }); + } + }; + + if (cwdIsRoot) { + pushDeps('dependencies', projectManifestJson, { hint: null, optional: false }, true); + pushDeps('devDependencies', projectManifestJson, { hint: 'dev', optional: false }, !_this.config.production); + pushDeps('optionalDependencies', projectManifestJson, { hint: 'optional', optional: true }, true); + } + + if (_this.config.workspaceRootFolder) { + const workspaceLoc = cwdIsRoot ? loc : path.join(_this.config.lockfileFolder, filename); + const workspacesRoot = path.dirname(workspaceLoc); + + let workspaceManifestJson = projectManifestJson; + if (!cwdIsRoot) { + // the manifest we read before was a child workspace, so get the root + workspaceManifestJson = yield _this.config.readJson(workspaceLoc); + yield (0, (_index || _load_index()).default)(workspaceManifestJson, workspacesRoot, _this.config, true); + } + + const workspaces = yield _this.config.resolveWorkspaces(workspacesRoot, workspaceManifestJson); + workspaceLayout = new (_workspaceLayout || _load_workspaceLayout()).default(workspaces, _this.config); + + // add virtual manifest that depends on all workspaces, this way package hoisters and resolvers will work fine + const workspaceDependencies = (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.dependencies); + for (var _iterator5 = Object.keys(workspaces), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + const workspaceName = _ref5; + + const workspaceManifest = workspaces[workspaceName].manifest; + workspaceDependencies[workspaceName] = workspaceManifest.version; + + // include dependencies from all workspaces + if (_this.flags.includeWorkspaceDeps) { + pushDeps('dependencies', workspaceManifest, { hint: null, optional: false }, true); + pushDeps('devDependencies', workspaceManifest, { hint: 'dev', optional: false }, !_this.config.production); + pushDeps('optionalDependencies', workspaceManifest, { hint: 'optional', optional: true }, true); + } + } + const virtualDependencyManifest = { + _uid: '', + name: `workspace-aggregator-${uuid.v4()}`, + version: '1.0.0', + _registry: 'npm', + _loc: workspacesRoot, + dependencies: workspaceDependencies, + devDependencies: (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.devDependencies), + optionalDependencies: (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.optionalDependencies), + private: workspaceManifestJson.private, + workspaces: workspaceManifestJson.workspaces + }; + workspaceLayout.virtualManifestName = virtualDependencyManifest.name; + const virtualDep = {}; + virtualDep[virtualDependencyManifest.name] = virtualDependencyManifest.version; + workspaces[virtualDependencyManifest.name] = { loc: workspacesRoot, manifest: virtualDependencyManifest }; + + // ensure dependencies that should be excluded are stripped from the correct manifest + stripExcluded(cwdIsRoot ? virtualDependencyManifest : workspaces[projectManifestJson.name].manifest); + + pushDeps('workspaces', { workspaces: virtualDep }, { hint: 'workspaces', optional: false }, true); + + const implicitWorkspaceDependencies = (0, (_extends2 || _load_extends()).default)({}, workspaceDependencies); + + for (var _iterator6 = (_constants || _load_constants()).OWNED_DEPENDENCY_TYPES, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { + var _ref6; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } + + const type = _ref6; + + for (var _iterator7 = Object.keys(projectManifestJson[type] || {}), _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { + var _ref7; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } + + const dependencyName = _ref7; + + delete implicitWorkspaceDependencies[dependencyName]; + } + } + + pushDeps('dependencies', { dependencies: implicitWorkspaceDependencies }, { hint: 'workspaces', optional: false }, true); + } + + break; + } + + // inherit root flat flag + if (manifest.flat) { + _this.flags.flat = true; + } + + return { + requests: [...resolutionDeps, ...deps], + patterns, + manifest, + usedPatterns, + ignorePatterns, + workspaceLayout + }; + })(); + } + + /** + * TODO description + */ + + prepareRequests(requests) { + return requests; + } + + preparePatterns(patterns) { + return patterns; + } + preparePatternsForLinking(patterns, cwdManifest, cwdIsRoot) { + return patterns; + } + + prepareManifests() { + var _this2 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const manifests = yield _this2.config.getRootManifests(); + return manifests; + })(); + } + + bailout(patterns, workspaceLayout) { + var _this3 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // We don't want to skip the audit - it could yield important errors + if (_this3.flags.audit) { + return false; + } + // PNP is so fast that the integrity check isn't pertinent + if (_this3.config.plugnplayEnabled) { + return false; + } + if (_this3.flags.skipIntegrityCheck || _this3.flags.force) { + return false; + } + const lockfileCache = _this3.lockfile.cache; + if (!lockfileCache) { + return false; + } + const lockfileClean = _this3.lockfile.parseResultType === 'success'; + const match = yield _this3.integrityChecker.check(patterns, lockfileCache, _this3.flags, workspaceLayout); + if (_this3.flags.frozenLockfile && (!lockfileClean || match.missingPatterns.length > 0)) { + throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('frozenLockfileError')); + } + + const haveLockfile = yield (_fs || _load_fs()).exists(path.join(_this3.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME)); + + const lockfileIntegrityPresent = !_this3.lockfile.hasEntriesExistWithoutIntegrity(); + const integrityBailout = lockfileIntegrityPresent || !_this3.config.autoAddIntegrity; + + if (match.integrityMatches && haveLockfile && lockfileClean && integrityBailout) { + _this3.reporter.success(_this3.reporter.lang('upToDate')); + return true; + } + + if (match.integrityFileMissing && haveLockfile) { + // Integrity file missing, force script installations + _this3.scripts.setForce(true); + return false; + } + + if (match.hardRefreshRequired) { + // e.g. node version doesn't match, force script installations + _this3.scripts.setForce(true); + return false; + } + + if (!patterns.length && !match.integrityFileMissing) { + _this3.reporter.success(_this3.reporter.lang('nothingToInstall')); + yield _this3.createEmptyManifestFolders(); + yield _this3.saveLockfileAndIntegrity(patterns, workspaceLayout); + return true; + } + + return false; + })(); + } + + /** + * Produce empty folders for all used root manifests. + */ + + createEmptyManifestFolders() { + var _this4 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this4.config.modulesFolder) { + // already created + return; + } + + for (var _iterator9 = _this4.rootManifestRegistries, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { + var _ref10; + + if (_isArray9) { + if (_i9 >= _iterator9.length) break; + _ref10 = _iterator9[_i9++]; + } else { + _i9 = _iterator9.next(); + if (_i9.done) break; + _ref10 = _i9.value; + } + + const registryName = _ref10; + const folder = _this4.config.registries[registryName].folder; + + yield (_fs || _load_fs()).mkdirp(path.join(_this4.config.lockfileFolder, folder)); + } + })(); + } + + /** + * TODO description + */ + + markIgnored(patterns) { + for (var _iterator10 = patterns, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { + var _ref11; + + if (_isArray10) { + if (_i10 >= _iterator10.length) break; + _ref11 = _iterator10[_i10++]; + } else { + _i10 = _iterator10.next(); + if (_i10.done) break; + _ref11 = _i10.value; + } + + const pattern = _ref11; + + const manifest = this.resolver.getStrictResolvedPattern(pattern); + const ref = manifest._reference; + invariant(ref, 'expected package reference'); + + // just mark the package as ignored. if the package is used by a required package, the hoister + // will take care of that. + ref.ignore = true; + } + } + + /** + * helper method that gets only recent manifests + * used by global.ls command + */ + getFlattenedDeps() { + var _this5 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref12 = yield _this5.fetchRequestFromCwd(); + + const depRequests = _ref12.requests, + rawPatterns = _ref12.patterns; + + + yield _this5.resolver.init(depRequests, {}); + + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this5.resolver.getManifests(), _this5.config); + _this5.resolver.updateManifests(manifests); + + return _this5.flatten(rawPatterns); + })(); + } + + /** + * TODO description + */ + + init() { + var _this6 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.checkUpdate(); + + // warn if we have a shrinkwrap + if (yield (_fs || _load_fs()).exists(path.join(_this6.config.lockfileFolder, (_constants || _load_constants()).NPM_SHRINKWRAP_FILENAME))) { + _this6.reporter.warn(_this6.reporter.lang('shrinkwrapWarning')); + } + + // warn if we have an npm lockfile + if (yield (_fs || _load_fs()).exists(path.join(_this6.config.lockfileFolder, (_constants || _load_constants()).NPM_LOCK_FILENAME))) { + _this6.reporter.warn(_this6.reporter.lang('npmLockfileWarning')); + } + + if (_this6.config.plugnplayEnabled) { + _this6.reporter.info(_this6.reporter.lang('plugnplaySuggestV2L1')); + _this6.reporter.info(_this6.reporter.lang('plugnplaySuggestV2L2')); + } + + let flattenedTopLevelPatterns = []; + const steps = []; + + var _ref13 = yield _this6.fetchRequestFromCwd(); + + const depRequests = _ref13.requests, + rawPatterns = _ref13.patterns, + ignorePatterns = _ref13.ignorePatterns, + workspaceLayout = _ref13.workspaceLayout, + manifest = _ref13.manifest; + + let topLevelPatterns = []; + + const artifacts = yield _this6.integrityChecker.getArtifacts(); + if (artifacts) { + _this6.linker.setArtifacts(artifacts); + _this6.scripts.setArtifacts(artifacts); + } + + if ((_packageCompatibility || _load_packageCompatibility()).shouldCheck(manifest, _this6.flags)) { + steps.push((() => { + var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this6.reporter.step(curr, total, _this6.reporter.lang('checkingManifest'), emoji.get('mag')); + yield _this6.checkCompatibility(); + }); + + return function (_x, _x2) { + return _ref14.apply(this, arguments); + }; + })()); + } + + const audit = new (_audit || _load_audit()).default(_this6.config, _this6.reporter, { groups: (_constants || _load_constants()).OWNED_DEPENDENCY_TYPES }); + let auditFoundProblems = false; + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('resolveStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.reporter.step(curr, total, _this6.reporter.lang('resolvingPackages'), emoji.get('mag')); + yield _this6.resolver.init(_this6.prepareRequests(depRequests), { + isFlat: _this6.flags.flat, + isFrozen: _this6.flags.frozenLockfile, + workspaceLayout + }); + topLevelPatterns = _this6.preparePatterns(rawPatterns); + flattenedTopLevelPatterns = yield _this6.flatten(topLevelPatterns); + return { bailout: !_this6.flags.audit && (yield _this6.bailout(topLevelPatterns, workspaceLayout)) }; + })); + }); + + if (_this6.flags.audit) { + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('auditStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.reporter.step(curr, total, _this6.reporter.lang('auditRunning'), emoji.get('mag')); + if (_this6.flags.offline) { + _this6.reporter.warn(_this6.reporter.lang('auditOffline')); + return { bailout: false }; + } + const preparedManifests = yield _this6.prepareManifests(); + // $FlowFixMe - Flow considers `m` in the map operation to be "mixed", so does not recognize `m.object` + const mergedManifest = Object.assign({}, ...Object.values(preparedManifests).map(function (m) { + return m.object; + })); + const auditVulnerabilityCounts = yield audit.performAudit(mergedManifest, _this6.lockfile, _this6.resolver, _this6.linker, topLevelPatterns); + auditFoundProblems = auditVulnerabilityCounts.info || auditVulnerabilityCounts.low || auditVulnerabilityCounts.moderate || auditVulnerabilityCounts.high || auditVulnerabilityCounts.critical; + return { bailout: yield _this6.bailout(topLevelPatterns, workspaceLayout) }; + })); + }); + } + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('fetchStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.markIgnored(ignorePatterns); + _this6.reporter.step(curr, total, _this6.reporter.lang('fetchingPackages'), emoji.get('truck')); + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this6.resolver.getManifests(), _this6.config); + _this6.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this6.resolver.getManifests(), _this6.config, _this6.flags.ignoreEngines); + })); + }); + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('linkStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // remove integrity hash to make this operation atomic + yield _this6.integrityChecker.removeIntegrityFile(); + _this6.reporter.step(curr, total, _this6.reporter.lang('linkingDependencies'), emoji.get('link')); + flattenedTopLevelPatterns = _this6.preparePatternsForLinking(flattenedTopLevelPatterns, manifest, _this6.config.lockfileFolder === _this6.config.cwd); + yield _this6.linker.init(flattenedTopLevelPatterns, workspaceLayout, { + linkDuplicates: _this6.flags.linkDuplicates, + ignoreOptional: _this6.flags.ignoreOptional + }); + })); + }); + + if (_this6.config.plugnplayEnabled) { + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('pnpStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const pnpPath = `${_this6.config.lockfileFolder}/${(_constants || _load_constants()).PNP_FILENAME}`; + + const code = yield (0, (_generatePnpMap || _load_generatePnpMap()).generatePnpMap)(_this6.config, flattenedTopLevelPatterns, { + resolver: _this6.resolver, + reporter: _this6.reporter, + targetPath: pnpPath, + workspaceLayout + }); + + try { + const file = yield (_fs || _load_fs()).readFile(pnpPath); + if (file === code) { + return; + } + } catch (error) {} + + yield (_fs || _load_fs()).writeFile(pnpPath, code); + yield (_fs || _load_fs()).chmod(pnpPath, 0o755); + })); + }); + } + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('buildStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.reporter.step(curr, total, _this6.flags.force ? _this6.reporter.lang('rebuildingPackages') : _this6.reporter.lang('buildingFreshPackages'), emoji.get('hammer')); + + if (_this6.config.ignoreScripts) { + _this6.reporter.warn(_this6.reporter.lang('ignoredScripts')); + } else { + yield _this6.scripts.init(flattenedTopLevelPatterns); + } + })); + }); + + if (_this6.flags.har) { + steps.push((() => { + var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + const formattedDate = new Date().toISOString().replace(/:/g, '-'); + const filename = `yarn-install_${formattedDate}.har`; + _this6.reporter.step(curr, total, _this6.reporter.lang('savingHar', filename), emoji.get('black_circle_for_record')); + yield _this6.config.requestManager.saveHar(filename); + }); + + return function (_x3, _x4) { + return _ref21.apply(this, arguments); + }; + })()); + } + + if (yield _this6.shouldClean()) { + steps.push((() => { + var _ref22 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this6.reporter.step(curr, total, _this6.reporter.lang('cleaningModules'), emoji.get('recycle')); + yield (0, (_autoclean || _load_autoclean()).clean)(_this6.config, _this6.reporter); + }); + + return function (_x5, _x6) { + return _ref22.apply(this, arguments); + }; + })()); + } + + let currentStep = 0; + for (var _iterator11 = steps, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { + var _ref23; + + if (_isArray11) { + if (_i11 >= _iterator11.length) break; + _ref23 = _iterator11[_i11++]; + } else { + _i11 = _iterator11.next(); + if (_i11.done) break; + _ref23 = _i11.value; + } + + const step = _ref23; + + const stepResult = yield step(++currentStep, steps.length); + if (stepResult && stepResult.bailout) { + if (_this6.flags.audit) { + audit.summary(); + } + if (auditFoundProblems) { + _this6.reporter.warn(_this6.reporter.lang('auditRunAuditForDetails')); + } + _this6.maybeOutputUpdate(); + return flattenedTopLevelPatterns; + } + } + + // fin! + if (_this6.flags.audit) { + audit.summary(); + } + if (auditFoundProblems) { + _this6.reporter.warn(_this6.reporter.lang('auditRunAuditForDetails')); + } + yield _this6.saveLockfileAndIntegrity(topLevelPatterns, workspaceLayout); + yield _this6.persistChanges(); + _this6.maybeOutputUpdate(); + _this6.config.requestManager.clearCache(); + return flattenedTopLevelPatterns; + })(); + } + + checkCompatibility() { + var _this7 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref24 = yield _this7.fetchRequestFromCwd(); + + const manifest = _ref24.manifest; + + yield (_packageCompatibility || _load_packageCompatibility()).checkOne(manifest, _this7.config, _this7.flags.ignoreEngines); + })(); + } + + persistChanges() { + var _this8 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // get all the different registry manifests in this folder + const manifests = yield _this8.config.getRootManifests(); + + if (yield _this8.applyChanges(manifests)) { + yield _this8.config.saveRootManifests(manifests); + } + })(); + } + + applyChanges(manifests) { + let hasChanged = false; + + if (this.config.plugnplayPersist) { + const object = manifests.npm.object; + + + if (typeof object.installConfig !== 'object') { + object.installConfig = {}; + } + + if (this.config.plugnplayEnabled && object.installConfig.pnp !== true) { + object.installConfig.pnp = true; + hasChanged = true; + } else if (!this.config.plugnplayEnabled && typeof object.installConfig.pnp !== 'undefined') { + delete object.installConfig.pnp; + hasChanged = true; + } + + if (Object.keys(object.installConfig).length === 0) { + delete object.installConfig; + } + } + + return Promise.resolve(hasChanged); + } + + /** + * Check if we should run the cleaning step. + */ + + shouldClean() { + return (_fs || _load_fs()).exists(path.join(this.config.lockfileFolder, (_constants || _load_constants()).CLEAN_FILENAME)); + } + + /** + * TODO + */ + + flatten(patterns) { + var _this9 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (!_this9.flags.flat) { + return patterns; + } + + const flattenedPatterns = []; + + for (var _iterator12 = _this9.resolver.getAllDependencyNamesByLevelOrder(patterns), _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { + var _ref25; + + if (_isArray12) { + if (_i12 >= _iterator12.length) break; + _ref25 = _iterator12[_i12++]; + } else { + _i12 = _iterator12.next(); + if (_i12.done) break; + _ref25 = _i12.value; + } + + const name = _ref25; + + const infos = _this9.resolver.getAllInfoForPackageName(name).filter(function (manifest) { + const ref = manifest._reference; + invariant(ref, 'expected package reference'); + return !ref.ignore; + }); + + if (infos.length === 0) { + continue; + } + + if (infos.length === 1) { + // single version of this package + // take out a single pattern as multiple patterns may have resolved to this package + flattenedPatterns.push(_this9.resolver.patternsByPackage[name][0]); + continue; + } + + const options = infos.map(function (info) { + const ref = info._reference; + invariant(ref, 'expected reference'); + return { + // TODO `and is required by {PARENT}`, + name: _this9.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version), + + value: info.version + }; + }); + const versions = infos.map(function (info) { + return info.version; + }); + let version; + + const resolutionVersion = _this9.resolutions[name]; + if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) { + // use json `resolution` version + version = resolutionVersion; + } else { + version = yield _this9.reporter.select(_this9.reporter.lang('manualVersionResolution', name), _this9.reporter.lang('answer'), options); + _this9.resolutions[name] = version; + } + + flattenedPatterns.push(_this9.resolver.collapseAllVersionsOfPackage(name, version)); + } + + // save resolutions to their appropriate root manifest + if (Object.keys(_this9.resolutions).length) { + const manifests = yield _this9.config.getRootManifests(); + + for (const name in _this9.resolutions) { + const version = _this9.resolutions[name]; + + const patterns = _this9.resolver.patternsByPackage[name]; + if (!patterns) { + continue; + } + + let manifest; + for (var _iterator13 = patterns, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { + var _ref26; + + if (_isArray13) { + if (_i13 >= _iterator13.length) break; + _ref26 = _iterator13[_i13++]; + } else { + _i13 = _iterator13.next(); + if (_i13.done) break; + _ref26 = _i13.value; + } + + const pattern = _ref26; + + manifest = _this9.resolver.getResolvedPattern(pattern); + if (manifest) { + break; + } + } + invariant(manifest, 'expected manifest'); + + const ref = manifest._reference; + invariant(ref, 'expected reference'); + + const object = manifests[ref.registry].object; + object.resolutions = object.resolutions || {}; + object.resolutions[name] = version; + } + + yield _this9.config.saveRootManifests(manifests); + } + + return flattenedPatterns; + })(); + } + + /** + * Remove offline tarballs that are no longer required + */ + + pruneOfflineMirror(lockfile) { + var _this10 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const mirror = _this10.config.getOfflineMirrorPath(); + if (!mirror) { + return; + } + + const requiredTarballs = new Set(); + for (const dependency in lockfile) { + const resolved = lockfile[dependency].resolved; + if (resolved) { + const basename = path.basename(resolved.split('#')[0]); + if (dependency[0] === '@' && basename[0] !== '@') { + requiredTarballs.add(`${dependency.split('/')[0]}-${basename}`); + } + requiredTarballs.add(basename); + } + } + + const mirrorFiles = yield (_fs || _load_fs()).walk(mirror); + for (var _iterator14 = mirrorFiles, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { + var _ref27; + + if (_isArray14) { + if (_i14 >= _iterator14.length) break; + _ref27 = _iterator14[_i14++]; + } else { + _i14 = _iterator14.next(); + if (_i14.done) break; + _ref27 = _i14.value; + } + + const file = _ref27; + + const isTarball = path.extname(file.basename) === '.tgz'; + // if using experimental-pack-script-packages-in-mirror flag, don't unlink prebuilt packages + const hasPrebuiltPackage = file.relative.startsWith('prebuilt/'); + if (isTarball && !hasPrebuiltPackage && !requiredTarballs.has(file.basename)) { + yield (_fs || _load_fs()).unlink(file.absolute); + } + } + })(); + } + + /** + * Save updated integrity and lockfiles. + */ + + saveLockfileAndIntegrity(patterns, workspaceLayout) { + var _this11 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const resolvedPatterns = {}; + Object.keys(_this11.resolver.patterns).forEach(function (pattern) { + if (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern)) { + resolvedPatterns[pattern] = _this11.resolver.patterns[pattern]; + } + }); + + // TODO this code is duplicated in a few places, need a common way to filter out workspace patterns from lockfile + patterns = patterns.filter(function (p) { + return !workspaceLayout || !workspaceLayout.getManifestByPattern(p); + }); + + const lockfileBasedOnResolver = _this11.lockfile.getLockfile(resolvedPatterns); + + if (_this11.config.pruneOfflineMirror) { + yield _this11.pruneOfflineMirror(lockfileBasedOnResolver); + } + + // write integrity hash + if (!_this11.config.plugnplayEnabled) { + yield _this11.integrityChecker.save(patterns, lockfileBasedOnResolver, _this11.flags, workspaceLayout, _this11.scripts.getArtifacts()); + } + + // --no-lockfile or --pure-lockfile or --frozen-lockfile + if (_this11.flags.lockfile === false || _this11.flags.pureLockfile || _this11.flags.frozenLockfile) { + return; + } + + const lockFileHasAllPatterns = patterns.every(function (p) { + return _this11.lockfile.getLocked(p); + }); + const lockfilePatternsMatch = Object.keys(_this11.lockfile.cache || {}).every(function (p) { + return lockfileBasedOnResolver[p]; + }); + const resolverPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { + const manifest = _this11.lockfile.getLocked(pattern); + return manifest && manifest.resolved === lockfileBasedOnResolver[pattern].resolved && deepEqual(manifest.prebuiltVariants, lockfileBasedOnResolver[pattern].prebuiltVariants); + }); + const integrityPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { + const existingIntegrityInfo = lockfileBasedOnResolver[pattern].integrity; + if (!existingIntegrityInfo) { + // if this entry does not have an integrity, no need to re-write the lockfile because of it + return true; + } + const manifest = _this11.lockfile.getLocked(pattern); + if (manifest && manifest.integrity) { + const manifestIntegrity = ssri.stringify(manifest.integrity); + return manifestIntegrity === existingIntegrityInfo; + } + return false; + }); + + // remove command is followed by install with force, lockfile will be rewritten in any case then + if (!_this11.flags.force && _this11.lockfile.parseResultType === 'success' && lockFileHasAllPatterns && lockfilePatternsMatch && resolverPatternsAreSameAsInLockfile && integrityPatternsAreSameAsInLockfile && patterns.length) { + return; + } + + // build lockfile location + const loc = path.join(_this11.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME); + + // write lockfile + const lockSource = (0, (_lockfile2 || _load_lockfile2()).stringify)(lockfileBasedOnResolver, false, _this11.config.enableLockfileVersions); + yield (_fs || _load_fs()).writeFilePreservingEol(loc, lockSource); + + _this11._logSuccessSaveLockfile(); + })(); + } + + _logSuccessSaveLockfile() { + this.reporter.success(this.reporter.lang('savedLockfile')); + } + + /** + * Load the dependency graph of the current install. Only does package resolving and wont write to the cwd. + */ + hydrate(ignoreUnusedPatterns) { + var _this12 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const request = yield _this12.fetchRequestFromCwd([], ignoreUnusedPatterns); + const depRequests = request.requests, + rawPatterns = request.patterns, + ignorePatterns = request.ignorePatterns, + workspaceLayout = request.workspaceLayout; + + + yield _this12.resolver.init(depRequests, { + isFlat: _this12.flags.flat, + isFrozen: _this12.flags.frozenLockfile, + workspaceLayout + }); + yield _this12.flatten(rawPatterns); + _this12.markIgnored(ignorePatterns); + + // fetch packages, should hit cache most of the time + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this12.resolver.getManifests(), _this12.config); + _this12.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this12.resolver.getManifests(), _this12.config, _this12.flags.ignoreEngines); + + // expand minimal manifests + for (var _iterator15 = _this12.resolver.getManifests(), _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { + var _ref28; + + if (_isArray15) { + if (_i15 >= _iterator15.length) break; + _ref28 = _iterator15[_i15++]; + } else { + _i15 = _iterator15.next(); + if (_i15.done) break; + _ref28 = _i15.value; + } + + const manifest = _ref28; + + const ref = manifest._reference; + invariant(ref, 'expected reference'); + const type = ref.remote.type; + // link specifier won't ever hit cache + + let loc = ''; + if (type === 'link') { + continue; + } else if (type === 'workspace') { + if (!ref.remote.reference) { + continue; + } + loc = ref.remote.reference; + } else { + loc = _this12.config.generateModuleCachePath(ref); + } + const newPkg = yield _this12.config.readManifest(loc); + yield _this12.resolver.updateManifest(ref, newPkg); + } + + return request; + })(); + } + + /** + * Check for updates every day and output a nag message if there's a newer version. + */ + + checkUpdate() { + if (this.config.nonInteractive) { + // don't show upgrade dialog on CI or non-TTY terminals + return; + } + + // don't check if disabled + if (this.config.getOption('disable-self-update-check')) { + return; + } + + // only check for updates once a day + const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0; + if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) { + return; + } + + // don't bug for updates on tagged releases + if ((_yarnVersion || _load_yarnVersion()).version.indexOf('-') >= 0) { + return; + } + + this._checkUpdate().catch(() => { + // swallow errors + }); + } + + _checkUpdate() { + var _this13 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let latestVersion = yield _this13.config.requestManager.request({ + url: (_constants || _load_constants()).SELF_UPDATE_VERSION_URL + }); + invariant(typeof latestVersion === 'string', 'expected string'); + latestVersion = latestVersion.trim(); + if (!semver.valid(latestVersion)) { + return; + } + + // ensure we only check for updates periodically + _this13.config.registries.yarn.saveHomeConfig({ + lastUpdateCheck: Date.now() + }); + + if (semver.gt(latestVersion, (_yarnVersion || _load_yarnVersion()).version)) { + const installationMethod = yield (0, (_yarnVersion || _load_yarnVersion()).getInstallationMethod)(); + _this13.maybeOutputUpdate = function () { + _this13.reporter.warn(_this13.reporter.lang('yarnOutdated', latestVersion, (_yarnVersion || _load_yarnVersion()).version)); + + const command = getUpdateCommand(installationMethod); + if (command) { + _this13.reporter.info(_this13.reporter.lang('yarnOutdatedCommand')); + _this13.reporter.command(command); + } else { + const installer = getUpdateInstaller(installationMethod); + if (installer) { + _this13.reporter.info(_this13.reporter.lang('yarnOutdatedInstaller', installer)); + } + } + }; + } + })(); + } + + /** + * Method to override with a possible upgrade message. + */ + + maybeOutputUpdate() {} +} + +exports.Install = Install; +function hasWrapper(commander, args) { + return true; +} + +function setFlags(commander) { + commander.description('Yarn install is used to install all dependencies for a project.'); + commander.usage('install [flags]'); + commander.option('-A, --audit', 'Run vulnerability audit on installed packages'); + commander.option('-g, --global', 'DEPRECATED'); + commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`'); + commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`'); + commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`'); + commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`'); + commander.option('-E, --save-exact', 'DEPRECATED'); + commander.option('-T, --save-tilde', 'DEPRECATED'); +} + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +var isObject = __webpack_require__(52); +module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + + +/***/ }), +/* 36 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SubjectSubscriber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subject; }); +/* unused harmony export AnonymousSubject */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Observable__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Subscriber__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Subscription__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__ = __webpack_require__(189); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__SubjectSubscription__ = __webpack_require__(422); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__internal_symbol_rxSubscriber__ = __webpack_require__(321); +/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ + + + + + + + +var SubjectSubscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](SubjectSubscriber, _super); + function SubjectSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + return _this; + } + return SubjectSubscriber; +}(__WEBPACK_IMPORTED_MODULE_2__Subscriber__["a" /* Subscriber */])); + +var Subject = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](Subject, _super); + function Subject() { + var _this = _super.call(this) || this; + _this.observers = []; + _this.closed = false; + _this.isStopped = false; + _this.hasError = false; + _this.thrownError = null; + return _this; + } + Subject.prototype[__WEBPACK_IMPORTED_MODULE_6__internal_symbol_rxSubscriber__["a" /* rxSubscriber */]] = function () { + return new SubjectSubscriber(this); + }; + Subject.prototype.lift = function (operator) { + var subject = new AnonymousSubject(this, this); + subject.operator = operator; + return subject; + }; + Subject.prototype.next = function (value) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + if (!this.isStopped) { + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].next(value); + } + } + }; + Subject.prototype.error = function (err) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + this.hasError = true; + this.thrownError = err; + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].error(err); + } + this.observers.length = 0; + }; + Subject.prototype.complete = function () { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].complete(); + } + this.observers.length = 0; + }; + Subject.prototype.unsubscribe = function () { + this.isStopped = true; + this.closed = true; + this.observers = null; + }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; + Subject.prototype._subscribe = function (subscriber) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + else if (this.hasError) { + subscriber.error(this.thrownError); + return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; + } + else if (this.isStopped) { + subscriber.complete(); + return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; + } + else { + this.observers.push(subscriber); + return new __WEBPACK_IMPORTED_MODULE_5__SubjectSubscription__["a" /* SubjectSubscription */](this, subscriber); + } + }; + Subject.prototype.asObservable = function () { + var observable = new __WEBPACK_IMPORTED_MODULE_1__Observable__["a" /* Observable */](); + observable.source = this; + return observable; + }; + Subject.create = function (destination, source) { + return new AnonymousSubject(destination, source); + }; + return Subject; +}(__WEBPACK_IMPORTED_MODULE_1__Observable__["a" /* Observable */])); + +var AnonymousSubject = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](AnonymousSubject, _super); + function AnonymousSubject(destination, source) { + var _this = _super.call(this) || this; + _this.destination = destination; + _this.source = source; + return _this; + } + AnonymousSubject.prototype.next = function (value) { + var destination = this.destination; + if (destination && destination.next) { + destination.next(value); + } + }; + AnonymousSubject.prototype.error = function (err) { + var destination = this.destination; + if (destination && destination.error) { + this.destination.error(err); + } + }; + AnonymousSubject.prototype.complete = function () { + var destination = this.destination; + if (destination && destination.complete) { + this.destination.complete(); + } + }; + AnonymousSubject.prototype._subscribe = function (subscriber) { + var source = this.source; + if (source) { + return this.source.subscribe(subscriber); + } + else { + return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; + } + }; + return AnonymousSubject; +}(Subject)); + +//# sourceMappingURL=Subject.js.map + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.normalizePattern = normalizePattern; + +/** + * Explode and normalize a pattern into its name and range. + */ + +function normalizePattern(pattern) { + let hasVersion = false; + let range = 'latest'; + let name = pattern; + + // if we're a scope then remove the @ and add it back later + let isScoped = false; + if (name[0] === '@') { + isScoped = true; + name = name.slice(1); + } + + // take first part as the name + const parts = name.split('@'); + if (parts.length > 1) { + name = parts.shift(); + range = parts.join('@'); + + if (range) { + hasVersion = true; + } else { + range = '*'; + } + } + + // add back @ scope suffix + if (isScoped) { + name = `@${name}`; + } + + return { name, range, hasVersion }; +} + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license + * Lodash + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.10'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + return key == '__proto__' + ? undefined + : object[key]; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + + return result; + } + + if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + + return result; + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array == null ? 0 : array.length, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' - - diff --git a/examples/aws-analog/package.json b/examples/aws-analog/package.json deleted file mode 100644 index f56f53e377..0000000000 --- a/examples/aws-analog/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "aws-analog", - "version": "0.0.0", - "type": "module", - "engines": { - "node": ">=18.19.1" - }, - "scripts": { - "build": "ng build", - "dev": "ng serve", - "ng": "ng", - "start": "npm run dev", - "test": "ng test", - "watch": "ng build --watch --configuration development" - }, - "private": true, - "dependencies": { - "@analogjs/content": "^1.8.1", - "@analogjs/router": "^1.8.1", - "@angular/animations": "^18.0.0", - "@angular/build": "^18.0.0", - "@angular/common": "^18.0.0", - "@angular/compiler": "^18.0.0", - "@angular/core": "^18.0.0", - "@angular/forms": "^18.0.0", - "@angular/platform-browser": "^18.0.0", - "@angular/platform-browser-dynamic": "^18.0.0", - "@angular/platform-server": "^18.0.0", - "@angular/router": "^18.0.0", - "@aws-sdk/client-s3": "^3.654.0", - "@aws-sdk/s3-request-presigner": "^3.654.0", - "front-matter": "^4.0.2", - "marked": "^5.0.2", - "marked-gfm-heading-id": "^3.1.0", - "marked-highlight": "^2.0.1", - "marked-mangle": "^1.1.7", - "prismjs": "^1.29.0", - "rxjs": "~7.8.0", - "sst": "file:../../sdk/js", - "tslib": "^2.3.0", - "zone.js": "~0.14.3" - }, - "devDependencies": { - "@analogjs/platform": "^1.8.1", - "@analogjs/vite-plugin-angular": "^1.8.1", - "@analogjs/vitest-angular": "^1.8.1", - "@angular/cli": "^18.0.0", - "@angular/compiler-cli": "^18.0.0", - "jsdom": "^22.0.0", - "typescript": "~5.4.2", - "vite": "^5.0.0", - "vite-tsconfig-paths": "^4.2.0", - "vitest": "^1.3.1" - } -} diff --git a/examples/aws-analog/public/analog.svg b/examples/aws-analog/public/analog.svg deleted file mode 100644 index e4f555aa7d..0000000000 --- a/examples/aws-analog/public/analog.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-analog/public/vite.svg b/examples/aws-analog/public/vite.svg deleted file mode 100644 index e7b8dfb1b2..0000000000 --- a/examples/aws-analog/public/vite.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-analog/src/app/app.component.spec.ts b/examples/aws-analog/src/app/app.component.spec.ts deleted file mode 100644 index 9a08b4b25f..0000000000 --- a/examples/aws-analog/src/app/app.component.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { TestBed } from '@angular/core/testing'; -import { provideRouter } from '@angular/router'; -import { provideLocationMocks } from '@angular/common/testing'; - -import { AppComponent } from './app.component'; - -describe('AppComponent', () => { - beforeEach(async () => { - await TestBed.configureTestingModule({ - imports: [AppComponent], - providers: [provideRouter([]), provideLocationMocks()], - }).compileComponents(); - }); - - it('should create the app', () => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.componentInstance; - expect(app).toBeTruthy(); - }); -}); diff --git a/examples/aws-analog/src/app/app.component.ts b/examples/aws-analog/src/app/app.component.ts deleted file mode 100644 index 2e02d16044..0000000000 --- a/examples/aws-analog/src/app/app.component.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Component } from '@angular/core'; -import { RouterOutlet } from '@angular/router'; - -@Component({ - selector: 'app-root', - standalone: true, - imports: [RouterOutlet], - template: ` `, - styles: [ - ` - :host { - max-width: 1280px; - margin: 0 auto; - padding: 2rem; - text-align: center; - } - `, - ], -}) -export class AppComponent {} diff --git a/examples/aws-analog/src/app/app.config.server.ts b/examples/aws-analog/src/app/app.config.server.ts deleted file mode 100644 index 0da63b09b0..0000000000 --- a/examples/aws-analog/src/app/app.config.server.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { mergeApplicationConfig, ApplicationConfig } from '@angular/core'; -import { provideServerRendering } from '@angular/platform-server'; - -import { appConfig } from './app.config'; - -const serverConfig: ApplicationConfig = { - providers: [provideServerRendering()], -}; - -export const config = mergeApplicationConfig(appConfig, serverConfig); diff --git a/examples/aws-analog/src/app/app.config.ts b/examples/aws-analog/src/app/app.config.ts deleted file mode 100644 index a1a58ee8fc..0000000000 --- a/examples/aws-analog/src/app/app.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - provideHttpClient, - withFetch, - withInterceptors, -} from '@angular/common/http'; -import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; -import { provideClientHydration } from '@angular/platform-browser'; -import { provideFileRouter, requestContextInterceptor } from '@analogjs/router'; - -export const appConfig: ApplicationConfig = { - providers: [ - provideZoneChangeDetection({ eventCoalescing: true }), - provideFileRouter(), - provideHttpClient( - withFetch(), - withInterceptors([requestContextInterceptor]) - ), - provideClientHydration(), - ], -}; diff --git a/examples/aws-analog/src/app/pages/index.page.ts b/examples/aws-analog/src/app/pages/index.page.ts deleted file mode 100644 index 56b2cfb557..0000000000 --- a/examples/aws-analog/src/app/pages/index.page.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Component } from '@angular/core'; -import { FormsModule } from '@angular/forms'; -import { injectLoad } from '@analogjs/router'; -import { toSignal } from '@angular/core/rxjs-interop'; - -import { load } from './index.server'; - -@Component({ - selector: 'app-home', - standalone: true, - imports: [FormsModule], - template: ` -
- - -
- `, -}) -export default class HomeComponent { - data = toSignal(injectLoad(), { requireSync: true }); - - async onSubmit(event: Event): Promise { - const file = (event.target as HTMLFormElement)['file'].files?.[0]!; - - const image = await fetch(this.data().url, { - body: file, - method: 'PUT', - headers: { - 'Content-Type': file.type, - 'Content-Disposition': `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split('?')[0]; - } -} diff --git a/examples/aws-analog/src/app/pages/index.server.ts b/examples/aws-analog/src/app/pages/index.server.ts deleted file mode 100644 index a120302365..0000000000 --- a/examples/aws-analog/src/app/pages/index.server.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from 'sst'; -import { PageServerLoad } from '@analogjs/router'; -import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; -import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; - -export const load = async ({ }: PageServerLoad) => { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - // @ts-ignore: Generated on deploy - Bucket: Resource.MyBucket.name, - }); - - const url = await getSignedUrl(new S3Client({}), command); - - return { - url - }; -}; diff --git a/examples/aws-analog/src/main.server.ts b/examples/aws-analog/src/main.server.ts deleted file mode 100644 index 2b6d4d14b5..0000000000 --- a/examples/aws-analog/src/main.server.ts +++ /dev/null @@ -1,32 +0,0 @@ -import 'zone.js/node'; -import '@angular/platform-server/init'; -import { enableProdMode } from '@angular/core'; -import { bootstrapApplication } from '@angular/platform-browser'; -import { renderApplication } from '@angular/platform-server'; -import { provideServerContext } from '@analogjs/router/server'; -import { ServerContext } from '@analogjs/router/tokens'; - -import { config } from './app/app.config.server'; -import { AppComponent } from './app/app.component'; - -if (import.meta.env.PROD) { - enableProdMode(); -} - -export function bootstrap() { - return bootstrapApplication(AppComponent, config); -} - -export default async function render( - url: string, - document: string, - serverContext: ServerContext -) { - const html = await renderApplication(bootstrap, { - document, - url, - platformProviders: [provideServerContext(serverContext)], - }); - - return html; -} diff --git a/examples/aws-analog/src/main.ts b/examples/aws-analog/src/main.ts deleted file mode 100644 index e774611399..0000000000 --- a/examples/aws-analog/src/main.ts +++ /dev/null @@ -1,7 +0,0 @@ -import 'zone.js'; -import { bootstrapApplication } from '@angular/platform-browser'; - -import { AppComponent } from './app/app.component'; -import { appConfig } from './app/app.config'; - -bootstrapApplication(AppComponent, appConfig); diff --git a/examples/aws-analog/src/server/routes/v1/hello.ts b/examples/aws-analog/src/server/routes/v1/hello.ts deleted file mode 100644 index 594c5d716d..0000000000 --- a/examples/aws-analog/src/server/routes/v1/hello.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { defineEventHandler } from 'h3'; - -export default defineEventHandler(() => ({ message: 'Hello World' })); diff --git a/examples/aws-analog/src/styles.css b/examples/aws-analog/src/styles.css deleted file mode 100644 index 8e92f8fcdc..0000000000 --- a/examples/aws-analog/src/styles.css +++ /dev/null @@ -1,75 +0,0 @@ -/* You can add global styles to this file, and also import other style files */ -:root { - font-family: Inter, Avenir, Helvetica, Arial, sans-serif; - font-size: 16px; - line-height: 24px; - font-weight: 400; - - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; - - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - -webkit-text-size-adjust: 100%; -} - -a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; -} -a:hover { - color: #535bf2; -} - -body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; -} - -h1 { - font-size: 3.2em; - line-height: 1.1; -} - -button { - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; -} -button:hover { - border-color: #646cff; -} -button:focus, -button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; -} - -.card { - padding: 2em; -} - -@media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } -} diff --git a/examples/aws-analog/src/test-setup.ts b/examples/aws-analog/src/test-setup.ts deleted file mode 100644 index 318c3b9d71..0000000000 --- a/examples/aws-analog/src/test-setup.ts +++ /dev/null @@ -1,12 +0,0 @@ -import '@analogjs/vitest-angular/setup-zone'; - -import { - BrowserDynamicTestingModule, - platformBrowserDynamicTesting, -} from '@angular/platform-browser-dynamic/testing'; -import { getTestBed } from '@angular/core/testing'; - -getTestBed().initTestEnvironment( - BrowserDynamicTestingModule, - platformBrowserDynamicTesting() -); diff --git a/examples/aws-analog/sst.config.ts b/examples/aws-analog/sst.config.ts deleted file mode 100644 index e7256be079..0000000000 --- a/examples/aws-analog/sst.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-analog", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public" - }); - - new sst.aws.Analog("MyWeb", { - link: [bucket], - }); - }, -}); diff --git a/examples/aws-analog/tsconfig.app.json b/examples/aws-analog/tsconfig.app.json deleted file mode 100644 index ad965f67de..0000000000 --- a/examples/aws-analog/tsconfig.app.json +++ /dev/null @@ -1,14 +0,0 @@ -/* To learn more about this file see: https://angular.io/config/tsconfig. */ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./out-tsc/app", - "types": [] - }, - "files": ["src/main.ts", "src/main.server.ts"], - "include": [ - "src/**/*.d.ts", - "src/app/pages/**/*.page.ts", - "src/server/middleware/**/*.ts" - ] -} diff --git a/examples/aws-analog/tsconfig.json b/examples/aws-analog/tsconfig.json deleted file mode 100644 index 94e11863a1..0000000000 --- a/examples/aws-analog/tsconfig.json +++ /dev/null @@ -1,31 +0,0 @@ -/* To learn more about this file see: https://angular.io/config/tsconfig. */ -{ - "compileOnSave": false, - "compilerOptions": { - "baseUrl": "./", - "outDir": "./dist/out-tsc", - "forceConsistentCasingInFileNames": true, - "strict": true, - "noImplicitOverride": true, - "noPropertyAccessFromIndexSignature": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "sourceMap": true, - "declaration": false, - "downlevelIteration": true, - "experimentalDecorators": true, - "moduleResolution": "node", - "importHelpers": true, - "target": "ES2022", - "module": "ES2022", - "lib": ["ES2022", "dom"], - "useDefineForClassFields": false, - "skipLibCheck": true - }, - "angularCompilerOptions": { - "enableI18nLegacyMessageIdFormat": false, - "strictInjectionParameters": true, - "strictInputAccessModifiers": true, - "strictTemplates": true - } -} diff --git a/examples/aws-analog/tsconfig.spec.json b/examples/aws-analog/tsconfig.spec.json deleted file mode 100644 index 06eb7cae61..0000000000 --- a/examples/aws-analog/tsconfig.spec.json +++ /dev/null @@ -1,11 +0,0 @@ -/* To learn more about this file see: https://angular.io/config/tsconfig. */ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./out-tsc/spec", - "target": "es2016", - "types": ["node", "vitest/globals"] - }, - "files": ["src/test-setup.ts"], - "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] -} diff --git a/examples/aws-analog/vite.config.ts b/examples/aws-analog/vite.config.ts deleted file mode 100644 index bb4ee185dd..0000000000 --- a/examples/aws-analog/vite.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// - -import { defineConfig } from 'vite'; -import analog from '@analogjs/platform'; - -// https://vitejs.dev/config/ -export default defineConfig(({ mode }) => ({ - build: { - target: ['es2020'], - }, - resolve: { - mainFields: ['module'], - }, - plugins: [analog({ - nitro: { - preset: "aws-lambda", - } - })], - test: { - globals: true, - environment: 'jsdom', - setupFiles: ['src/test-setup.ts'], - include: ['**/*.spec.ts'], - reporters: ['default'], - }, - define: { - 'import.meta.vitest': mode !== 'production', - }, -})); diff --git a/examples/aws-angular/.editorconfig b/examples/aws-angular/.editorconfig deleted file mode 100644 index 59d9a3a3e7..0000000000 --- a/examples/aws-angular/.editorconfig +++ /dev/null @@ -1,16 +0,0 @@ -# Editor configuration, see https://editorconfig.org -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.ts] -quote_type = single - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/examples/aws-angular/.gitignore b/examples/aws-angular/.gitignore deleted file mode 100644 index c23cd03a2f..0000000000 --- a/examples/aws-angular/.gitignore +++ /dev/null @@ -1,44 +0,0 @@ -# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. - -# Compiled output -/dist -/tmp -/out-tsc -/bazel-out - -# Node -/node_modules -npm-debug.log -yarn-error.log - -# IDEs and editors -.idea/ -.project -.classpath -.c9/ -*.launch -.settings/ -*.sublime-workspace - -# Visual Studio Code -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -.history/* - -# Miscellaneous -/.angular/cache -.sass-cache/ -/connect.lock -/coverage -/libpeerconnection.log -testem.log -/typings - -# System files -.DS_Store -Thumbs.db - -.sst diff --git a/examples/aws-angular/.vscode/extensions.json b/examples/aws-angular/.vscode/extensions.json deleted file mode 100644 index 77b374577d..0000000000 --- a/examples/aws-angular/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 - "recommendations": ["angular.ng-template"] -} diff --git a/examples/aws-angular/.vscode/launch.json b/examples/aws-angular/.vscode/launch.json deleted file mode 100644 index 925af83705..0000000000 --- a/examples/aws-angular/.vscode/launch.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "ng serve", - "type": "chrome", - "request": "launch", - "preLaunchTask": "npm: start", - "url": "http://localhost:4200/" - }, - { - "name": "ng test", - "type": "chrome", - "request": "launch", - "preLaunchTask": "npm: test", - "url": "http://localhost:9876/debug.html" - } - ] -} diff --git a/examples/aws-angular/.vscode/tasks.json b/examples/aws-angular/.vscode/tasks.json deleted file mode 100644 index a298b5bd87..0000000000 --- a/examples/aws-angular/.vscode/tasks.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 - "version": "2.0.0", - "tasks": [ - { - "type": "npm", - "script": "start", - "isBackground": true, - "problemMatcher": { - "owner": "typescript", - "pattern": "$tsc", - "background": { - "activeOnStart": true, - "beginsPattern": { - "regexp": "(.*?)" - }, - "endsPattern": { - "regexp": "bundle generation complete" - } - } - } - }, - { - "type": "npm", - "script": "test", - "isBackground": true, - "problemMatcher": { - "owner": "typescript", - "pattern": "$tsc", - "background": { - "activeOnStart": true, - "beginsPattern": { - "regexp": "(.*?)" - }, - "endsPattern": { - "regexp": "bundle generation complete" - } - } - } - } - ] -} diff --git a/examples/aws-angular/angular.json b/examples/aws-angular/angular.json deleted file mode 100644 index e928c0184f..0000000000 --- a/examples/aws-angular/angular.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "version": 1, - "newProjectRoot": "projects", - "projects": { - "aws-angular": { - "projectType": "application", - "schematics": {}, - "root": "", - "sourceRoot": "src", - "prefix": "app", - "architect": { - "build": { - "builder": "@ngx-env/builder:application", - "options": { - "outputPath": "dist/aws-angular", - "index": "src/index.html", - "browser": "src/main.ts", - "polyfills": [ - "zone.js" - ], - "tsConfig": "tsconfig.app.json", - "assets": [ - { - "glob": "**/*", - "input": "public" - } - ], - "styles": [ - "src/styles.css" - ], - "scripts": [] - }, - "configurations": { - "production": { - "budgets": [ - { - "type": "initial", - "maximumWarning": "500kB", - "maximumError": "1MB" - }, - { - "type": "anyComponentStyle", - "maximumWarning": "2kB", - "maximumError": "4kB" - } - ], - "outputHashing": "all" - }, - "development": { - "optimization": false, - "extractLicenses": false, - "sourceMap": true - } - }, - "defaultConfiguration": "production" - }, - "serve": { - "builder": "@ngx-env/builder:dev-server", - "configurations": { - "production": { - "buildTarget": "aws-angular:build:production" - }, - "development": { - "buildTarget": "aws-angular:build:development" - } - }, - "defaultConfiguration": "development" - }, - "extract-i18n": { - "builder": "@ngx-env/builder:extract-i18n" - }, - "test": { - "builder": "@ngx-env/builder:karma", - "options": { - "polyfills": [ - "zone.js", - "zone.js/testing" - ], - "tsConfig": "tsconfig.spec.json", - "assets": [ - { - "glob": "**/*", - "input": "public" - } - ], - "styles": [ - "src/styles.css" - ], - "scripts": [] - } - } - } - } - } -} \ No newline at end of file diff --git a/examples/aws-angular/functions/presigned.ts b/examples/aws-angular/functions/presigned.ts deleted file mode 100644 index 063e82b94f..0000000000 --- a/examples/aws-angular/functions/presigned.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -export async function handler() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - - return { - statusCode: 200, - body: await getSignedUrl(new S3Client({}), command), - }; -} diff --git a/examples/aws-angular/package.json b/examples/aws-angular/package.json deleted file mode 100644 index 26c545ea06..0000000000 --- a/examples/aws-angular/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "aws-angular", - "version": "0.0.0", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build", - "watch": "ng build --watch --configuration development", - "test": "ng test" - }, - "private": true, - "dependencies": { - "@angular/animations": "^18.2.0", - "@angular/common": "^18.2.0", - "@angular/compiler": "^18.2.0", - "@angular/core": "^18.2.0", - "@angular/forms": "^18.2.0", - "@angular/platform-browser": "^18.2.0", - "@angular/platform-browser-dynamic": "^18.2.0", - "@angular/router": "^18.2.0", - "@aws-sdk/client-s3": "^3.637.0", - "@aws-sdk/s3-request-presigner": "^3.637.0", - "rxjs": "~7.8.0", - "tslib": "^2.3.0", - "zone.js": "~0.14.10" - }, - "devDependencies": { - "@angular-devkit/build-angular": "^18.2.2", - "@angular/cli": "^18.2.2", - "@angular/compiler-cli": "^18.2.0", - "@ngx-env/builder": "^18.0.1", - "@types/jasmine": "~5.1.0", - "jasmine-core": "~5.2.0", - "karma": "~6.4.0", - "karma-chrome-launcher": "~3.2.0", - "karma-coverage": "~2.2.0", - "karma-jasmine": "~5.1.0", - "karma-jasmine-html-reporter": "~2.1.0", - "sst": "file:../../sdk/js", - "typescript": "~5.5.2" - } -} diff --git a/examples/aws-angular/public/favicon.ico b/examples/aws-angular/public/favicon.ico deleted file mode 100644 index 57614f9c96..0000000000 Binary files a/examples/aws-angular/public/favicon.ico and /dev/null differ diff --git a/examples/aws-angular/src/app/app.component.html b/examples/aws-angular/src/app/app.component.html deleted file mode 100644 index 8a552a3da8..0000000000 --- a/examples/aws-angular/src/app/app.component.html +++ /dev/null @@ -1,336 +0,0 @@ - - - - - - - - - - - -
-
-
- -

Hello, {{ title }}

-

Congratulations! Your app is running. 🎉

-
- -
-
- @for (item of [ - { title: 'Explore the Docs', link: 'https://angular.dev' }, - { title: 'Learn with Tutorials', link: 'https://angular.dev/tutorials' }, - { title: 'CLI Docs', link: 'https://angular.dev/tools/cli' }, - { title: 'Angular Language Service', link: 'https://angular.dev/tools/language-service' }, - { title: 'Angular DevTools', link: 'https://angular.dev/tools/devtools' }, - ]; track item.title) { - - {{ item.title }} - - - - - } -
- -
-
-
- - - - - - - - - - - diff --git a/examples/aws-angular/src/app/app.component.spec.ts b/examples/aws-angular/src/app/app.component.spec.ts deleted file mode 100644 index c2e1a61504..0000000000 --- a/examples/aws-angular/src/app/app.component.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { TestBed } from '@angular/core/testing'; -import { AppComponent } from './app.component'; - -describe('AppComponent', () => { - beforeEach(async () => { - await TestBed.configureTestingModule({ - imports: [AppComponent], - }).compileComponents(); - }); - - it('should create the app', () => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.componentInstance; - expect(app).toBeTruthy(); - }); - - it(`should have the 'aws-angular' title`, () => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.componentInstance; - expect(app.title).toEqual('aws-angular'); - }); - - it('should render title', () => { - const fixture = TestBed.createComponent(AppComponent); - fixture.detectChanges(); - const compiled = fixture.nativeElement as HTMLElement; - expect(compiled.querySelector('h1')?.textContent).toContain('Hello, aws-angular'); - }); -}); diff --git a/examples/aws-angular/src/app/app.component.ts b/examples/aws-angular/src/app/app.component.ts deleted file mode 100644 index 8ed480a4d4..0000000000 --- a/examples/aws-angular/src/app/app.component.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Component } from '@angular/core'; -import { RouterOutlet } from '@angular/router'; -import { FileUploadComponent } from './file-upload.component'; - -@Component({ - selector: 'app-root', - standalone: true, - imports: [RouterOutlet, FileUploadComponent], - template: ` -
- -
- - `, - styles: [` - main { - margin: auto; - padding: 1.5rem; - max-width: 60ch; - } - `], -}) -export class AppComponent { } diff --git a/examples/aws-angular/src/app/app.config.ts b/examples/aws-angular/src/app/app.config.ts deleted file mode 100644 index 138d4e9d95..0000000000 --- a/examples/aws-angular/src/app/app.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; -import { provideHttpClient, withFetch } from '@angular/common/http'; -import { provideRouter } from '@angular/router'; - -import { routes } from './app.routes'; - -export const appConfig: ApplicationConfig = { - providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(withFetch())] -}; diff --git a/examples/aws-angular/src/app/app.routes.ts b/examples/aws-angular/src/app/app.routes.ts deleted file mode 100644 index dc39edb5f2..0000000000 --- a/examples/aws-angular/src/app/app.routes.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { Routes } from '@angular/router'; - -export const routes: Routes = []; diff --git a/examples/aws-angular/src/app/file-upload.component.ts b/examples/aws-angular/src/app/file-upload.component.ts deleted file mode 100644 index 25d34d1e5e..0000000000 --- a/examples/aws-angular/src/app/file-upload.component.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Component, inject } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import { FormsModule } from '@angular/forms'; - -@Component({ - selector: 'app-file-upload', - standalone: true, - imports: [FormsModule], - template: ` -
- - -
- `, - styles: [` - form { - color: white; - padding: 2rem; - display: flex; - align-items: center; - justify-content: space-between; - background-color: #23262d; - background-image: none; - background-size: 400%; - border-radius: 0.6rem; - background-position: 100%; - box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); - } - button { - appearance: none; - border: 0; - font-weight: 500; - border-radius: 5px; - font-size: 0.875rem; - padding: 0.5rem 0.75rem; - background-color: white; - color: black; - } - button:active:enabled { - background-color: #EEE; - } - `] -}) -export class FileUploadComponent { - private http = inject(HttpClient); - - presignedApi = import.meta.env['NG_APP_PRESIGNED_API']; - - async onSubmit(event: Event): Promise { - const file = (event.target as HTMLFormElement)['file'].files?.[0]!; - - this.http.get(this.presignedApi, { responseType: 'text' }).subscribe({ - next: async (url: string) => { - const image = await fetch(url, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }, - }); - } -} diff --git a/examples/aws-angular/src/env.d.ts b/examples/aws-angular/src/env.d.ts deleted file mode 100644 index f27c3a9850..0000000000 --- a/examples/aws-angular/src/env.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Define the type of the environment variables. -declare interface Env { - readonly NODE_ENV: string; - // Replace the following with your own environment variables. - // Example: NGX_VERSION: string; - [key: string]: any; -} - -// Choose how to access the environment variables. -// Remove the unused options. - -// 1. Use import.meta.env.YOUR_ENV_VAR in your code. (conventional) -declare interface ImportMeta { - readonly env: Env; -} - -// 2. Use _NGX_ENV_.YOUR_ENV_VAR in your code. (customizable) -// You can modify the name of the variable in angular.json. -// ngxEnv: { -// define: '_NGX_ENV_', -// } -declare const _NGX_ENV_: Env; - -// 3. Use process.env.YOUR_ENV_VAR in your code. (deprecated) -declare namespace NodeJS { - export interface ProcessEnv extends Env {} -} diff --git a/examples/aws-angular/src/index.html b/examples/aws-angular/src/index.html deleted file mode 100644 index 21b153fb31..0000000000 --- a/examples/aws-angular/src/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - AwsAngular - - - - - - - - diff --git a/examples/aws-angular/src/main.ts b/examples/aws-angular/src/main.ts deleted file mode 100644 index 35b00f3463..0000000000 --- a/examples/aws-angular/src/main.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { bootstrapApplication } from '@angular/platform-browser'; -import { appConfig } from './app/app.config'; -import { AppComponent } from './app/app.component'; - -bootstrapApplication(AppComponent, appConfig) - .catch((err) => console.error(err)); diff --git a/examples/aws-angular/sst.config.ts b/examples/aws-angular/sst.config.ts deleted file mode 100644 index 2a2628ce96..0000000000 --- a/examples/aws-angular/sst.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-angular", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - - const pre = new sst.aws.Function("MyFunction", { - url: true, - link: [bucket], - handler: "functions/presigned.handler", - }); - - new sst.aws.StaticSite("MyWeb", { - dev: { - command: "npm run start", - }, - build: { - output: "dist/browser", - command: "ng build --output-path dist", - }, - environment: { - NG_APP_PRESIGNED_API: pre.url - } - }); - }, -}); - diff --git a/examples/aws-angular/tsconfig.app.json b/examples/aws-angular/tsconfig.app.json deleted file mode 100644 index 3775b37e3b..0000000000 --- a/examples/aws-angular/tsconfig.app.json +++ /dev/null @@ -1,15 +0,0 @@ -/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ -/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./out-tsc/app", - "types": [] - }, - "files": [ - "src/main.ts" - ], - "include": [ - "src/**/*.d.ts" - ] -} diff --git a/examples/aws-angular/tsconfig.json b/examples/aws-angular/tsconfig.json deleted file mode 100644 index a8bb65b6e2..0000000000 --- a/examples/aws-angular/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ -/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ -{ - "compileOnSave": false, - "compilerOptions": { - "outDir": "./dist/out-tsc", - "strict": true, - "noImplicitOverride": true, - "noPropertyAccessFromIndexSignature": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "skipLibCheck": true, - "isolatedModules": true, - "esModuleInterop": true, - "sourceMap": true, - "declaration": false, - "experimentalDecorators": true, - "moduleResolution": "bundler", - "importHelpers": true, - "target": "ES2022", - "module": "ES2022", - "lib": [ - "ES2022", - "dom" - ] - }, - "angularCompilerOptions": { - "enableI18nLegacyMessageIdFormat": false, - "strictInjectionParameters": true, - "strictInputAccessModifiers": true, - "strictTemplates": true - } -} diff --git a/examples/aws-angular/tsconfig.spec.json b/examples/aws-angular/tsconfig.spec.json deleted file mode 100644 index 5fb748d920..0000000000 --- a/examples/aws-angular/tsconfig.spec.json +++ /dev/null @@ -1,15 +0,0 @@ -/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ -/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./out-tsc/spec", - "types": [ - "jasmine" - ] - }, - "include": [ - "src/**/*.spec.ts", - "src/**/*.d.ts" - ] -} diff --git a/examples/aws-api/.gitignore b/examples/aws-api/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-api/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-api/index.ts b/examples/aws-api/index.ts deleted file mode 100644 index 4c760bfc12..0000000000 --- a/examples/aws-api/index.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { - S3Client, - GetObjectCommand, - PutObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; - -const s3 = new S3Client({}); - -export async function upload() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - - return { - statusCode: 200, - body: await getSignedUrl(s3, command), - }; -} - -export async function latest() { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }) - ); - - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0) - )[0]; - - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - - return { - statusCode: 302, - headers: { - Location: await getSignedUrl(s3, command), - }, - }; -} diff --git a/examples/aws-api/package.json b/examples/aws-api/package.json deleted file mode 100644 index 544351cff4..0000000000 --- a/examples/aws-api/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-api", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-s3": "^3.540.0", - "@aws-sdk/s3-request-presigner": "^3.540.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.142" - } -} diff --git a/examples/aws-api/sst.config.ts b/examples/aws-api/sst.config.ts deleted file mode 100644 index 5a8f1ddcb3..0000000000 --- a/examples/aws-api/sst.config.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-api", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket"); - const api = new sst.aws.ApiGatewayV2("MyApi"); - api.route("GET /", { - link: [bucket], - handler: "index.upload", - }); - api.route("GET /latest", { - link: [bucket], - handler: "index.latest", - }); - }, -}); diff --git a/examples/aws-apig-auth/package.json b/examples/aws-apig-auth/package.json deleted file mode 100644 index 7776c8ad27..0000000000 --- a/examples/aws-apig-auth/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-apig-auth", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-apig-auth/route.ts b/examples/aws-apig-auth/route.ts deleted file mode 100644 index 3bc5653e3a..0000000000 --- a/examples/aws-apig-auth/route.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const handler = async (event) => { - console.log(event); - return { - statusCode: 200, - body: JSON.stringify({ route: event.routeKey, status: "ok" }, null, 2), - }; -}; diff --git a/examples/aws-apig-auth/sst.config.ts b/examples/aws-apig-auth/sst.config.ts deleted file mode 100644 index 4c07cb077f..0000000000 --- a/examples/aws-apig-auth/sst.config.ts +++ /dev/null @@ -1,43 +0,0 @@ -/// - -/** - * ## API Gateway auth - * - * Enable IAM and JWT authorizers for API Gateway routes. - * - */ -export default $config({ - app(input) { - return { - name: "aws-apig-auth", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const api = new sst.aws.ApiGatewayV2("MyApi", { - domain: { - name: "api.ion.sst.sh", - path: "v1", - }, - }); - api.route("GET /", { - handler: "route.handler", - }); - api.route("GET /foo", "route.handler", { auth: { iam: true } }); - api.route("GET /bar", "route.handler", { - auth: { - jwt: { - issuer: - "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_Rq4d8zILG", - audiences: ["user@example.com"], - }, - }, - }); - api.route("$default", "route.handler"); - - return { - api: api.url, - }; - }, -}); diff --git a/examples/aws-apig-websocket/.gitignore b/examples/aws-apig-websocket/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-apig-websocket/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-apig-websocket/lambda.ts b/examples/aws-apig-websocket/lambda.ts deleted file mode 100644 index 9755466b92..0000000000 --- a/examples/aws-apig-websocket/lambda.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Resource } from "sst"; -import { - ApiGatewayManagementApiClient, - PostToConnectionCommand, -} from "@aws-sdk/client-apigatewaymanagementapi"; - -export async function connect(event) { - console.log("!!! connect"); - - // If subprotocols are requested, return the allowed protocol. In this example, we only - // allow "MY_ALLOWED_PROTOCOL". - const protocolHeader = event.headers["Sec-WebSocket-Protocol"]; - if (protocolHeader) { - const subprotocols = protocolHeader.split(",").map((p) => p.trim()); - return subprotocols.includes("MY_ALLOWED_PROTOCOL") - ? { - statusCode: 200, - headers: { "Sec-WebSocket-Protocol": "MY_ALLOWED_PROTOCOL" }, - } - : { statusCode: 400 }; - } - - return { statusCode: 200 }; -} - -export async function disconnect(event) { - console.log("!!! disconnect"); - return { statusCode: 200 }; -} - -export async function sendMessage(event) { - console.log("!!! sendMessage"); - return { statusCode: 200 }; -} - -export async function catchAll(event) { - console.log("!!! default"); - - // Send a message back to the client - const client = new ApiGatewayManagementApiClient({ - endpoint: Resource.MyApi.managementEndpoint, - }); - await client.send( - new PostToConnectionCommand({ - ConnectionId: event.requestContext.connectionId, - Data: "Hey! What is this?", - }) - ); - - return { statusCode: 200 }; -} diff --git a/examples/aws-apig-websocket/package.json b/examples/aws-apig-websocket/package.json deleted file mode 100644 index 3b0dba2a21..0000000000 --- a/examples/aws-apig-websocket/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-apig-websocket", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-apigatewaymanagementapi": "^3.699.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-apig-websocket/sst.config.ts b/examples/aws-apig-websocket/sst.config.ts deleted file mode 100644 index ebc05181b7..0000000000 --- a/examples/aws-apig-websocket/sst.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-apig-websocket", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const api = new sst.aws.ApiGatewayWebSocket("MyApi", {}); - api.route("$connect", "lambda.connect"); - api.route("$disconnect", "lambda.disconnect"); - api.route("$default", { handler: "lambda.catchAll", link: [api] }); - api.route("sendmessage", "lambda.sendMessage"); - - return { - managementEndpoint: api.managementEndpoint, - }; - }, -}); diff --git a/examples/aws-apigv1-stream/hono.ts b/examples/aws-apigv1-stream/hono.ts deleted file mode 100644 index a80f1f5cbc..0000000000 --- a/examples/aws-apigv1-stream/hono.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Hono } from "hono"; -import { streamText } from "hono/streaming"; -import { streamHandle } from "hono/aws-lambda"; - -const app = new Hono().get("/hono", (c) => { - return streamText(c, async (stream) => { - await stream.writeln("Hello"); - await stream.sleep(3000); - await stream.writeln("World"); - }); -}); - -export const handler = streamHandle(app); diff --git a/examples/aws-apigv1-stream/index.ts b/examples/aws-apigv1-stream/index.ts deleted file mode 100644 index fb8e0b89d2..0000000000 --- a/examples/aws-apigv1-stream/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export const handler = awslambda.streamifyResponse( - async (event, stream) => { - stream = awslambda.HttpResponseStream.from(stream, { - statusCode: 200, - headers: { - "Content-Type": "text/plain; charset=UTF-8", - "X-Content-Type-Options": "nosniff", - }, - }); - - stream.write("Hello "); - await new Promise((resolve) => setTimeout(resolve, 3000)); - stream.write("World"); - - stream.end(); - }, -); diff --git a/examples/aws-apigv1-stream/package.json b/examples/aws-apigv1-stream/package.json deleted file mode 100644 index 6669ffcf77..0000000000 --- a/examples/aws-apigv1-stream/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "aws-apigv1-stream", - "version": "1.0.0", - "dependencies": { - "@types/aws-lambda": "^8.10.161", - "hono": "^4", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-apigv1-stream/sst.config.ts b/examples/aws-apigv1-stream/sst.config.ts deleted file mode 100644 index 8e27d03985..0000000000 --- a/examples/aws-apigv1-stream/sst.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// - -/** - * ## AWS API Gateway V1 streaming - * - * An example on how to enable streaming for API Gateway REST API routes. - * - * ```ts title="sst.config.ts" - * api.route("GET /", { - * handler: "index.handler", - * streaming: true, - * }); - * ``` - * - * The handler uses the native `awslambda.streamifyResponse` and - * `awslambda.HttpResponseStream.from` to stream responses through API Gateway. - * - * ```ts title="index.ts" - * export const handler = awslambda.streamifyResponse( - * async (event, stream) => { - * stream = awslambda.HttpResponseStream.from(stream, { - * statusCode: 200, - * headers: { - * "Content-Type": "text/plain; charset=UTF-8", - * "X-Content-Type-Options": "nosniff", - * }, - * }); - * - * stream.write("Hello "); - * await new Promise((resolve) => setTimeout(resolve, 3000)); - * stream.write("World"); - * - * stream.end(); - * }, - * ); - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-apigv1-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const api = new sst.aws.ApiGatewayV1("MyApi"); - api.route("GET /", { - handler: "index.handler", - streaming: true, - }); - api.route("GET /hono", { - handler: "hono.handler", - streaming: true, - }); - api.deploy(); - - return { - api: api.url, - }; - }, -}); diff --git a/examples/aws-apigv1-stream/tsconfig.json b/examples/aws-apigv1-stream/tsconfig.json deleted file mode 100644 index 853c71f05c..0000000000 --- a/examples/aws-apigv1-stream/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true - } -} diff --git a/examples/aws-apigv1/.gitignore b/examples/aws-apigv1/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-apigv1/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-apigv1/index.ts b/examples/aws-apigv1/index.ts deleted file mode 100644 index 149485da7a..0000000000 --- a/examples/aws-apigv1/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -export async function handler() { - return { - statusCode: 200, - body: "hello world", - }; -} - -export async function authorizer(event, context) { - const authHeader = event.authorizationToken; - let username, password; - - if (authHeader) { - const base64Info = authHeader.split(" ")[1]; - // Stored as 'username:password' in base64 - const userInfo = Buffer.from(base64Info, "base64").toString(); - [username, password] = userInfo.split(":"); - } - - return username === "hello" && password === "world" - ? { - principalId: "*", - policyDocument: { - Version: "2012-10-17", - Statement: [ - { - Action: "execute-api:Invoke", - Effect: "Allow", - Resource: "*", - }, - ], - }, - } - : "Unauthorized"; -} diff --git a/examples/aws-apigv1/package.json b/examples/aws-apigv1/package.json deleted file mode 100644 index 132ea3562d..0000000000 --- a/examples/aws-apigv1/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "aws-apigv1", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-s3": "^3.540.0", - "@aws-sdk/s3-request-presigner": "^3.540.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-apigv1/sst.config.ts b/examples/aws-apigv1/sst.config.ts deleted file mode 100644 index d2991e0ed3..0000000000 --- a/examples/aws-apigv1/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-apigv1", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const api = new sst.aws.ApiGatewayV1("MyApi"); - const authorizer = api.addAuthorizer({ - name: "MyAuthorizer", - tokenFunction: "index.authorizer", - }); - api.route("GET /", "index.handler"); - api.route("GET /iam", "index.handler", { - auth: { iam: true }, - }); - api.route("GET /token", "index.handler", { - auth: { custom: authorizer.id }, - }); - api.route("GET /{proxy+}", "index.handler"); - api.deploy(); - }, -}); diff --git a/examples/aws-apigv1/tsconfig.json b/examples/aws-apigv1/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-apigv1/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-app-sync/lambda.ts b/examples/aws-app-sync/lambda.ts deleted file mode 100644 index 08136570e8..0000000000 --- a/examples/aws-app-sync/lambda.ts +++ /dev/null @@ -1,10 +0,0 @@ -type AppSyncEvent = { - info: { - fieldName: string; - }; -}; - -export async function main(event: AppSyncEvent) { - console.log(event); - return { status: "ok" }; -} diff --git a/examples/aws-app-sync/package.json b/examples/aws-app-sync/package.json deleted file mode 100644 index 36cadba873..0000000000 --- a/examples/aws-app-sync/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-app-sync", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-app-sync/schema.graphql b/examples/aws-app-sync/schema.graphql deleted file mode 100644 index b2c0cef549..0000000000 --- a/examples/aws-app-sync/schema.graphql +++ /dev/null @@ -1,5 +0,0 @@ -type Query { - license: String - user: String - pipeline: String -} diff --git a/examples/aws-app-sync/sst.config.ts b/examples/aws-app-sync/sst.config.ts deleted file mode 100644 index 53412e24a2..0000000000 --- a/examples/aws-app-sync/sst.config.ts +++ /dev/null @@ -1,47 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-app-sync", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const table = new sst.aws.Dynamo("MyTable", { - fields: { - userId: "string", - }, - primaryIndex: { hashKey: "userId" }, - }); - - const api = new sst.aws.AppSync("MyApi", { - schema: "schema.graphql", - domain: "appsync.ion.sst.sh", - }); - const lambdaDS = api.addDataSource({ - name: "lambda", - lambda: "lambda.main", - }); - const dynamoDS = api.addDataSource({ name: "dyanmo", dynamodb: table.arn }); - api.addResolver("Query license", { dataSource: lambdaDS.name }); - api.addResolver("Query user", { - dataSource: dynamoDS.name, - requestTemplate: `{ - "version": "2017-02-28", - "operation": "Scan", - }`, - responseTemplate: `{ - "users": $utils.toJson($context.result.items) - }`, - }); - - const apiKey = new aws.appsync.ApiKey("MyApiKey", { - apiId: api.id, - }); - return { - API_KEY: apiKey.key, - }; - }, -}); diff --git a/examples/aws-astro-container/.dockerignore b/examples/aws-astro-container/.dockerignore deleted file mode 100644 index cf88ac3dd3..0000000000 --- a/examples/aws-astro-container/.dockerignore +++ /dev/null @@ -1,7 +0,0 @@ -.DS_Store -node_modules -dist - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-astro-container/.gitignore b/examples/aws-astro-container/.gitignore deleted file mode 100644 index 12ff1bf9ce..0000000000 --- a/examples/aws-astro-container/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# build output -dist/ - -# generated types -.astro/ - -# dependencies -node_modules/ - -# logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - -# environment variables -.env -.env.production - -# macOS-specific files -.DS_Store - -# jetbrains setting folder -.idea/ - -# sst -.sst diff --git a/examples/aws-astro-container/.vscode/extensions.json b/examples/aws-astro-container/.vscode/extensions.json deleted file mode 100644 index 22a15055d6..0000000000 --- a/examples/aws-astro-container/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "recommendations": ["astro-build.astro-vscode"], - "unwantedRecommendations": [] -} diff --git a/examples/aws-astro-container/.vscode/launch.json b/examples/aws-astro-container/.vscode/launch.json deleted file mode 100644 index d642209762..0000000000 --- a/examples/aws-astro-container/.vscode/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "command": "./node_modules/.bin/astro dev", - "name": "Development server", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/examples/aws-astro-container/Dockerfile b/examples/aws-astro-container/Dockerfile deleted file mode 100644 index f096fbb0b5..0000000000 --- a/examples/aws-astro-container/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM node:lts AS base -WORKDIR /app - -COPY package.json package-lock.json ./ - -FROM base AS prod-deps -RUN npm install --omit=dev - -FROM base AS build-deps -RUN npm install - -FROM build-deps AS build -COPY . . -RUN npm run build - -FROM base AS runtime -COPY --from=prod-deps /app/node_modules ./node_modules -COPY --from=build /app/dist ./dist - -ENV HOST=0.0.0.0 -ENV PORT=4321 -EXPOSE 4321 -CMD node ./dist/server/entry.mjs diff --git a/examples/aws-astro-container/astro.config.mjs b/examples/aws-astro-container/astro.config.mjs deleted file mode 100644 index af450f938d..0000000000 --- a/examples/aws-astro-container/astro.config.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// @ts-check -// @ts-check -import { defineConfig } from 'astro/config'; - -import node from '@astrojs/node'; - -// https://astro.build/config -export default defineConfig({ - output: 'server', - - adapter: node({ - mode: 'standalone' - }) -}); diff --git a/examples/aws-astro-container/package.json b/examples/aws-astro-container/package.json deleted file mode 100644 index 1bd6f7c6b7..0000000000 --- a/examples/aws-astro-container/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-astro-container", - "type": "module", - "version": "0.0.1", - "scripts": { - "astro": "astro", - "build": "astro check && astro build", - "dev": "astro dev", - "preview": "astro preview" - }, - "dependencies": { - "@astrojs/check": "^0.9.4", - "@astrojs/node": "^8.3.4", - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "astro": "^4.16.16", - "astro-sst": "2.43.5", - "sst": "file:../../sdk/js", - "typescript": "^5.7.2" - } -} diff --git a/examples/aws-astro-container/public/favicon.svg b/examples/aws-astro-container/public/favicon.svg deleted file mode 100644 index f157bd1c5e..0000000000 --- a/examples/aws-astro-container/public/favicon.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/examples/aws-astro-container/src/assets/astro.svg b/examples/aws-astro-container/src/assets/astro.svg deleted file mode 100644 index 8cf8fb0c7d..0000000000 --- a/examples/aws-astro-container/src/assets/astro.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/aws-astro-container/src/assets/background.svg b/examples/aws-astro-container/src/assets/background.svg deleted file mode 100644 index 4b2be0ac0e..0000000000 --- a/examples/aws-astro-container/src/assets/background.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/aws-astro-container/src/components/Welcome.astro b/examples/aws-astro-container/src/components/Welcome.astro deleted file mode 100644 index d08955687f..0000000000 --- a/examples/aws-astro-container/src/components/Welcome.astro +++ /dev/null @@ -1,209 +0,0 @@ ---- -import astroLogo from '../assets/astro.svg'; -import background from '../assets/background.svg'; ---- - - - - diff --git a/examples/aws-astro-container/src/env.d.ts b/examples/aws-astro-container/src/env.d.ts deleted file mode 100644 index 9bc5cb41c2..0000000000 --- a/examples/aws-astro-container/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// \ No newline at end of file diff --git a/examples/aws-astro-container/src/layouts/Layout.astro b/examples/aws-astro-container/src/layouts/Layout.astro deleted file mode 100644 index e455c61067..0000000000 --- a/examples/aws-astro-container/src/layouts/Layout.astro +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - Astro Basics - - - - - - - diff --git a/examples/aws-astro-container/src/pages/index.astro b/examples/aws-astro-container/src/pages/index.astro deleted file mode 100644 index cb2889fa2a..0000000000 --- a/examples/aws-astro-container/src/pages/index.astro +++ /dev/null @@ -1,74 +0,0 @@ ---- -import { Resource } from "sst"; -import Layout from '../layouts/Layout.astro'; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, -}); -const url = await getSignedUrl(new S3Client({}), command); ---- - - -
-
- - -
- -
-
- - diff --git a/examples/aws-astro-container/sst.config.ts b/examples/aws-astro-container/sst.config.ts deleted file mode 100644 index 4190fc3729..0000000000 --- a/examples/aws-astro-container/sst.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-astro-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: "80/http", forward: "4321/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-astro-container/tsconfig.json b/examples/aws-astro-container/tsconfig.json deleted file mode 100644 index 96e2f10d1c..0000000000 --- a/examples/aws-astro-container/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "astro/tsconfigs/strict", - "include": [ - ".astro/types.d.ts", - "**/*" - ], - "exclude": [ - "dist","sst.config.ts" - ] -} diff --git a/examples/aws-astro-redis/.dockerignore b/examples/aws-astro-redis/.dockerignore deleted file mode 100644 index cf88ac3dd3..0000000000 --- a/examples/aws-astro-redis/.dockerignore +++ /dev/null @@ -1,7 +0,0 @@ -.DS_Store -node_modules -dist - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-astro-redis/.gitignore b/examples/aws-astro-redis/.gitignore deleted file mode 100644 index 12ff1bf9ce..0000000000 --- a/examples/aws-astro-redis/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# build output -dist/ - -# generated types -.astro/ - -# dependencies -node_modules/ - -# logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - -# environment variables -.env -.env.production - -# macOS-specific files -.DS_Store - -# jetbrains setting folder -.idea/ - -# sst -.sst diff --git a/examples/aws-astro-redis/.vscode/extensions.json b/examples/aws-astro-redis/.vscode/extensions.json deleted file mode 100644 index 22a15055d6..0000000000 --- a/examples/aws-astro-redis/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "recommendations": ["astro-build.astro-vscode"], - "unwantedRecommendations": [] -} diff --git a/examples/aws-astro-redis/.vscode/launch.json b/examples/aws-astro-redis/.vscode/launch.json deleted file mode 100644 index d642209762..0000000000 --- a/examples/aws-astro-redis/.vscode/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "command": "./node_modules/.bin/astro dev", - "name": "Development server", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/examples/aws-astro-redis/Dockerfile b/examples/aws-astro-redis/Dockerfile deleted file mode 100644 index 843b983342..0000000000 --- a/examples/aws-astro-redis/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# From https://docs.astro.build/en/recipes/docker/ - -FROM node:lts AS base -WORKDIR /app - -# By copying only the package.json and package-lock.json here, we ensure that the following `-deps` steps are independent of the source code. -# Therefore, the `-deps` steps will be skipped if only the source code changes. -COPY package.json package-lock.json ./ - -FROM base AS prod-deps -RUN npm install --omit=dev - -FROM base AS build-deps -RUN npm install - -FROM build-deps AS build -COPY . . -RUN npm run build - -FROM base AS runtime -COPY --from=prod-deps /app/node_modules ./node_modules -COPY --from=build /app/dist ./dist - -ENV HOST=0.0.0.0 -ENV PORT=4321 -EXPOSE 4321 -CMD node ./dist/server/entry.mjs diff --git a/examples/aws-astro-redis/astro.config.mjs b/examples/aws-astro-redis/astro.config.mjs deleted file mode 100644 index b806b438e1..0000000000 --- a/examples/aws-astro-redis/astro.config.mjs +++ /dev/null @@ -1,13 +0,0 @@ -// @ts-check -import { defineConfig } from 'astro/config'; - -import node from '@astrojs/node'; - -// https://astro.build/config -export default defineConfig({ - output: 'server', - - adapter: node({ - mode: 'standalone' - }) -}); \ No newline at end of file diff --git a/examples/aws-astro-redis/package.json b/examples/aws-astro-redis/package.json deleted file mode 100644 index 24ddfc5ac6..0000000000 --- a/examples/aws-astro-redis/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-astro-redis", - "type": "module", - "version": "0.0.1", - "scripts": { - "astro": "astro", - "build": "astro check && astro build", - "dev": "astro dev", - "preview": "astro preview", - "start": "astro dev" - }, - "dependencies": { - "@astrojs/check": "^0.9.4", - "@astrojs/node": "^8.3.4", - "astro": "^4.16.3", - "astro-sst": "2.43.5", - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js", - "typescript": "^5.6.3" - } -} diff --git a/examples/aws-astro-redis/public/favicon.svg b/examples/aws-astro-redis/public/favicon.svg deleted file mode 100644 index f157bd1c5e..0000000000 --- a/examples/aws-astro-redis/public/favicon.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/examples/aws-astro-redis/src/components/Card.astro b/examples/aws-astro-redis/src/components/Card.astro deleted file mode 100644 index bd6d5971eb..0000000000 --- a/examples/aws-astro-redis/src/components/Card.astro +++ /dev/null @@ -1,61 +0,0 @@ ---- -interface Props { - title: string; - body: string; - href: string; -} - -const { href, title, body } = Astro.props; ---- - - - diff --git a/examples/aws-astro-redis/src/env.d.ts b/examples/aws-astro-redis/src/env.d.ts deleted file mode 100644 index 9bc5cb41c2..0000000000 --- a/examples/aws-astro-redis/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// \ No newline at end of file diff --git a/examples/aws-astro-redis/src/layouts/Layout.astro b/examples/aws-astro-redis/src/layouts/Layout.astro deleted file mode 100644 index 181097125d..0000000000 --- a/examples/aws-astro-redis/src/layouts/Layout.astro +++ /dev/null @@ -1,50 +0,0 @@ ---- -interface Props { - title: string; -} - -const { title } = Astro.props; ---- - - - - - - - - - - {title} - - - - - - diff --git a/examples/aws-astro-redis/src/pages/index.astro b/examples/aws-astro-redis/src/pages/index.astro deleted file mode 100644 index d6602d4bce..0000000000 --- a/examples/aws-astro-redis/src/pages/index.astro +++ /dev/null @@ -1,44 +0,0 @@ ---- -import { Resource } from "sst"; -import { Cluster } from "ioredis"; -import Layout from '../layouts/Layout.astro'; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -const counter = await redis.incr("counter"); ---- - - -
-

Hit counter: {counter}

-
-
- - diff --git a/examples/aws-astro-redis/sst.config.ts b/examples/aws-astro-redis/sst.config.ts deleted file mode 100644 index 621ca85c0a..0000000000 --- a/examples/aws-astro-redis/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## AWS Astro container with Redis - * - * Creates a hit counter app with Astro and Redis. - * - * This deploys Astro as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "npm run dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:4321` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it by adding the `Dockerfile` that's included in this example and - * running `npx sst deploy --stage production`. - */ -export default $config({ - app(input) { - return { - name: "aws-astro-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "4321/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-astro-redis/tsconfig.json b/examples/aws-astro-redis/tsconfig.json deleted file mode 100644 index ddbfe3e6f3..0000000000 --- a/examples/aws-astro-redis/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "astro/tsconfigs/strict", - "exclude": ["sst.config.ts"] -} diff --git a/examples/aws-astro-stream/.gitignore b/examples/aws-astro-stream/.gitignore deleted file mode 100644 index 12ff1bf9ce..0000000000 --- a/examples/aws-astro-stream/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# build output -dist/ - -# generated types -.astro/ - -# dependencies -node_modules/ - -# logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - -# environment variables -.env -.env.production - -# macOS-specific files -.DS_Store - -# jetbrains setting folder -.idea/ - -# sst -.sst diff --git a/examples/aws-astro-stream/.vscode/extensions.json b/examples/aws-astro-stream/.vscode/extensions.json deleted file mode 100644 index 22a15055d6..0000000000 --- a/examples/aws-astro-stream/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "recommendations": ["astro-build.astro-vscode"], - "unwantedRecommendations": [] -} diff --git a/examples/aws-astro-stream/.vscode/launch.json b/examples/aws-astro-stream/.vscode/launch.json deleted file mode 100644 index d642209762..0000000000 --- a/examples/aws-astro-stream/.vscode/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "command": "./node_modules/.bin/astro dev", - "name": "Development server", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/examples/aws-astro-stream/astro.config.mjs b/examples/aws-astro-stream/astro.config.mjs deleted file mode 100644 index d08eebd972..0000000000 --- a/examples/aws-astro-stream/astro.config.mjs +++ /dev/null @@ -1,11 +0,0 @@ -// @ts-check -import aws from "astro-sst"; -import { defineConfig } from 'astro/config'; - -// https://astro.build/config -export default defineConfig({ - output: "server", - adapter: aws({ - responseMode: "stream", - }), -}); diff --git a/examples/aws-astro-stream/package.json b/examples/aws-astro-stream/package.json deleted file mode 100644 index d2ee3a1fb7..0000000000 --- a/examples/aws-astro-stream/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-astro-stream", - "type": "module", - "version": "0.0.1", - "scripts": { - "astro": "astro", - "build": "astro check && astro build", - "dev": "astro dev", - "preview": "astro preview", - "start": "astro dev" - }, - "dependencies": { - "@astrojs/check": "^0.9.3", - "astro": "^4.15.9", - "astro-sst": "2.43.5", - "sst": "file:../../sdk/js", - "typescript": "^5.6.2" - } -} diff --git a/examples/aws-astro-stream/public/favicon.svg b/examples/aws-astro-stream/public/favicon.svg deleted file mode 100644 index f157bd1c5e..0000000000 --- a/examples/aws-astro-stream/public/favicon.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/examples/aws-astro-stream/public/mr-krabs.png b/examples/aws-astro-stream/public/mr-krabs.png deleted file mode 100644 index e94ea64054..0000000000 Binary files a/examples/aws-astro-stream/public/mr-krabs.png and /dev/null differ diff --git a/examples/aws-astro-stream/public/patrick.png b/examples/aws-astro-stream/public/patrick.png deleted file mode 100644 index 030eaaf8a3..0000000000 Binary files a/examples/aws-astro-stream/public/patrick.png and /dev/null differ diff --git a/examples/aws-astro-stream/public/sandy.png b/examples/aws-astro-stream/public/sandy.png deleted file mode 100644 index eb7a9cc324..0000000000 Binary files a/examples/aws-astro-stream/public/sandy.png and /dev/null differ diff --git a/examples/aws-astro-stream/public/spongebob.png b/examples/aws-astro-stream/public/spongebob.png deleted file mode 100644 index 18f7df537e..0000000000 Binary files a/examples/aws-astro-stream/public/spongebob.png and /dev/null differ diff --git a/examples/aws-astro-stream/public/squidward.png b/examples/aws-astro-stream/public/squidward.png deleted file mode 100644 index 4af85e000b..0000000000 Binary files a/examples/aws-astro-stream/public/squidward.png and /dev/null differ diff --git a/examples/aws-astro-stream/src/components/Bio.astro b/examples/aws-astro-stream/src/components/Bio.astro deleted file mode 100644 index 0cac88361e..0000000000 --- a/examples/aws-astro-stream/src/components/Bio.astro +++ /dev/null @@ -1,35 +0,0 @@ ---- -import type { Character } from "./character"; - -const spongebob: Character = { - name: "SpongeBob SquarePants", - description: "SpongeBob SquarePants is the main character of the popular animated TV series. He's a cheerful sea sponge who lives in a pineapple house in the underwater city of Bikini Bottom. SpongeBob works as a fry cook at the Krusty Krab and loves jellyfishing with his best friend Patrick Star.", - image: "spongebob.png", -}; ---- -
-

{spongebob.name}

-
-
-

{spongebob.description}

-
- {spongebob.name} -
-
- - diff --git a/examples/aws-astro-stream/src/components/Friends.astro b/examples/aws-astro-stream/src/components/Friends.astro deleted file mode 100644 index b3f69f2815..0000000000 --- a/examples/aws-astro-stream/src/components/Friends.astro +++ /dev/null @@ -1,43 +0,0 @@ ---- -import type { Character } from "./character"; - -const friends: Character[] = await new Promise((resolve) => setTimeout(() => { - setTimeout(() => { - resolve( - [ - { name: "Patrick Star", image: "patrick.png" }, - { name: "Sandy Cheeks", image: "sandy.png" }, - { name: "Squidward Tentacles", image: "squidward.png" }, - { name: "Mr. Krabs", image: "mr-krabs.png" }, - ] - ); - }, 3000); -})); ---- -
- {friends.map((friend) => ( -
- {friend.name} -

{friend.name}

-
- ))} -
- - diff --git a/examples/aws-astro-stream/src/components/character.ts b/examples/aws-astro-stream/src/components/character.ts deleted file mode 100644 index b1c51ce400..0000000000 --- a/examples/aws-astro-stream/src/components/character.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface Character { - name: string; - image: string; - description?: string; -} diff --git a/examples/aws-astro-stream/src/env.d.ts b/examples/aws-astro-stream/src/env.d.ts deleted file mode 100644 index 9bc5cb41c2..0000000000 --- a/examples/aws-astro-stream/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// \ No newline at end of file diff --git a/examples/aws-astro-stream/src/layouts/Layout.astro b/examples/aws-astro-stream/src/layouts/Layout.astro deleted file mode 100644 index 9b3c662692..0000000000 --- a/examples/aws-astro-stream/src/layouts/Layout.astro +++ /dev/null @@ -1,39 +0,0 @@ ---- -interface Props { - title: string; -} - -const { title } = Astro.props; ---- - - - - - - - - - - {title} - - -
- -
- - - diff --git a/examples/aws-astro-stream/src/pages/index.astro b/examples/aws-astro-stream/src/pages/index.astro deleted file mode 100644 index 8b90a967db..0000000000 --- a/examples/aws-astro-stream/src/pages/index.astro +++ /dev/null @@ -1,73 +0,0 @@ ---- -import Layout from '../layouts/Layout.astro'; -import Bio from '../components/Bio.astro'; -import Friends from '../components/Friends.astro'; ---- - - - - -
-

Friends from Bikini Bottom

- -
-
- - diff --git a/examples/aws-astro-stream/sst.config.ts b/examples/aws-astro-stream/sst.config.ts deleted file mode 100644 index 856fce0412..0000000000 --- a/examples/aws-astro-stream/sst.config.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// - -/** - * ## AWS Astro streaming - * - * Follows the [Astro Streaming](https://docs.astro.build/en/recipes/streaming-improve-page-performance/) guide to create an app that streams HTML. - * - * The `responseMode` in the [`astro-sst`](https://www.npmjs.com/package/astro-sst) adapter - * is set to enable streaming. - * - * - * ```ts title="astro.config.mjs" - * adapter: aws({ - * responseMode: "stream" - * }) - * ``` - * - * Now any components that return promises will be streamed. - * - * ```astro title="src/components/Friends.astro" - * --- - * import type { Character } from "./character"; - * - * const friends: Character[] = await new Promise((resolve) => setTimeout(() => { - * setTimeout(() => { - * resolve( - * [ - * { name: "Patrick Star", image: "patrick.png" }, - * { name: "Sandy Cheeks", image: "sandy.png" }, - * { name: "Squidward Tentacles", image: "squidward.png" }, - * { name: "Mr. Krabs", image: "mr-krabs.png" }, - * ] - * ); - * }, 3000); - * })); - * --- - *
- * {friends.map((friend) => ( - *
- * {friend.name} - *

{friend.name}

- *
- * ))} - *
- * ``` - * - * You should see the _friends_ section load after a 3 second delay. - * - * :::note - * Safari handles streaming differently than other browsers. - * ::: - * - * Safari uses a [different heuristic](https://bugs.webkit.org/show_bug.cgi?id=252413) to - * determine when to stream data. You need to render _enough_ initial HTML to trigger streaming. - * This is typically only a problem for demo apps. - * - * There's nothing to configure for streaming in the `Astro` component. - */ -export default $config({ - app(input) { - return { - name: "aws-astro-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Astro("MyWeb"); - }, -}); diff --git a/examples/aws-astro-stream/tsconfig.json b/examples/aws-astro-stream/tsconfig.json deleted file mode 100644 index 77da9dd009..0000000000 --- a/examples/aws-astro-stream/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "astro/tsconfigs/strict" -} \ No newline at end of file diff --git a/examples/aws-astro/.gitignore b/examples/aws-astro/.gitignore deleted file mode 100644 index 9a746a2f70..0000000000 --- a/examples/aws-astro/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# build output -dist/ - -# generated types -.astro/ - -# dependencies -node_modules/ - -# logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - -# environment variables -.env -.env.production - -# macOS-specific files -.DS_Store - -# sst -.sst diff --git a/examples/aws-astro/.vscode/extensions.json b/examples/aws-astro/.vscode/extensions.json deleted file mode 100644 index 22a15055d6..0000000000 --- a/examples/aws-astro/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "recommendations": ["astro-build.astro-vscode"], - "unwantedRecommendations": [] -} diff --git a/examples/aws-astro/.vscode/launch.json b/examples/aws-astro/.vscode/launch.json deleted file mode 100644 index d642209762..0000000000 --- a/examples/aws-astro/.vscode/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "command": "./node_modules/.bin/astro dev", - "name": "Development server", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/examples/aws-astro/astro.config.mjs b/examples/aws-astro/astro.config.mjs deleted file mode 100644 index b4f287b9a8..0000000000 --- a/examples/aws-astro/astro.config.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from "astro/config"; -import aws from "astro-sst"; - -export default defineConfig({ - output: "server", - adapter: aws(), -}); diff --git a/examples/aws-astro/package.json b/examples/aws-astro/package.json deleted file mode 100644 index 6c677d9e32..0000000000 --- a/examples/aws-astro/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-astro", - "type": "module", - "version": "0.0.1", - "scripts": { - "dev": "astro dev", - "start": "astro dev", - "build": "astro check && astro build", - "preview": "astro preview", - "astro": "astro" - }, - "dependencies": { - "@astrojs/check": "^0.5.10", - "@aws-sdk/client-s3": "^3.540.0", - "@aws-sdk/s3-request-presigner": "^3.540.0", - "astro": "^4.5.9", - "astro-sst": "^2.41.2", - "sst": "file:../../sdk/js", - "typescript": "^5.4.3" - } -} diff --git a/examples/aws-astro/public/favicon.svg b/examples/aws-astro/public/favicon.svg deleted file mode 100644 index f157bd1c5e..0000000000 --- a/examples/aws-astro/public/favicon.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/examples/aws-astro/src/components/Card.astro b/examples/aws-astro/src/components/Card.astro deleted file mode 100644 index bd6d5971eb..0000000000 --- a/examples/aws-astro/src/components/Card.astro +++ /dev/null @@ -1,61 +0,0 @@ ---- -interface Props { - title: string; - body: string; - href: string; -} - -const { href, title, body } = Astro.props; ---- - - - diff --git a/examples/aws-astro/src/env.d.ts b/examples/aws-astro/src/env.d.ts deleted file mode 100644 index f964fe0cff..0000000000 --- a/examples/aws-astro/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/aws-astro/src/layouts/Layout.astro b/examples/aws-astro/src/layouts/Layout.astro deleted file mode 100644 index 7b552be19b..0000000000 --- a/examples/aws-astro/src/layouts/Layout.astro +++ /dev/null @@ -1,51 +0,0 @@ ---- -interface Props { - title: string; -} - -const { title } = Astro.props; ---- - - - - - - - - - - {title} - - - - - - diff --git a/examples/aws-astro/src/pages/index.astro b/examples/aws-astro/src/pages/index.astro deleted file mode 100644 index cb2889fa2a..0000000000 --- a/examples/aws-astro/src/pages/index.astro +++ /dev/null @@ -1,74 +0,0 @@ ---- -import { Resource } from "sst"; -import Layout from '../layouts/Layout.astro'; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, -}); -const url = await getSignedUrl(new S3Client({}), command); ---- - - -
-
- - -
- -
-
- - diff --git a/examples/aws-astro/sst.config.ts b/examples/aws-astro/sst.config.ts deleted file mode 100644 index f115965f2c..0000000000 --- a/examples/aws-astro/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-astro", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - new sst.aws.Astro("MyWeb", { - link: [bucket], - }); - }, -}); diff --git a/examples/aws-astro/tsconfig.json b/examples/aws-astro/tsconfig.json deleted file mode 100644 index 77da9dd009..0000000000 --- a/examples/aws-astro/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "astro/tsconfigs/strict" -} \ No newline at end of file diff --git a/examples/aws-aurora-local/.gitignore b/examples/aws-aurora-local/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-aurora-local/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-aurora-local/index.ts b/examples/aws-aurora-local/index.ts deleted file mode 100644 index b0f7a15ddd..0000000000 --- a/examples/aws-aurora-local/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -import postgres from "postgres"; -import { Resource } from "sst"; - -const sql = postgres({ - username: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, -}); - -export async function handler() { - const result = await sql`SELECT NOW()`; - - return { - statusCode: 200, - body: `Querying ${Resource.MyPostgres.host}\n\n` + result.rows[0].now, - }; -} diff --git a/examples/aws-aurora-local/package.json b/examples/aws-aurora-local/package.json deleted file mode 100644 index d1dee66d4c..0000000000 --- a/examples/aws-aurora-local/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-aurora-local", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "postgres": "^3.4.5", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-aurora-local/sst.config.ts b/examples/aws-aurora-local/sst.config.ts deleted file mode 100644 index 940240acb1..0000000000 --- a/examples/aws-aurora-local/sst.config.ts +++ /dev/null @@ -1,87 +0,0 @@ -/// - -/** - * ## AWS Aurora local - * - * In this example, we connect to a locally running Postgres instance for dev. While - * on deploy, we use RDS Aurora. - * - * We use the [`docker run`](https://docs.docker.com/reference/cli/docker/container/run/) CLI - * to start a local container with Postgres. You don't have to use Docker, you can use - * Postgres.app or any other way to run Postgres locally. - * - * ```bash - * docker run \ - * --rm \ - * -p 5432:5432 \ - * -v $(pwd)/.sst/storage/postgres:/var/lib/postgresql/data \ - * -e POSTGRES_USER=postgres \ - * -e POSTGRES_PASSWORD=password \ - * -e POSTGRES_DB=local \ - * postgres:16.4 - * ``` - * - * The data is saved to the `.sst/storage` directory. So if you restart the dev server, the - * data will still be there. - * - * We then configure the `dev` property of the `Aurora` component with the settings for the - * local Postgres instance. - * - * ```ts title="sst.config.ts" - * dev: { - * username: "postgres", - * password: "password", - * database: "local", - * port: 5432, - * } - * ``` - * - * By providing the `dev` prop for Postgres, SST will use the local Postgres instance and - * not deploy a new RDS database when running `sst dev`. - * - * It also allows us to access the database through a Resource `link` without having to - * conditionally check if we are running locally. - * - * ```ts title="index.ts" - * const pool = new Pool({ - * host: Resource.MyPostgres.host, - * port: Resource.MyPostgres.port, - * user: Resource.MyPostgres.username, - * password: Resource.MyPostgres.password, - * database: Resource.MyPostgres.database, - * }); - * ``` - * - * The above will work in both `sst dev` and `sst deploy`. - */ -export default $config({ - app(input) { - return { - name: "aws-aurora-local", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "ec2" }); - - const database = new sst.aws.Aurora("MyPostgres", { - engine: "postgres", - dev: { - username: "postgres", - password: "password", - database: "local", - host: "localhost", - port: 5432, - }, - vpc, - }); - - new sst.aws.Function("MyFunction", { - vpc, - url: true, - link: [database], - handler: "index.handler", - }); - }, -}); diff --git a/examples/aws-aurora-local/tsconfig.json b/examples/aws-aurora-local/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-aurora-local/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-aurora-mysql/index.ts b/examples/aws-aurora-mysql/index.ts deleted file mode 100644 index dcfc68e8b2..0000000000 --- a/examples/aws-aurora-mysql/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Resource } from "sst"; -import mysql from "mysql2/promise"; - -const connection = await mysql.createConnection({ - database: Resource.MyDatabase.database, - host: Resource.MyDatabase.host, - port: Resource.MyDatabase.port, - user: Resource.MyDatabase.username, - password: Resource.MyDatabase.password, -}); - -export async function handler() { - const [rows] = await connection.query("SELECT ? as message", [ - "Hello world!", - ]); - return { - statusCode: 200, - body: rows[0].message, - }; -} diff --git a/examples/aws-aurora-mysql/package.json b/examples/aws-aurora-mysql/package.json deleted file mode 100644 index e1996251eb..0000000000 --- a/examples/aws-aurora-mysql/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-aurora-mysql", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "mysql2": "^3.12.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-aurora-mysql/sst.config.ts b/examples/aws-aurora-mysql/sst.config.ts deleted file mode 100644 index 72f57b73ac..0000000000 --- a/examples/aws-aurora-mysql/sst.config.ts +++ /dev/null @@ -1,83 +0,0 @@ -/// - -/** - * ## AWS Aurora MySQL - * - * In this example, we deploy a Aurora MySQL database. - * - * ```ts title="sst.config.ts" - * const mysql = new sst.aws.Aurora("MyDatabase", { - * engine: "mysql", - * vpc, - * }); - * ``` - * - * And link it to a Lambda function. - * - * ```ts title="sst.config.ts" {4} - * new sst.aws.Function("MyApp", { - * handler: "index.handler", - * link: [mysql], - * url: true, - * vpc, - * }); - * ``` - * - * Now in the function we can access the database. - * - * ```ts title="index.ts" - * const connection = await mysql.createConnection({ - * database: Resource.MyDatabase.database, - * host: Resource.MyDatabase.host, - * port: Resource.MyDatabase.port, - * user: Resource.MyDatabase.username, - * password: Resource.MyDatabase.password, - * }); - * ``` - * - * We also enable the `bastion` option for the VPC. This allows us to connect to the database - * from our local machine with the `sst tunnel` CLI. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * Now you can run `npx sst dev` and you can connect to the database from your local machine. - * - */ -export default $config({ - app(input) { - return { - name: "aws-aurora-mysql", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { - nat: "ec2", - bastion: true, - }); - const mysql = new sst.aws.Aurora("MyDatabase", { - engine: "mysql", - vpc, - }); - new sst.aws.Function("MyApp", { - handler: "index.handler", - link: [mysql], - url: true, - vpc, - }); - - return { - host: mysql.host, - port: mysql.port, - username: mysql.username, - password: mysql.password, - database: mysql.database, - }; - }, -}); diff --git a/examples/aws-aurora-postgres/index.ts b/examples/aws-aurora-postgres/index.ts deleted file mode 100644 index cf76e8201a..0000000000 --- a/examples/aws-aurora-postgres/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -import postgres from "postgres"; -import { Resource } from "sst"; - -const sql = postgres({ - username: Resource.MyDatabase.username, - password: Resource.MyDatabase.password, - database: Resource.MyDatabase.database, - host: Resource.MyDatabase.host, - port: Resource.MyDatabase.port, -}); - -export async function handler() { - const res = await sql`SELECT ${"Hello world!"}::text as message`; - return { - statusCode: 200, - body: res.at(0)?.message, - }; -} diff --git a/examples/aws-aurora-postgres/package.json b/examples/aws-aurora-postgres/package.json deleted file mode 100644 index 941512a6ae..0000000000 --- a/examples/aws-aurora-postgres/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-aurora-postgres", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "postgres": "^3.4.5", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-aurora-postgres/sst.config.ts b/examples/aws-aurora-postgres/sst.config.ts deleted file mode 100644 index 55cfeda634..0000000000 --- a/examples/aws-aurora-postgres/sst.config.ts +++ /dev/null @@ -1,86 +0,0 @@ -/// - -/** - * ## AWS Aurora Postgres - * - * In this example, we deploy a Aurora Postgres database. - * - * ```ts title="sst.config.ts" - * const postgres = new sst.aws.Aurora("MyDatabase", { - * engine: "postgres", - * vpc, - * }); - * ``` - * - * And link it to a Lambda function. - * - * ```ts title="sst.config.ts" {4} - * new sst.aws.Function("MyApp", { - * handler: "index.handler", - * link: [postgres], - * url: true, - * vpc, - * }); - * ``` - * - * In the function we use the [`postgres`](https://www.npmjs.com/package/postgres) package. - * - * ```ts title="index.ts" - * import postgres from "postgres"; - * import { Resource } from "sst"; - * - * const sql = postgres({ - * username: Resource.MyDatabase.username, - * password: Resource.MyDatabase.password, - * database: Resource.MyDatabase.database, - * host: Resource.MyDatabase.host, - * port: Resource.MyDatabase.port, - * }); - * ``` - * - * We also enable the `bastion` option for the VPC. This allows us to connect to the database - * from our local machine with the `sst tunnel` CLI. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * Now you can run `npx sst dev` and you can connect to the database from your local machine. - * - */ -export default $config({ - app(input) { - return { - name: "aws-aurora-postgres", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { - nat: "ec2", - bastion: true, - }); - const postgres = new sst.aws.Aurora("MyDatabase", { - engine: "postgres", - vpc, - }); - new sst.aws.Function("MyApp", { - handler: "index.handler", - link: [postgres], - url: true, - vpc, - }); - - return { - host: postgres.host, - port: postgres.port, - username: postgres.username, - password: postgres.password, - database: postgres.database, - }; - }, -}); diff --git a/examples/aws-auth-nextjs/.gitignore b/examples/aws-auth-nextjs/.gitignore deleted file mode 100644 index 845fae0e4b..0000000000 --- a/examples/aws-auth-nextjs/.gitignore +++ /dev/null @@ -1,47 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/versions - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* -.pnpm-debug.log* - -# env files (can opt-in for committing if needed) -.env* - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-auth-nextjs/app/actions.ts b/examples/aws-auth-nextjs/app/actions.ts deleted file mode 100644 index 1a3e291c37..0000000000 --- a/examples/aws-auth-nextjs/app/actions.ts +++ /dev/null @@ -1,62 +0,0 @@ -"use server"; - -import { redirect } from "next/navigation"; -import { headers as getHeaders, cookies as getCookies } from "next/headers"; -import { subjects } from "../auth/subjects"; -import { client, setTokens } from "./auth"; - -export async function auth() { - const cookies = await getCookies(); - const accessToken = cookies.get("access_token"); - const refreshToken = cookies.get("refresh_token"); - - if (!accessToken) { - return false; - } - - const verified = await client.verify(subjects, accessToken.value, { - refresh: refreshToken?.value, - }); - - if (verified.err) { - return false; - } - if (verified.tokens) { - await setTokens(verified.tokens.access, verified.tokens.refresh); - } - - return verified.subject; -} - -export async function login() { - const cookies = await getCookies(); - const accessToken = cookies.get("access_token"); - const refreshToken = cookies.get("refresh_token"); - - if (accessToken) { - const verified = await client.verify(subjects, accessToken.value, { - refresh: refreshToken?.value, - }); - if (!verified.err && verified.tokens) { - await setTokens(verified.tokens.access, verified.tokens.refresh); - redirect("/"); - } - } - - const headers = await getHeaders(); - const host = headers.get("host"); - const protocol = host?.includes("localhost") ? "http" : "https"; - const { url } = await client.authorize( - `${protocol}://${host}/api/callback`, - "code", - ); - redirect(url); -} - -export async function logout() { - const cookies = await getCookies(); - cookies.delete("access_token"); - cookies.delete("refresh_token"); - - redirect("/"); -} diff --git a/examples/aws-auth-nextjs/app/api/callback/route.ts b/examples/aws-auth-nextjs/app/api/callback/route.ts deleted file mode 100644 index 6bcce834a7..0000000000 --- a/examples/aws-auth-nextjs/app/api/callback/route.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { client, setTokens } from "../../auth"; -import { type NextRequest, NextResponse } from "next/server"; - -export async function GET(req: NextRequest) { - const url = new URL(req.url); - const code = url.searchParams.get("code"); - - const exchanged = await client.exchange(code!, `${url.origin}/api/callback`); - - if (exchanged.err) return NextResponse.json(exchanged.err, { status: 400 }); - - await setTokens(exchanged.tokens.access, exchanged.tokens.refresh); - - return NextResponse.redirect(`${url.origin}/`); -} diff --git a/examples/aws-auth-nextjs/app/auth.ts b/examples/aws-auth-nextjs/app/auth.ts deleted file mode 100644 index 792ad3aeea..0000000000 --- a/examples/aws-auth-nextjs/app/auth.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Resource } from "sst"; -import { createClient } from "@openauthjs/openauth/client"; -import { cookies as getCookies } from "next/headers"; - -export const client = createClient({ - clientID: "nextjs", - issuer: Resource.MyAuth.url, -}); - -export async function setTokens(access: string, refresh: string) { - const cookies = await getCookies(); - - cookies.set({ - name: "access_token", - value: access, - httpOnly: true, - sameSite: "lax", - path: "/", - maxAge: 34560000, - }); - cookies.set({ - name: "refresh_token", - value: refresh, - httpOnly: true, - sameSite: "lax", - path: "/", - maxAge: 34560000, - }); -} diff --git a/examples/aws-auth-nextjs/app/globals.css b/examples/aws-auth-nextjs/app/globals.css deleted file mode 100644 index e3734be15e..0000000000 --- a/examples/aws-auth-nextjs/app/globals.css +++ /dev/null @@ -1,42 +0,0 @@ -:root { - --background: #ffffff; - --foreground: #171717; -} - -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: var(--foreground); - background: var(--background); - font-family: Arial, Helvetica, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-auth-nextjs/app/layout.tsx b/examples/aws-auth-nextjs/app/layout.tsx deleted file mode 100644 index 8cdb9eb3b3..0000000000 --- a/examples/aws-auth-nextjs/app/layout.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import type { Metadata } from "next" -import { Geist, Geist_Mono } from "next/font/google" -import "./globals.css" - -const geistSans = Geist({ - variable: "--font-geist-sans", - subsets: ["latin"], -}) - -const geistMono = Geist_Mono({ - variable: "--font-geist-mono", - subsets: ["latin"], -}) - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -} - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode -}>) { - return ( - - - {children} - - - ) -} diff --git a/examples/aws-auth-nextjs/app/page.module.css b/examples/aws-auth-nextjs/app/page.module.css deleted file mode 100644 index 1f4ec4aaf0..0000000000 --- a/examples/aws-auth-nextjs/app/page.module.css +++ /dev/null @@ -1,200 +0,0 @@ -.page { - --gray-rgb: 0, 0, 0; - --gray-alpha-200: rgba(var(--gray-rgb), 0.08); - --gray-alpha-100: rgba(var(--gray-rgb), 0.05); - - --button-primary-hover: #383838; - --button-secondary-hover: #f2f2f2; - - display: grid; - grid-template-rows: 20px 1fr 20px; - align-items: center; - justify-items: center; - min-height: 100svh; - padding: 80px; - gap: 64px; - font-family: var(--font-geist-sans); -} - -@media (prefers-color-scheme: dark) { - .page { - --gray-rgb: 255, 255, 255; - --gray-alpha-200: rgba(var(--gray-rgb), 0.145); - --gray-alpha-100: rgba(var(--gray-rgb), 0.06); - - --button-primary-hover: #ccc; - --button-secondary-hover: #1a1a1a; - } -} - -.main { - display: flex; - flex-direction: column; - gap: 32px; - grid-row-start: 2; -} - -.main ol { - font-family: var(--font-geist-mono); - padding-left: 0; - margin: 0; - font-size: 14px; - line-height: 24px; - letter-spacing: -0.01em; - list-style-position: inside; -} - -.main li:not(:last-of-type) { - margin-bottom: 8px; -} - -.main code { - font-family: inherit; - background: var(--gray-alpha-100); - padding: 2px 4px; - border-radius: 4px; - font-weight: 600; -} - -.ctas { - display: flex; - gap: 16px; -} - -.ctas a { - appearance: none; - border-radius: 128px; - height: 48px; - padding: 0 20px; - border: none; - border: 1px solid transparent; - transition: - background 0.2s, - color 0.2s, - border-color 0.2s; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - font-size: 16px; - line-height: 20px; - font-weight: 500; -} - -a.primary { - background: var(--foreground); - color: var(--background); - gap: 8px; -} - -a.secondary { - border-color: var(--gray-alpha-200); - min-width: 180px; -} - -.footer { - grid-row-start: 3; - display: flex; - gap: 24px; -} - -.footer a { - display: flex; - align-items: center; - gap: 8px; -} - -.footer img { - flex-shrink: 0; -} - -/* Enable hover only on non-touch devices */ -@media (hover: hover) and (pointer: fine) { - a.primary:hover { - background: var(--button-primary-hover); - border-color: transparent; - } - - a.secondary:hover { - background: var(--button-secondary-hover); - border-color: transparent; - } - - .footer a:hover { - text-decoration: underline; - text-underline-offset: 4px; - } -} - -@media (max-width: 600px) { - .page { - padding: 32px; - padding-bottom: 80px; - } - - .main { - align-items: center; - } - - .main ol { - text-align: center; - } - - .ctas { - flex-direction: column; - } - - .ctas a { - font-size: 14px; - height: 40px; - padding: 0 16px; - } - - a.secondary { - min-width: auto; - } - - .footer { - flex-wrap: wrap; - align-items: center; - justify-content: center; - } -} - -@media (prefers-color-scheme: dark) { - .logo { - filter: invert(); - } -} - -.ctas button { - appearance: none; - background: transparent; - border-radius: 128px; - height: 48px; - padding: 0 20px; - border: none; - border: 1px solid transparent; - transition: - background 0.2s, - color 0.2s, - border-color 0.2s; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - font-size: 16px; - line-height: 20px; - font-weight: 500; -} - -button.primary { - background: var(--foreground); - color: var(--background); - gap: 8px; -} - -button.secondary { - border-color: var(--gray-alpha-200); - min-width: 180px; -} diff --git a/examples/aws-auth-nextjs/app/page.tsx b/examples/aws-auth-nextjs/app/page.tsx deleted file mode 100644 index 0916983bd4..0000000000 --- a/examples/aws-auth-nextjs/app/page.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import Image from "next/image"; -import styles from "./page.module.css"; -import { auth, login, logout } from "./actions"; - -export default async function Home() { - const subject = await auth(); - - return ( -
-
- Next.js logo -
    - {subject ? ( - <> -
  1. - Logged in as {subject.properties.id}. -
  2. -
  3. - And then check out app/page.tsx. -
  4. - - ) : ( - <> -
  5. Login with your email and password.
  6. -
  7. - And then check out app/page.tsx. -
  8. - - )} -
- -
- {subject ? ( -
- -
- ) : ( -
- -
- )} -
-
-
- ); -} diff --git a/examples/aws-auth-nextjs/auth/index.ts b/examples/aws-auth-nextjs/auth/index.ts deleted file mode 100644 index 7e298f674d..0000000000 --- a/examples/aws-auth-nextjs/auth/index.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { handle } from "hono/aws-lambda"; -import { issuer } from "@openauthjs/openauth"; -import { CodeUI } from "@openauthjs/openauth/ui/code"; -import { CodeProvider } from "@openauthjs/openauth/provider/code"; -import { subjects } from "./subjects"; - -async function getUser(email: string) { - // Get user from database and return user ID - return "123"; -} - -const app = issuer({ - subjects, - // Remove after setting custom domain - allow: async () => true, - providers: { - code: CodeProvider( - CodeUI({ - sendCode: async (email, code) => { - console.log(email, code); - }, - }), - ), - }, - success: async (ctx, value) => { - if (value.provider === "code") { - return ctx.subject("user", { - id: await getUser(value.claims.email), - }); - } - throw new Error("Invalid provider"); - }, -}); - -export const handler = handle(app); diff --git a/examples/aws-auth-nextjs/auth/subjects.ts b/examples/aws-auth-nextjs/auth/subjects.ts deleted file mode 100644 index f8e6ed2f57..0000000000 --- a/examples/aws-auth-nextjs/auth/subjects.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { object, string } from "valibot"; -import { createSubjects } from "@openauthjs/openauth/subject"; - -export const subjects = createSubjects({ - user: object({ - id: string(), - }), -}); diff --git a/examples/aws-auth-nextjs/next.config.ts b/examples/aws-auth-nextjs/next.config.ts deleted file mode 100644 index 3b84f68abf..0000000000 --- a/examples/aws-auth-nextjs/next.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { NextConfig } from "next" - -const nextConfig: NextConfig = { - /* config options here */ -} - -export default nextConfig diff --git a/examples/aws-auth-nextjs/package.json b/examples/aws-auth-nextjs/package.json deleted file mode 100644 index 0c83c699ac..0000000000 --- a/examples/aws-auth-nextjs/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "aws-auth-nextjs", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "@openauthjs/openauth": "latest", - "hono": "^4.6.16", - "next": "15.1.4", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "sst": "file:../../sdk/js", - "valibot": "^1.0.0-beta.11" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^19", - "@types/react-dom": "^19", - "typescript": "^5" - } -} diff --git a/examples/aws-auth-nextjs/public/file.svg b/examples/aws-auth-nextjs/public/file.svg deleted file mode 100644 index 004145cddf..0000000000 --- a/examples/aws-auth-nextjs/public/file.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-nextjs/public/globe.svg b/examples/aws-auth-nextjs/public/globe.svg deleted file mode 100644 index 567f17b0d7..0000000000 --- a/examples/aws-auth-nextjs/public/globe.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-nextjs/public/next.svg b/examples/aws-auth-nextjs/public/next.svg deleted file mode 100644 index 5174b28c56..0000000000 --- a/examples/aws-auth-nextjs/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-nextjs/public/vercel.svg b/examples/aws-auth-nextjs/public/vercel.svg deleted file mode 100644 index 7705396033..0000000000 --- a/examples/aws-auth-nextjs/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-nextjs/public/window.svg b/examples/aws-auth-nextjs/public/window.svg deleted file mode 100644 index b2b2a44f6e..0000000000 --- a/examples/aws-auth-nextjs/public/window.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-nextjs/sst.config.ts b/examples/aws-auth-nextjs/sst.config.ts deleted file mode 100644 index 17a8c02f8a..0000000000 --- a/examples/aws-auth-nextjs/sst.config.ts +++ /dev/null @@ -1,21 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-auth-nextjs", - removal: input?.stage === "production" ? "retain" : "remove", - protect: ["production"].includes(input?.stage), - home: "aws", - }; - }, - async run() { - const auth = new sst.aws.Auth("MyAuth", { - issuer: "auth/index.handler", - }); - - new sst.aws.Nextjs("MyWeb", { - link: [auth], - }); - }, -}); diff --git a/examples/aws-auth-nextjs/tsconfig.json b/examples/aws-auth-nextjs/tsconfig.json deleted file mode 100644 index 30ced59690..0000000000 --- a/examples/aws-auth-nextjs/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2017", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules", "sst.config.ts"] -} diff --git a/examples/aws-auth-react/.gitignore b/examples/aws-auth-react/.gitignore deleted file mode 100644 index e2ead72a02..0000000000 --- a/examples/aws-auth-react/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -# dependencies -node_modules - -# sst -.sst - -# tmp files -.#* - -# env -.env*.local -.env - -# opennext -.open-next - -# misc -.DS_Store diff --git a/examples/aws-auth-react/LICENSE b/examples/aws-auth-react/LICENSE deleted file mode 100644 index c6eca6eed7..0000000000 --- a/examples/aws-auth-react/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 SST - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/examples/aws-auth-react/infra/api.ts b/examples/aws-auth-react/infra/api.ts deleted file mode 100644 index e3e4d07413..0000000000 --- a/examples/aws-auth-react/infra/api.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { auth } from "./auth"; - -export const api = new sst.aws.Function("MyApi", { - url: true, - link: [auth], - handler: "packages/functions/src/api.handler", -}); diff --git a/examples/aws-auth-react/infra/auth.ts b/examples/aws-auth-react/infra/auth.ts deleted file mode 100644 index 96e0d2c7af..0000000000 --- a/examples/aws-auth-react/infra/auth.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const auth = new sst.aws.Auth("MyAuth", { - issuer: "packages/functions/src/auth.handler", -}); - diff --git a/examples/aws-auth-react/infra/web.ts b/examples/aws-auth-react/infra/web.ts deleted file mode 100644 index c49c45496d..0000000000 --- a/examples/aws-auth-react/infra/web.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { api } from "./api"; -import { auth } from "./auth"; - -export const web = new sst.aws.StaticSite("MyWeb", { - path: "packages/web", - build: { - output: "dist", - command: "npm run build", - }, - environment: { - VITE_API_URL: api.url, - VITE_AUTH_URL: auth.url, - }, -}); - diff --git a/examples/aws-auth-react/package.json b/examples/aws-auth-react/package.json deleted file mode 100644 index 1f1027b316..0000000000 --- a/examples/aws-auth-react/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-auth-react", - "version": "0.0.0", - "workspaces": [ - "packages/*" - ], - "scripts": {}, - "devDependencies": { - "@tsconfig/node22": "^22", - "typescript": "^5" - }, - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-auth-react/packages/core/package.json b/examples/aws-auth-react/packages/core/package.json deleted file mode 100644 index e7d239d85e..0000000000 --- a/examples/aws-auth-react/packages/core/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "@aws-auth-react/core", - "type": "module", - "version": "0.0.0", - "scripts": { - "test": "sst shell vitest" - }, - "exports": { - "./*": [ - "./src/*/index.ts", - "./src/*.ts" - ] - }, - "dependencies": { - "sst": "file:../../../../sdk/js" - }, - "devDependencies": { - "vitest": "^2" - } -} diff --git a/examples/aws-auth-react/packages/core/src/example/index.ts b/examples/aws-auth-react/packages/core/src/example/index.ts deleted file mode 100644 index 9cb1c03477..0000000000 --- a/examples/aws-auth-react/packages/core/src/example/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export namespace Example { - export function hello() { - return "Hello, world!"; - } -} diff --git a/examples/aws-auth-react/packages/core/src/example/test/index.test.ts b/examples/aws-auth-react/packages/core/src/example/test/index.test.ts deleted file mode 100644 index 18d84d117b..0000000000 --- a/examples/aws-auth-react/packages/core/src/example/test/index.test.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { expect, test } from "vitest"; -import { Example } from "../"; - -test("Hello test", () => { - const expected = "Hello, world!"; - - expect(Example.hello()).toEqual(expected); -}); diff --git a/examples/aws-auth-react/packages/core/tsconfig.json b/examples/aws-auth-react/packages/core/tsconfig.json deleted file mode 100644 index be3c6ace73..0000000000 --- a/examples/aws-auth-react/packages/core/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@tsconfig/node22/tsconfig.json", - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "Bundler", - }, -} diff --git a/examples/aws-auth-react/packages/functions/package.json b/examples/aws-auth-react/packages/functions/package.json deleted file mode 100644 index c6348f56a0..0000000000 --- a/examples/aws-auth-react/packages/functions/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@aws-auth-react/functions", - "version": "0.0.0", - "type": "module", - "dependencies": { - "@aws-auth-react/core": "*", - "@openauthjs/openauth": "^0.3.6", - "hono": "^4.6.18", - "sst": "file:../../../../sdk/js", - "valibot": "^1.0.0-beta.14" - }, - "devDependencies": { - "@types/aws-lambda": "^8" - } -} diff --git a/examples/aws-auth-react/packages/functions/src/api.ts b/examples/aws-auth-react/packages/functions/src/api.ts deleted file mode 100644 index ee2410c0c3..0000000000 --- a/examples/aws-auth-react/packages/functions/src/api.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Hono } from "hono"; -import { Resource } from "sst"; -import { handle } from "hono/aws-lambda"; -import { createClient } from "@openauthjs/openauth/client"; -import { subjects } from "./subjects"; - -const client = createClient({ - clientID: "jwt-api", - issuer: Resource.MyAuth.url, -}); - -async function getUserInfo(userId: string) { - // Get user from database - return { - userId, - name: "Patrick Star", - }; -} - -const app = new Hono(); - -app.get("/me", async (c) => { - const authHeader = c.req.header("Authorization"); - - if (!authHeader) { - return c.status(401); - } - - const token = authHeader.split(" ")[1]; - const verified = await client.verify(subjects, token); - - if (verified.err) { - return c.status(401); - } - - return c.json(await getUserInfo(verified.subject.properties.id)); -}); - -export const handler = handle(app); diff --git a/examples/aws-auth-react/packages/functions/src/auth.ts b/examples/aws-auth-react/packages/functions/src/auth.ts deleted file mode 100644 index 7e298f674d..0000000000 --- a/examples/aws-auth-react/packages/functions/src/auth.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { handle } from "hono/aws-lambda"; -import { issuer } from "@openauthjs/openauth"; -import { CodeUI } from "@openauthjs/openauth/ui/code"; -import { CodeProvider } from "@openauthjs/openauth/provider/code"; -import { subjects } from "./subjects"; - -async function getUser(email: string) { - // Get user from database and return user ID - return "123"; -} - -const app = issuer({ - subjects, - // Remove after setting custom domain - allow: async () => true, - providers: { - code: CodeProvider( - CodeUI({ - sendCode: async (email, code) => { - console.log(email, code); - }, - }), - ), - }, - success: async (ctx, value) => { - if (value.provider === "code") { - return ctx.subject("user", { - id: await getUser(value.claims.email), - }); - } - throw new Error("Invalid provider"); - }, -}); - -export const handler = handle(app); diff --git a/examples/aws-auth-react/packages/functions/src/subjects.ts b/examples/aws-auth-react/packages/functions/src/subjects.ts deleted file mode 100644 index f8e6ed2f57..0000000000 --- a/examples/aws-auth-react/packages/functions/src/subjects.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { object, string } from "valibot"; -import { createSubjects } from "@openauthjs/openauth/subject"; - -export const subjects = createSubjects({ - user: object({ - id: string(), - }), -}); diff --git a/examples/aws-auth-react/packages/functions/tsconfig.json b/examples/aws-auth-react/packages/functions/tsconfig.json deleted file mode 100644 index be3c6ace73..0000000000 --- a/examples/aws-auth-react/packages/functions/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@tsconfig/node22/tsconfig.json", - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "Bundler", - }, -} diff --git a/examples/aws-auth-react/packages/scripts/package.json b/examples/aws-auth-react/packages/scripts/package.json deleted file mode 100644 index 39ae89e8c4..0000000000 --- a/examples/aws-auth-react/packages/scripts/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "@aws-auth-react/scripts", - "version": "0.0.0", - "type": "module", - "dependencies": { - "@aws-auth-react/core": "*", - "sst": "file:../../../../sdk/js" - }, - "scripts": { - "shell": "sst shell tsx" - }, - "devDependencies": { - "@types/node": "^22", - "tsx": "^4" - } -} diff --git a/examples/aws-auth-react/packages/scripts/src/example.ts b/examples/aws-auth-react/packages/scripts/src/example.ts deleted file mode 100644 index 44c3c0263b..0000000000 --- a/examples/aws-auth-react/packages/scripts/src/example.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { Resource } from "sst"; -import { Example } from "@aws-auth-react/core/example"; - -console.log(`${Example.hello()} Linked to ${Resource.MyBucket.name}.`); diff --git a/examples/aws-auth-react/packages/scripts/tsconfig.json b/examples/aws-auth-react/packages/scripts/tsconfig.json deleted file mode 100644 index be3c6ace73..0000000000 --- a/examples/aws-auth-react/packages/scripts/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@tsconfig/node22/tsconfig.json", - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "Bundler", - }, -} diff --git a/examples/aws-auth-react/packages/web/.gitignore b/examples/aws-auth-react/packages/web/.gitignore deleted file mode 100644 index a547bf36d8..0000000000 --- a/examples/aws-auth-react/packages/web/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr -*.local - -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? diff --git a/examples/aws-auth-react/packages/web/eslint.config.js b/examples/aws-auth-react/packages/web/eslint.config.js deleted file mode 100644 index 092408a9f0..0000000000 --- a/examples/aws-auth-react/packages/web/eslint.config.js +++ /dev/null @@ -1,28 +0,0 @@ -import js from '@eslint/js' -import globals from 'globals' -import reactHooks from 'eslint-plugin-react-hooks' -import reactRefresh from 'eslint-plugin-react-refresh' -import tseslint from 'typescript-eslint' - -export default tseslint.config( - { ignores: ['dist'] }, - { - extends: [js.configs.recommended, ...tseslint.configs.recommended], - files: ['**/*.{ts,tsx}'], - languageOptions: { - ecmaVersion: 2020, - globals: globals.browser, - }, - plugins: { - 'react-hooks': reactHooks, - 'react-refresh': reactRefresh, - }, - rules: { - ...reactHooks.configs.recommended.rules, - 'react-refresh/only-export-components': [ - 'warn', - { allowConstantExport: true }, - ], - }, - }, -) diff --git a/examples/aws-auth-react/packages/web/index.html b/examples/aws-auth-react/packages/web/index.html deleted file mode 100644 index e4b78eae12..0000000000 --- a/examples/aws-auth-react/packages/web/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Vite + React + TS - - -
- - - diff --git a/examples/aws-auth-react/packages/web/package.json b/examples/aws-auth-react/packages/web/package.json deleted file mode 100644 index 4afc4bb251..0000000000 --- a/examples/aws-auth-react/packages/web/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "web", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc -b && vite build", - "lint": "eslint .", - "preview": "vite preview" - }, - "dependencies": { - "@openauthjs/openauth": "^0.3.8", - "react": "^18.3.1", - "react-dom": "^18.3.1" - }, - "devDependencies": { - "@eslint/js": "^9.17.0", - "@types/react": "^18.3.18", - "@types/react-dom": "^18.3.5", - "@vitejs/plugin-react": "^4.3.4", - "eslint": "^9.17.0", - "eslint-plugin-react-hooks": "^5.0.0", - "eslint-plugin-react-refresh": "^0.4.16", - "globals": "^15.14.0", - "typescript": "~5.6.2", - "typescript-eslint": "^8.18.2", - "vite": "^6.0.5" - } -} diff --git a/examples/aws-auth-react/packages/web/public/vite.svg b/examples/aws-auth-react/packages/web/public/vite.svg deleted file mode 100644 index e7b8dfb1b2..0000000000 --- a/examples/aws-auth-react/packages/web/public/vite.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-react/packages/web/src/App.css b/examples/aws-auth-react/packages/web/src/App.css deleted file mode 100644 index 79f55915a0..0000000000 --- a/examples/aws-auth-react/packages/web/src/App.css +++ /dev/null @@ -1,48 +0,0 @@ -#root { - max-width: 1280px; - margin: 0 auto; - padding: 2rem; - text-align: center; -} - -.logo { - height: 6em; - padding: 1.5em; - will-change: filter; - transition: filter 300ms; -} -.logo:hover { - filter: drop-shadow(0 0 2em #646cffaa); -} -.logo.react:hover { - filter: drop-shadow(0 0 2em #61dafbaa); -} - -@keyframes logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -} - -@media (prefers-reduced-motion: no-preference) { - a:nth-of-type(2) .logo { - animation: logo-spin infinite 20s linear; - } -} - -.card { - padding: 2em; -} - -.read-the-docs { - color: #888; -} - -.controls { - display: flex; - justify-content: center; - gap: 1rem; -} diff --git a/examples/aws-auth-react/packages/web/src/App.tsx b/examples/aws-auth-react/packages/web/src/App.tsx deleted file mode 100644 index e049b006ec..0000000000 --- a/examples/aws-auth-react/packages/web/src/App.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { useState } from "react"; -import { useAuth } from "./AuthContext"; -import "./App.css"; - -function App() { - const auth = useAuth(); - const [status, setStatus] = useState(""); - - async function callApi() { - const res = await fetch(`${import.meta.env.VITE_API_URL}me`, { - headers: { - Authorization: `Bearer ${await auth.getToken()}`, - }, - }); - - setStatus(res.ok ? await res.text() : "error"); - } - - return !auth.loaded ? ( -
Loading...
- ) : ( -
- {auth.loggedIn ? ( -
-

- Logged in - {auth.userId && as {auth.userId}} -

- {status !== "" &&

API call: {status}

} -
- - -
-
- ) : ( - - )} -
- ); -} - -export default App; diff --git a/examples/aws-auth-react/packages/web/src/AuthContext.tsx b/examples/aws-auth-react/packages/web/src/AuthContext.tsx deleted file mode 100644 index 821757a6f9..0000000000 --- a/examples/aws-auth-react/packages/web/src/AuthContext.tsx +++ /dev/null @@ -1,156 +0,0 @@ -import { - useRef, - useState, - ReactNode, - useEffect, - useContext, - createContext, -} from "react"; -import { createClient } from "@openauthjs/openauth/client"; - -const client = createClient({ - clientID: "web", - issuer: import.meta.env.VITE_AUTH_URL, -}); - -interface AuthContextType { - userId?: string; - loaded: boolean; - loggedIn: boolean; - logout: () => void; - login: () => Promise; - getToken: () => Promise; -} - -const AuthContext = createContext({} as AuthContextType); - -export function AuthProvider({ children }: { children: ReactNode }) { - const initializing = useRef(true); - const [loaded, setLoaded] = useState(false); - const [loggedIn, setLoggedIn] = useState(false); - const token = useRef(undefined); - const [userId, setUserId] = useState(); - - useEffect(() => { - const hash = new URLSearchParams(location.search.slice(1)); - const code = hash.get("code"); - const state = hash.get("state"); - - if (!initializing.current) { - return; - } - - initializing.current = false; - - if (code && state) { - callback(code, state); - return; - } - - auth(); - }, []); - - async function auth() { - const token = await refreshTokens(); - - if (token) { - await user(); - } - - setLoaded(true); - } - - async function refreshTokens() { - const refresh = localStorage.getItem("refresh"); - if (!refresh) return; - const next = await client.refresh(refresh, { - access: token.current, - }); - if (next.err) return; - if (!next.tokens) return token.current; - - localStorage.setItem("refresh", next.tokens.refresh); - token.current = next.tokens.access; - - return next.tokens.access; - } - - async function getToken() { - const token = await refreshTokens(); - - if (!token) { - await login(); - return; - } - - return token; - } - - async function login() { - const { challenge, url } = await client.authorize(location.origin, "code", { - pkce: true, - }); - sessionStorage.setItem("challenge", JSON.stringify(challenge)); - location.href = url; - } - - async function callback(code: string, state: string) { - console.log("callback", code, state); - const challenge = JSON.parse(sessionStorage.getItem("challenge")!); - if (code) { - if (state === challenge.state && challenge.verifier) { - const exchanged = await client.exchange( - code!, - location.origin, - challenge.verifier, - ); - if (!exchanged.err) { - token.current = exchanged.tokens?.access; - localStorage.setItem("refresh", exchanged.tokens.refresh); - } - } - window.location.replace("/"); - } - } - - async function user() { - const res = await fetch(`${import.meta.env.VITE_API_URL}me`, { - headers: { - Authorization: `Bearer ${token.current}`, - }, - }); - - if (res.ok) { - const user = await res.json(); - - setUserId(user.userId); - setLoggedIn(true); - } - } - - function logout() { - localStorage.removeItem("refresh"); - token.current = undefined; - - window.location.replace("/"); - } - - return ( - - {children} - - ); -} - -export function useAuth() { - return useContext(AuthContext); -} diff --git a/examples/aws-auth-react/packages/web/src/assets/react.svg b/examples/aws-auth-react/packages/web/src/assets/react.svg deleted file mode 100644 index 6c87de9bb3..0000000000 --- a/examples/aws-auth-react/packages/web/src/assets/react.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-auth-react/packages/web/src/index.css b/examples/aws-auth-react/packages/web/src/index.css deleted file mode 100644 index 6119ad9a8f..0000000000 --- a/examples/aws-auth-react/packages/web/src/index.css +++ /dev/null @@ -1,68 +0,0 @@ -:root { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - line-height: 1.5; - font-weight: 400; - - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; - - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; -} -a:hover { - color: #535bf2; -} - -body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; -} - -h1 { - font-size: 3.2em; - line-height: 1.1; -} - -button { - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; -} -button:hover { - border-color: #646cff; -} -button:focus, -button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; -} - -@media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } -} diff --git a/examples/aws-auth-react/packages/web/src/main.tsx b/examples/aws-auth-react/packages/web/src/main.tsx deleted file mode 100644 index 2778110c85..0000000000 --- a/examples/aws-auth-react/packages/web/src/main.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { StrictMode } from "react"; -import { createRoot } from "react-dom/client"; -import { AuthProvider } from "./AuthContext"; -import "./index.css"; -import App from "./App.tsx"; - -createRoot(document.getElementById("root")!).render( - - - - - , -); diff --git a/examples/aws-auth-react/packages/web/src/vite-env.d.ts b/examples/aws-auth-react/packages/web/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/aws-auth-react/packages/web/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/aws-auth-react/packages/web/tsconfig.app.json b/examples/aws-auth-react/packages/web/tsconfig.app.json deleted file mode 100644 index 358ca9ba93..0000000000 --- a/examples/aws-auth-react/packages/web/tsconfig.app.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", - "target": "ES2020", - "useDefineForClassFields": true, - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "module": "ESNext", - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, - "jsx": "react-jsx", - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true - }, - "include": ["src"] -} diff --git a/examples/aws-auth-react/packages/web/tsconfig.json b/examples/aws-auth-react/packages/web/tsconfig.json deleted file mode 100644 index 1ffef600d9..0000000000 --- a/examples/aws-auth-react/packages/web/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "files": [], - "references": [ - { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" } - ] -} diff --git a/examples/aws-auth-react/packages/web/tsconfig.node.json b/examples/aws-auth-react/packages/web/tsconfig.node.json deleted file mode 100644 index db0becc8b0..0000000000 --- a/examples/aws-auth-react/packages/web/tsconfig.node.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", - "target": "ES2022", - "lib": ["ES2023"], - "module": "ESNext", - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true - }, - "include": ["vite.config.ts"] -} diff --git a/examples/aws-auth-react/packages/web/vite.config.ts b/examples/aws-auth-react/packages/web/vite.config.ts deleted file mode 100644 index 8b0f57b91a..0000000000 --- a/examples/aws-auth-react/packages/web/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' - -// https://vite.dev/config/ -export default defineConfig({ - plugins: [react()], -}) diff --git a/examples/aws-auth-react/sst.config.ts b/examples/aws-auth-react/sst.config.ts deleted file mode 100644 index ac4f254171..0000000000 --- a/examples/aws-auth-react/sst.config.ts +++ /dev/null @@ -1,116 +0,0 @@ -/// - -/** - * ## AWS OpenAuth React SPA - * - * This is a full-stack monorepo app shows the OpenAuth flow for a single-page app - * and an authenticated API. It has: - * - * - React SPA built with Vite and the `StaticSite` component in the `packages/web` - * directory. - * ```ts title="infra/web.ts" - * export const web = new sst.aws.StaticSite("MyWeb", { - * path: "packages/web", - * build: { - * output: "dist", - * command: "npm run build", - * }, - * environment: { - * VITE_API_URL: api.url, - * VITE_AUTH_URL: auth.url, - * }, - * }); - * ``` - * - * - API with Hono and the `Function` component in `packages/functions/src/api.ts`. - * ```ts title="infra/api.ts" - * export const api = new sst.aws.Function("MyApi", { - * url: true, - * link: [auth], - * handler: "packages/functions/src/api.handler", - * }); - * ``` - * - * - OpenAuth with the `Auth` component in `packages/functions/src/auth.ts`. - * ```ts title="infra/auth.ts" - * export const auth = new sst.aws.Auth("MyAuth", { - * issuer: "packages/functions/src/auth.handler", - * }); - * ``` - * - * The React frontend uses a `AuthContext` provider to manage the auth flow. - * - * ```tsx title="packages/web/src/AuthContext.tsx" - * - * {children} - * - * ``` - * - * Now in `App.tsx`, we can use the `useAuth` hook. - * - * ```tsx title="packages/web/src/App.tsx" - * const auth = useAuth(); - * - * return !auth.loaded ? ( - *
Loading...
- * ) : ( - *
- * {auth.loggedIn ? ( - *
- *

- * Logged in - * {auth.userId && as {auth.userId}} - *

- *
- * ) : ( - * - * )} - *
- * ); - * ``` - * - * Once authenticated, we can call our authenticated API by passing in the access - * token. - * - * ```tsx title="packages/web/src/App.tsx" {3} - * await fetch(`${import.meta.env.VITE_API_URL}me`, { - * headers: { - * Authorization: `Bearer ${await auth.getToken()}`, - * }, - * }); - * ``` - * - * The API uses the OpenAuth client to verify the token. - * - * ```ts title="packages/functions/src/api.ts" {3} - * const authHeader = c.req.header("Authorization"); - * const token = authHeader.split(" ")[1]; - * const verified = await client.verify(subjects, token); - * ``` - * - * The `sst.config.ts` dynamically imports all the `infra/` files. - */ -export default $config({ - app(input) { - return { - name: "aws-auth-react", - removal: input?.stage === "production" ? "retain" : "remove", - protect: ["production"].includes(input?.stage), - home: "aws", - }; - }, - async run() { - await import("./infra/auth"); - await import("./infra/api"); - await import("./infra/web"); - }, -}); diff --git a/examples/aws-auth-react/tsconfig.json b/examples/aws-auth-react/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-auth-react/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-base/.gitignore b/examples/aws-base/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-base/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-base/package.json b/examples/aws-base/package.json deleted file mode 100644 index 8721162115..0000000000 --- a/examples/aws-base/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-base", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-base/sst.config.ts b/examples/aws-base/sst.config.ts deleted file mode 100644 index 825dc1c077..0000000000 --- a/examples/aws-base/sst.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-base", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() {}, -}); diff --git a/examples/aws-base/tsconfig.json b/examples/aws-base/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-base/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-bucket-lifecycle-rules/package.json b/examples/aws-bucket-lifecycle-rules/package.json deleted file mode 100644 index 5a92f09ea9..0000000000 --- a/examples/aws-bucket-lifecycle-rules/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-bucket-lifecycle-rules", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bucket-lifecycle-rules/sst.config.ts b/examples/aws-bucket-lifecycle-rules/sst.config.ts deleted file mode 100644 index 012b5fd95c..0000000000 --- a/examples/aws-bucket-lifecycle-rules/sst.config.ts +++ /dev/null @@ -1,38 +0,0 @@ -/// - -/** - * ## Bucket lifecycle policies - * - * Configure S3 bucket lifecycle policies to expire objects automatically. - */ -export default $config({ - app(input) { - return { - name: "aws-bucket-lifecycle-rules", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - lifecycle: [ - { - expiresIn: "60 days", - }, - { - id: "expire-tmp-files", - prefix: "tmp/", - expiresIn: "30 days", - }, - { - prefix: "data/", - expiresAt: "2028-12-31", - }, - ], - }); - - return { - bucket: bucket.name, - }; - }, -}); diff --git a/examples/aws-bucket-policy/package.json b/examples/aws-bucket-policy/package.json deleted file mode 100644 index a336ca8ce1..0000000000 --- a/examples/aws-bucket-policy/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-bucket-policy", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bucket-policy/sst.config.ts b/examples/aws-bucket-policy/sst.config.ts deleted file mode 100644 index 85140112f0..0000000000 --- a/examples/aws-bucket-policy/sst.config.ts +++ /dev/null @@ -1,38 +0,0 @@ -/// - -/** - * ## Bucket policy - * - * Create an S3 bucket and transform its bucket policy. - */ -export default $config({ - app(input) { - return { - name: "aws-bucket-policy", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - transform: { - policy: (args) => { - // use sst.aws.iamEdit helper function to manipulate IAM policy - // containing Output values from components - args.policy = sst.aws.iamEdit(args.policy, (policy) => { - policy.Statement.push({ - Effect: "Allow", - Principal: { Service: "ses.amazonaws.com" }, - Action: "s3:PutObject", - Resource: $interpolate`arn:aws:s3:::${args.bucket}/*`, - }); - }); - }, - }, - }); - - return { - bucket: bucket.name, - }; - }, -}); diff --git a/examples/aws-bucket-queue-subscriber/package.json b/examples/aws-bucket-queue-subscriber/package.json deleted file mode 100644 index f0361aa21e..0000000000 --- a/examples/aws-bucket-queue-subscriber/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-bucket-queue-subscriber", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "@types/aws-lambda": "^8.10.149", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bucket-queue-subscriber/sst.config.ts b/examples/aws-bucket-queue-subscriber/sst.config.ts deleted file mode 100644 index 4b10069241..0000000000 --- a/examples/aws-bucket-queue-subscriber/sst.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// - -/** - * ## Bucket queue notifications - * - * Create an S3 bucket and subscribe to its events with an SQS queue. - */ -export default $config({ - app(input) { - return { - name: "aws-bucket-queue-subscriber", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const queue = new sst.aws.Queue("MyQueue"); - queue.subscribe("subscriber.handler"); - - const bucket = new sst.aws.Bucket("MyBucket"); - bucket.notify({ - notifications: [ - { - name: "MySubscriber", - queue, - events: ["s3:ObjectCreated:*"], - }, - ], - }); - - return { - bucket: bucket.name, - queue: queue.url, - }; - }, -}); diff --git a/examples/aws-bucket-queue-subscriber/subscriber.ts b/examples/aws-bucket-queue-subscriber/subscriber.ts deleted file mode 100644 index c4264f003f..0000000000 --- a/examples/aws-bucket-queue-subscriber/subscriber.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { SQSEvent } from "aws-lambda"; - -export const handler = async (event: SQSEvent) => { - console.log(event); - return "ok"; -}; diff --git a/examples/aws-bucket-subscriber/package.json b/examples/aws-bucket-subscriber/package.json deleted file mode 100644 index 4cdabdf595..0000000000 --- a/examples/aws-bucket-subscriber/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-bucket-subscriber", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bucket-subscriber/sst.config.ts b/examples/aws-bucket-subscriber/sst.config.ts deleted file mode 100644 index 2b8b5ef585..0000000000 --- a/examples/aws-bucket-subscriber/sst.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -/// - -/** - * ## Bucket notifications - * - * Create an S3 bucket and subscribe to its events with a function. - */ -export default $config({ - app(input) { - return { - name: "aws-bucket-subscriber", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket"); - bucket.notify({ - notifications: [ - { - name: "MySubscriber", - function: "subscriber.handler", - events: ["s3:ObjectCreated:*"], - }, - ], - }); - - return { - bucket: bucket.name, - }; - }, -}); diff --git a/examples/aws-bucket-subscriber/subscriber.ts b/examples/aws-bucket-subscriber/subscriber.ts deleted file mode 100644 index f9e60137f3..0000000000 --- a/examples/aws-bucket-subscriber/subscriber.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Handler, S3Event } from 'aws-lambda'; - -export const handler: Handler = async (event) => { - console.log(event); - return "ok"; -}; diff --git a/examples/aws-bucket-topic-subscriber/package.json b/examples/aws-bucket-topic-subscriber/package.json deleted file mode 100644 index c54f3182da..0000000000 --- a/examples/aws-bucket-topic-subscriber/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-bucket-topic-subscriber", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bucket-topic-subscriber/sst.config.ts b/examples/aws-bucket-topic-subscriber/sst.config.ts deleted file mode 100644 index 25e481759d..0000000000 --- a/examples/aws-bucket-topic-subscriber/sst.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// - -/** - * ## Bucket topic notifications - * - * Create an S3 bucket and subscribe to its events with an SNS topic. - */ -export default $config({ - app(input) { - return { - name: "aws-bucket-topic-subscriber", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const topic = new sst.aws.SnsTopic("MyTopic"); - topic.subscribe("MySubscriber", "subscriber.handler"); - - const bucket = new sst.aws.Bucket("MyBucket"); - bucket.notify({ - notifications: [ - { - name: "MySubscriber", - topic, - events: ["s3:ObjectCreated:*"], - }, - ], - }); - - return { - bucket: bucket.name, - topic: topic.name, - }; - }, -}); diff --git a/examples/aws-bucket-topic-subscriber/subscriber.ts b/examples/aws-bucket-topic-subscriber/subscriber.ts deleted file mode 100644 index 118f4371ad..0000000000 --- a/examples/aws-bucket-topic-subscriber/subscriber.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const handler = async (event) => { - console.log(event); - return "ok"; -}; diff --git a/examples/aws-bun-elysia/.dockerignore b/examples/aws-bun-elysia/.dockerignore deleted file mode 100644 index d13a1cca01..0000000000 --- a/examples/aws-bun-elysia/.dockerignore +++ /dev/null @@ -1,2 +0,0 @@ -.sst -node_modules diff --git a/examples/aws-bun-elysia/.gitignore b/examples/aws-bun-elysia/.gitignore deleted file mode 100644 index 92b10320b7..0000000000 --- a/examples/aws-bun-elysia/.gitignore +++ /dev/null @@ -1,45 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env.local -.env.development.local -.env.test.local -.env.production.local - -# vercel -.vercel - -**/*.trace -**/*.zip -**/*.tar.gz -**/*.tgz -**/*.log -package-lock.json -**/*.bun - -# sst -.sst diff --git a/examples/aws-bun-elysia/Dockerfile b/examples/aws-bun-elysia/Dockerfile deleted file mode 100644 index 4af145b928..0000000000 --- a/examples/aws-bun-elysia/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -# https://elysiajs.com/patterns/deployment.html#docker - -FROM oven/bun AS build - -WORKDIR /app - -# Cache packages installation -COPY package.json package.json -COPY bun.lockb bun.lockb - -RUN bun install - -COPY ./src ./src - -ENV NODE_ENV=production - -RUN bun build \ - --compile \ - --minify-whitespace \ - --minify-syntax \ - --target bun \ - --outfile server \ - ./src/index.ts - -FROM gcr.io/distroless/base - -WORKDIR /app - -COPY --from=build /app/server server - -ENV NODE_ENV=production - -CMD ["./server"] - -EXPOSE 3000 diff --git a/examples/aws-bun-elysia/elysia.png b/examples/aws-bun-elysia/elysia.png deleted file mode 100644 index 64dc586344..0000000000 Binary files a/examples/aws-bun-elysia/elysia.png and /dev/null differ diff --git a/examples/aws-bun-elysia/package.json b/examples/aws-bun-elysia/package.json deleted file mode 100644 index 931c1cff18..0000000000 --- a/examples/aws-bun-elysia/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-bun-elysia", - "version": "1.0.50", - "scripts": { - "dev": "bun run --watch src/index.ts", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.658.1", - "@aws-sdk/lib-storage": "^3.658.1", - "@aws-sdk/s3-request-presigner": "^3.658.1", - "elysia": "latest", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "bun-types": "latest" - }, - "module": "src/index.js" -} diff --git a/examples/aws-bun-elysia/src/index.ts b/examples/aws-bun-elysia/src/index.ts deleted file mode 100644 index cebfd22b9c..0000000000 --- a/examples/aws-bun-elysia/src/index.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Elysia } from "elysia"; -import { Resource } from "sst"; -import { - S3Client, - GetObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; -import { Upload } from "@aws-sdk/lib-storage"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; - -const s3 = new S3Client(); - -const app = new Elysia() - .get("/", () => "Hello Elysia") - .post("/", async ({ body: { file } }: { body: { file: File } }) => { - const params = { - Bucket: Resource.MyBucket.name, - Key: file.name, - Body: file, - }; - const upload = new Upload({ - params, - client: s3, - }); - await upload.done(); - - return "File uploaded successfully."; - }) - .get("/latest", async ({ redirect }) => { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0), - )[0]; - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - return redirect(await getSignedUrl(s3, command)); - }) - .listen(3000); - -console.log( - `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}` -); diff --git a/examples/aws-bun-elysia/sst.config.ts b/examples/aws-bun-elysia/sst.config.ts deleted file mode 100644 index 794730233c..0000000000 --- a/examples/aws-bun-elysia/sst.config.ts +++ /dev/null @@ -1,69 +0,0 @@ -/// - -/** - * ## AWS Bun Elysia container - * - * Deploys a Bun [Elysia](https://elysiajs.com/) API to AWS. - * - * You can get started by running. - * - * ```bash - * bun create elysia aws-bun-elysia - * cd aws-bun-elysia - * bunx sst init - * ``` - * - * Now you can add a service. - * - * ```ts title="sst.config.ts" - * new sst.aws.Service("MyService", { - * cluster, - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "bun dev", - * }, - * }); - * ``` - * - * Start your app locally. - * - * ```bash - * bun sst dev - * ``` - * - * This example lets you upload a file to S3 and then download it. - * - * ```bash - * curl -F file=@elysia.png http://localhost:3000/ - * curl http://localhost:3000/latest - * ``` - * - * Finally, you can deploy it using `bun sst deploy --stage production`. - */ -export default $config({ - app(input) { - return { - name: "aws-bun-elysia", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket"); - const vpc = new sst.aws.Vpc("MyVpc"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "bun dev", - }, - link: [bucket], - }); - }, -}); diff --git a/examples/aws-bun-elysia/tsconfig.json b/examples/aws-bun-elysia/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-bun-elysia/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-bun-redis/.dockerignore b/examples/aws-bun-redis/.dockerignore deleted file mode 100644 index 8c3bacfca9..0000000000 --- a/examples/aws-bun-redis/.dockerignore +++ /dev/null @@ -1,9 +0,0 @@ -node_modules -.git -.gitignore -README.md -Dockerfile* - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-bun-redis/.gitignore b/examples/aws-bun-redis/.gitignore deleted file mode 100644 index 1426860d41..0000000000 --- a/examples/aws-bun-redis/.gitignore +++ /dev/null @@ -1,178 +0,0 @@ -# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore - -# Logs - -logs -_.log -npm-debug.log_ -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -.pnpm-debug.log* - -# Caches - -.cache - -# Diagnostic reports (https://nodejs.org/api/report.html) - -report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json - -# Runtime data - -pids -_.pid -_.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover - -lib-cov - -# Coverage directory used by tools like istanbul - -coverage -*.lcov - -# nyc test coverage - -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) - -.grunt - -# Bower dependency directory (https://bower.io/) - -bower_components - -# node-waf configuration - -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) - -build/Release - -# Dependency directories - -node_modules/ -jspm_packages/ - -# Snowpack dependency directory (https://snowpack.dev/) - -web_modules/ - -# TypeScript cache - -*.tsbuildinfo - -# Optional npm cache directory - -.npm - -# Optional eslint cache - -.eslintcache - -# Optional stylelint cache - -.stylelintcache - -# Microbundle cache - -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history - -.node_repl_history - -# Output of 'npm pack' - -*.tgz - -# Yarn Integrity file - -.yarn-integrity - -# dotenv environment variable files - -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# parcel-bundler cache (https://parceljs.org/) - -.parcel-cache - -# Next.js build output - -.next -out - -# Nuxt.js build / generate output - -.nuxt -dist - -# Gatsby files - -# Comment in the public line in if your project uses Gatsby and not Next.js - -# https://nextjs.org/blog/next-9-1#public-directory-support - -# public - -# vuepress build output - -.vuepress/dist - -# vuepress v2.x temp and cache directory - -.temp - -# Docusaurus cache and generated files - -.docusaurus - -# Serverless directories - -.serverless/ - -# FuseBox cache - -.fusebox/ - -# DynamoDB Local files - -.dynamodb/ - -# TernJS port file - -.tern-port - -# Stores VSCode versions used for testing VSCode extensions - -.vscode-test - -# yarn v2 - -.yarn/cache -.yarn/unplugged -.yarn/build-state.yml -.yarn/install-state.gz -.pnp.* - -# IntelliJ based IDEs -.idea - -# Finder (MacOS) folder config -.DS_Store - -# sst -.sst diff --git a/examples/aws-bun-redis/Dockerfile b/examples/aws-bun-redis/Dockerfile deleted file mode 100644 index a50d40e263..0000000000 --- a/examples/aws-bun-redis/Dockerfile +++ /dev/null @@ -1,38 +0,0 @@ -# use the official Bun image -# see all versions at https://hub.docker.com/r/oven/bun/tags -FROM oven/bun:1 AS base -WORKDIR /usr/src/app - -# install dependencies into temp directory -# this will cache them and speed up future builds -FROM base AS install -RUN mkdir -p /temp/dev -COPY package.json bun.lockb /temp/dev/ -RUN cd /temp/dev && bun install --frozen-lockfile - -# install with --production (exclude devDependencies) -RUN mkdir -p /temp/prod -COPY package.json bun.lockb /temp/prod/ -RUN cd /temp/prod && bun install --frozen-lockfile --production - -# copy node_modules from temp directory -# then copy all (non-ignored) project files into the image -FROM base AS prerelease -COPY --from=install /temp/dev/node_modules node_modules -COPY . . - -# [optional] tests & build -ENV NODE_ENV=production -# RUN bun test -RUN bun run build - -# copy production dependencies and source code into final image -FROM base AS release -COPY --from=install /temp/prod/node_modules node_modules -COPY --from=prerelease /usr/src/app/index.ts . -COPY --from=prerelease /usr/src/app/package.json . - -# run the app -USER bun -EXPOSE 3000/tcp -ENTRYPOINT [ "bun", "run", "index.ts" ] diff --git a/examples/aws-bun-redis/index.ts b/examples/aws-bun-redis/index.ts deleted file mode 100644 index 0168d45220..0000000000 --- a/examples/aws-bun-redis/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -const server = Bun.serve({ - async fetch(req) { - const url = new URL(req.url); - - if (url.pathname === "/" && req.method === "GET") { - const counter = await redis.incr("counter"); - return new Response(`Hit counter: ${counter}`); - } - - return new Response("404!"); - }, -}); - -console.log(`Listening on ${server.url}`); diff --git a/examples/aws-bun-redis/package.json b/examples/aws-bun-redis/package.json deleted file mode 100644 index c4aa0fa55c..0000000000 --- a/examples/aws-bun-redis/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-bun-redis", - "module": "index.ts", - "type": "module", - "scripts": { - "build": "bun build --target bun index.ts", - "dev": "bun run --watch index.ts" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5.0.0" - }, - "dependencies": { - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bun-redis/sst.config.ts b/examples/aws-bun-redis/sst.config.ts deleted file mode 100644 index 6ca2730f76..0000000000 --- a/examples/aws-bun-redis/sst.config.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// - -/** - * ## AWS Bun Redis - * - * Creates a hit counter app with Bun and Redis. - * - * This deploys Bun as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {9} - * new sst.aws.Service("MyService", { - * cluster, - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "bun dev", - * }, - * link: [redis], - * }); - * ``` - * - * We also have a couple of scripts. A `dev` script with a watcher and a `build` script - * that used when we deploy to production. - * - * ```json title="package.json" - * { - * "scripts": { - * "dev": "bun run --watch index.ts", - * "build": "bun build --target bun index.ts" - * }, - * } - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo bun sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * bun sst dev - * ``` - * - * Now if you go to `http://localhost:3000` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it using `bun sst deploy --stage production` using a `Dockerfile` - * that's included in the example. - */ -export default $config({ - app(input) { - return { - name: "aws-bun-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "bun dev", - }, - }); - }, -}); diff --git a/examples/aws-bun-redis/tsconfig.json b/examples/aws-bun-redis/tsconfig.json deleted file mode 100644 index 238655f2ce..0000000000 --- a/examples/aws-bun-redis/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - // Enable latest features - "lib": ["ESNext", "DOM"], - "target": "ESNext", - "module": "ESNext", - "moduleDetection": "force", - "jsx": "react-jsx", - "allowJs": true, - - // Bundler mode - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "noEmit": true, - - // Best practices - "strict": true, - "skipLibCheck": true, - "noFallthroughCasesInSwitch": true, - - // Some stricter flags (disabled by default) - "noUnusedLocals": false, - "noUnusedParameters": false, - "noPropertyAccessFromIndexSignature": false - } -} diff --git a/examples/aws-bun/.dockerignore b/examples/aws-bun/.dockerignore deleted file mode 100644 index 8c3bacfca9..0000000000 --- a/examples/aws-bun/.dockerignore +++ /dev/null @@ -1,9 +0,0 @@ -node_modules -.git -.gitignore -README.md -Dockerfile* - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-bun/.gitignore b/examples/aws-bun/.gitignore deleted file mode 100644 index 1426860d41..0000000000 --- a/examples/aws-bun/.gitignore +++ /dev/null @@ -1,178 +0,0 @@ -# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore - -# Logs - -logs -_.log -npm-debug.log_ -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -.pnpm-debug.log* - -# Caches - -.cache - -# Diagnostic reports (https://nodejs.org/api/report.html) - -report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json - -# Runtime data - -pids -_.pid -_.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover - -lib-cov - -# Coverage directory used by tools like istanbul - -coverage -*.lcov - -# nyc test coverage - -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) - -.grunt - -# Bower dependency directory (https://bower.io/) - -bower_components - -# node-waf configuration - -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) - -build/Release - -# Dependency directories - -node_modules/ -jspm_packages/ - -# Snowpack dependency directory (https://snowpack.dev/) - -web_modules/ - -# TypeScript cache - -*.tsbuildinfo - -# Optional npm cache directory - -.npm - -# Optional eslint cache - -.eslintcache - -# Optional stylelint cache - -.stylelintcache - -# Microbundle cache - -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history - -.node_repl_history - -# Output of 'npm pack' - -*.tgz - -# Yarn Integrity file - -.yarn-integrity - -# dotenv environment variable files - -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# parcel-bundler cache (https://parceljs.org/) - -.parcel-cache - -# Next.js build output - -.next -out - -# Nuxt.js build / generate output - -.nuxt -dist - -# Gatsby files - -# Comment in the public line in if your project uses Gatsby and not Next.js - -# https://nextjs.org/blog/next-9-1#public-directory-support - -# public - -# vuepress build output - -.vuepress/dist - -# vuepress v2.x temp and cache directory - -.temp - -# Docusaurus cache and generated files - -.docusaurus - -# Serverless directories - -.serverless/ - -# FuseBox cache - -.fusebox/ - -# DynamoDB Local files - -.dynamodb/ - -# TernJS port file - -.tern-port - -# Stores VSCode versions used for testing VSCode extensions - -.vscode-test - -# yarn v2 - -.yarn/cache -.yarn/unplugged -.yarn/build-state.yml -.yarn/install-state.gz -.pnp.* - -# IntelliJ based IDEs -.idea - -# Finder (MacOS) folder config -.DS_Store - -# sst -.sst diff --git a/examples/aws-bun/Dockerfile b/examples/aws-bun/Dockerfile deleted file mode 100644 index 457b544c5c..0000000000 --- a/examples/aws-bun/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM oven/bun - -COPY bun.lockb . -COPY package.json . - -RUN bun install --frozen-lockfile - -COPY . . - -EXPOSE 3000 -CMD ["bun", "index.ts"] diff --git a/examples/aws-bun/index.ts b/examples/aws-bun/index.ts deleted file mode 100644 index c552d40423..0000000000 --- a/examples/aws-bun/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Resource } from "sst"; -import { - S3Client, - GetObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; -import { Upload } from "@aws-sdk/lib-storage"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; - -const s3 = new S3Client(); - -const server = Bun.serve({ - async fetch(req) { - const url = new URL(req.url); - - if (url.pathname === "/" && req.method === "GET") { - return new Response("Hello World!"); - } - - if (url.pathname === "/" && req.method === "POST") { - const formData = await req.formData(); - const file = formData.get("file")! as File; - const params = { - Bucket: Resource.MyBucket.name, - ContentType: file.type, - Key: file.name, - Body: file, - }; - const upload = new Upload({ - params, - client: s3, - }); - await upload.done(); - - return new Response("File uploaded successfully."); - } - - if (url.pathname === "/latest" && req.method === "GET") { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0), - )[0]; - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - return Response.redirect(await getSignedUrl(s3, command)); - } - - return new Response("404!"); - }, -}); - -console.log(`Listening on ${server.url}`); diff --git a/examples/aws-bun/package.json b/examples/aws-bun/package.json deleted file mode 100644 index d2c2c3afb3..0000000000 --- a/examples/aws-bun/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-bun", - "module": "index.ts", - "type": "module", - "scripts": { - "dev": "bun run --watch index.ts" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5.0.0" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.658.1", - "@aws-sdk/lib-storage": "^3.658.1", - "@aws-sdk/s3-request-presigner": "^3.658.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bun/sst.config.ts b/examples/aws-bun/sst.config.ts deleted file mode 100644 index 6a75af0d44..0000000000 --- a/examples/aws-bun/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-bun", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "bun dev", - }, - link: [bucket], - }); - }, -}); diff --git a/examples/aws-bun/tsconfig.json b/examples/aws-bun/tsconfig.json deleted file mode 100644 index 238655f2ce..0000000000 --- a/examples/aws-bun/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - // Enable latest features - "lib": ["ESNext", "DOM"], - "target": "ESNext", - "module": "ESNext", - "moduleDetection": "force", - "jsx": "react-jsx", - "allowJs": true, - - // Bundler mode - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "noEmit": true, - - // Best practices - "strict": true, - "skipLibCheck": true, - "noFallthroughCasesInSwitch": true, - - // Some stricter flags (disabled by default) - "noUnusedLocals": false, - "noUnusedParameters": false, - "noPropertyAccessFromIndexSignature": false - } -} diff --git a/examples/aws-bundle/.gitignore b/examples/aws-bundle/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-bundle/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-bundle/package.json b/examples/aws-bundle/package.json deleted file mode 100644 index 737d546186..0000000000 --- a/examples/aws-bundle/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "aws-bundle", - "version": "0.0.0", - "type": "module", - "dependencies": { - "@types/node": "^22.13.2", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-bundle/src/file.json b/examples/aws-bundle/src/file.json deleted file mode 100644 index 29c5f233a6..0000000000 --- a/examples/aws-bundle/src/file.json +++ /dev/null @@ -1 +0,0 @@ -{ "test": "foo" } diff --git a/examples/aws-bundle/src/index.mjs b/examples/aws-bundle/src/index.mjs deleted file mode 100644 index 91c8642eba..0000000000 --- a/examples/aws-bundle/src/index.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import { readFileSync } from "fs"; - -const data = readFileSync(new URL("./file.json", import.meta.url)); - -export async function handler() { - return { - statusCode: 200, - body: data.toString(), - }; -} diff --git a/examples/aws-bundle/src/resource.enc b/examples/aws-bundle/src/resource.enc deleted file mode 100644 index a34504402c..0000000000 --- a/examples/aws-bundle/src/resource.enc +++ /dev/null @@ -1 +0,0 @@ -aΚ NX\SMϻ j \ No newline at end of file diff --git a/examples/aws-bundle/sst.config.ts b/examples/aws-bundle/sst.config.ts deleted file mode 100644 index 76ee71699c..0000000000 --- a/examples/aws-bundle/sst.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-bundle", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Function("Function", { - bundle: "./src", - handler: "index.handler", - url: true, - }); - }, -}); diff --git a/examples/aws-bundle/tsconfig.json b/examples/aws-bundle/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-bundle/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-bus/.gitignore b/examples/aws-bus/.gitignore deleted file mode 100644 index 9a902f0c53..0000000000 --- a/examples/aws-bus/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# sst -.sst diff --git a/examples/aws-bus/package.json b/examples/aws-bus/package.json deleted file mode 100644 index 17ef5c7687..0000000000 --- a/examples/aws-bus/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "aws-bus", - "version": "0.0.0", - "dependencies": { - "@aws-sdk/client-eventbridge": "^3.582.0", - "sst": "file:../../sdk/js", - "zod": "^4.1.13" - }, - "devDependencies": { - "typescript": "^5.9.3" - } -} diff --git a/examples/aws-bus/src/events.ts b/examples/aws-bus/src/events.ts deleted file mode 100644 index 596f081190..0000000000 --- a/examples/aws-bus/src/events.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { event } from "sst/event"; -import { ZodValidator } from "sst/event/validator"; -import { z } from "zod"; - -const defineEvent = event.builder({ - validator: ZodValidator, - metadata: () => { - return { - timestamp: Date.now(), - }; - }, -}); - -export const MyEvent = defineEvent( - "app.myevent", - z.object({ - foo: z.string(), - }), -); diff --git a/examples/aws-bus/src/publisher.ts b/examples/aws-bus/src/publisher.ts deleted file mode 100644 index 228ff26366..0000000000 --- a/examples/aws-bus/src/publisher.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { bus } from "sst/aws/bus"; -import { z } from "zod"; -import { Resource } from "sst"; -import { MyEvent } from "./events"; - -export async function handler() { - await bus.publish(Resource.Bus, MyEvent, { foo: "hello" }); - - return { - statusCode: 200, - }; -} diff --git a/examples/aws-bus/src/receiver.ts b/examples/aws-bus/src/receiver.ts deleted file mode 100644 index 7d6230d6ea..0000000000 --- a/examples/aws-bus/src/receiver.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { bus } from "sst/aws/bus"; -import { MyEvent } from "./events"; - -export const handler = bus.subscriber([MyEvent], async (event) => { - console.log({ event }); -}); diff --git a/examples/aws-bus/sst.config.ts b/examples/aws-bus/sst.config.ts deleted file mode 100644 index 0e8840a675..0000000000 --- a/examples/aws-bus/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -/** - * ## AWS Bus subscriptions - * - * Subscribe bus events with AWS Lambda functions. - */ -export default $config({ - app(input) { - return { - name: "aws-bus", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bus = new sst.aws.Bus("Bus"); - - const publisher = new sst.aws.Function("Publisher", { - handler: "./src/publisher.handler", - url: true, - link: [bus], - }); - - bus.subscribe("Example", "./src/receiver.handler"); - }, -}); diff --git a/examples/aws-bus/tsconfig.json b/examples/aws-bus/tsconfig.json deleted file mode 100644 index 62526ee80a..0000000000 --- a/examples/aws-bus/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "compilerOptions": { - "module": "ESNext", - "moduleResolution": "Bundler" - } -} diff --git a/examples/aws-cloudflare-combined/.gitignore b/examples/aws-cloudflare-combined/.gitignore deleted file mode 100644 index f4d5339fb2..0000000000 --- a/examples/aws-cloudflare-combined/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -.env -.sst diff --git a/examples/aws-cloudflare-combined/package.json b/examples/aws-cloudflare-combined/package.json deleted file mode 100644 index 0b47f9bf35..0000000000 --- a/examples/aws-cloudflare-combined/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "aws-cloudflare-combined", - "type": "module", - "dependencies": { - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "@cloudflare/workers-types": "^4.20240403.0", - "hono": "^4.6.12", - "sst": "../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.146" - } -} diff --git a/examples/aws-cloudflare-combined/src/index.ts b/examples/aws-cloudflare-combined/src/index.ts deleted file mode 100644 index cb7ac2f0ae..0000000000 --- a/examples/aws-cloudflare-combined/src/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Hono } from "hono"; -import { handle } from "hono/aws-lambda"; -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { - S3Client, - GetObjectCommand, - PutObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; - -const s3 = new S3Client(); - -const app = new Hono(); - -app.get("/", async (c) => { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - - return c.text(await getSignedUrl(s3, command)); -}); - -app.get("/latest", async (c) => { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0), - )[0]; - - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - - return c.redirect(await getSignedUrl(s3, command)); -}); - -export const handler = handle(app); diff --git a/examples/aws-cloudflare-combined/sst.config.ts b/examples/aws-cloudflare-combined/sst.config.ts deleted file mode 100644 index 32c74ea0f1..0000000000 --- a/examples/aws-cloudflare-combined/sst.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-cloudflare-combined", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - cloudflare: "6.13.0", - }, - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket"); - const api = new sst.aws.Function("Hono", { - url: true, - link: [bucket], - handler: "src/index.handler", - }); - - // Add a Cloudflare Bucket and link it to the worker - const cfBucket = new sst.cloudflare.Bucket("CfBucket"); - const worker = new sst.cloudflare.Worker("MyWorker", { - handler: "./worker.ts", - link: [cfBucket], - url: true, - }); - - return { - api: api.url, - worker: worker.url, - }; - }, -}); diff --git a/examples/aws-cloudflare-combined/tsconfig.json b/examples/aws-cloudflare-combined/tsconfig.json deleted file mode 100644 index 95a44f83fe..0000000000 --- a/examples/aws-cloudflare-combined/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "Bundler", - "strict": true, - "skipLibCheck": true, - "types": ["node"] - } -} diff --git a/examples/aws-cloudflare-combined/worker.ts b/examples/aws-cloudflare-combined/worker.ts deleted file mode 100644 index abea65a222..0000000000 --- a/examples/aws-cloudflare-combined/worker.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { Resource } from "sst"; - -export default { - async fetch(req: Request) { - if (req.method === "PUT") { - const key = crypto.randomUUID(); - await Resource.CfBucket.put(key, req.body, { - httpMetadata: { - contentType: req.headers.get("content-type"), - }, - }); - return new Response(`Object created with key: ${key}`); - } - - if (req.method === "GET") { - const first = await Resource.CfBucket.list().then( - (res) => - res.objects.toSorted( - (a, b) => a.uploaded.getTime() - b.uploaded.getTime(), - )[0], - ); - if (!first) { - return new Response("No objects found"); - } - const result = await Resource.CfBucket.get(first.key); - return new Response(result.body, { - headers: { - "content-type": result.httpMetadata.contentType, - }, - }); - } - - return new Response("Hello from Cloudflare Worker!"); - }, -}; diff --git a/examples/aws-cluster-autoscaling/.dockerignore b/examples/aws-cluster-autoscaling/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-cluster-autoscaling/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-cluster-autoscaling/Dockerfile b/examples/aws-cluster-autoscaling/Dockerfile deleted file mode 100644 index 9cfff20241..0000000000 --- a/examples/aws-cluster-autoscaling/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] \ No newline at end of file diff --git a/examples/aws-cluster-autoscaling/index.mjs b/examples/aws-cluster-autoscaling/index.mjs deleted file mode 100644 index dc532b9de3..0000000000 --- a/examples/aws-cluster-autoscaling/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import express from "express"; - -const PORT = 80; - -const app = express(); - -app.get("/", async (req, res) => { - res.send("Hello World"); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-cluster-autoscaling/package.json b/examples/aws-cluster-autoscaling/package.json deleted file mode 100644 index 6afabf1390..0000000000 --- a/examples/aws-cluster-autoscaling/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "aws-cluster-autoscaling", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "@aws-sdk/client-sqs": "^3.682.0", - "express": "^4.21.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-cluster-autoscaling/queue.ts b/examples/aws-cluster-autoscaling/queue.ts deleted file mode 100644 index f9e07dd59e..0000000000 --- a/examples/aws-cluster-autoscaling/queue.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Resource } from "sst"; -import { - SQSClient, - SendMessageBatchCommand, - PurgeQueueCommand, -} from "@aws-sdk/client-sqs"; -const client = new SQSClient(); - -export const seeder = async () => { - await client.send( - new SendMessageBatchCommand({ - QueueUrl: Resource.MyQueue.url, - Entries: [ - { Id: "1", MessageBody: JSON.stringify({ foo: "bar" }) }, - { Id: "2", MessageBody: JSON.stringify({ foo: "bar" }) }, - { Id: "3", MessageBody: JSON.stringify({ foo: "bar" }) }, - { Id: "4", MessageBody: JSON.stringify({ foo: "bar" }) }, - { Id: "5", MessageBody: JSON.stringify({ foo: "bar" }) }, - ], - }) - ); - - return { statusCode: 200, body: "seeded" }; -}; - -export const purger = async () => { - await client.send( - new PurgeQueueCommand({ - QueueUrl: Resource.MyQueue.url, - }) - ); - - return { statusCode: 200, body: "purged" }; -}; diff --git a/examples/aws-cluster-autoscaling/sst.config.ts b/examples/aws-cluster-autoscaling/sst.config.ts deleted file mode 100644 index 2f5905f030..0000000000 --- a/examples/aws-cluster-autoscaling/sst.config.ts +++ /dev/null @@ -1,175 +0,0 @@ -/// - -/** - * ## AWS Cluster custom autoscaling - * - * In this example, we'll create a cluster that autoscales based on a custom - * metric. In this case, the number of messages in a queue. - * - * We'll create a queue, and two functions that'll seed and purge the queue. We'll - * also create two policies. - * - * One that scales it up. - * - * ```ts title="sst.config.ts" - * const scaleUpPolicy = new aws.appautoscaling.Policy("ScaleUpPolicy", { - * serviceNamespace: service.nodes.autoScalingTarget.serviceNamespace, - * scalableDimension: service.nodes.autoScalingTarget.scalableDimension, - * resourceId: service.nodes.autoScalingTarget.resourceId, - * policyType: "StepScaling", - * stepScalingPolicyConfiguration: { - * adjustmentType: "ChangeInCapacity", - * cooldown: 5, - * stepAdjustments: [ - * { - * metricIntervalLowerBound: "0", - * scalingAdjustment: 1, - * }, - * ], - * }, - * }); - * ``` - * - * And one that scales it down. - * - * ```ts title="sst.config.ts" - * const scaleDownPolicy = new aws.appautoscaling.Policy("ScaleDownPolicy", { - * serviceNamespace: service.nodes.autoScalingTarget.serviceNamespace, - * scalableDimension: service.nodes.autoScalingTarget.scalableDimension, - * resourceId: service.nodes.autoScalingTarget.resourceId, - * policyType: "StepScaling", - * stepScalingPolicyConfiguration: { - * adjustmentType: "ChangeInCapacity", - * cooldown: 5, - * stepAdjustments: [ - * { - * metricIntervalUpperBound: "0", - * scalingAdjustment: -1, - * }, - * ], - * }, - * }); - * ``` - * - * We'll add a CloudWatch metric alarm that triggers the scaling policies if the - * queue depth exceeds 3 messages. - * - * ```ts title="sst.config.ts" - * new aws.cloudwatch.MetricAlarm("QueueDepthAlarm", { - * comparisonOperator: "GreaterThanThreshold", - * evaluationPeriods: 1, - * metricName: "ApproximateNumberOfMessagesVisible", - * namespace: "AWS/SQS", - * period: 10, - * statistic: "Average", - * threshold: 3, - * dimensions: { - * QueueName: queue.nodes.queue.name, - * }, - * alarmDescription: "Scale up when queue depth exceeds 3 messages", - * alarmActions: [scaleUpPolicy.arn], - * okActions: [scaleDownPolicy.arn], - * }); - * ``` - * - * To test this example, first deploy your app then: - * - * 1. Invoke the `MyQueueSeeder` URL. This will cause the service to scale up to 5 - * instances in a few minutes. - * 2. Then invoke the `MyQueuePurger` URL. This will cause the service to scale - * down to 1 instance in a few minutes. - */ -export default $config({ - app(input) { - return { - name: "aws-cluster-autoscaling", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - - // Create a queue and two functions to seed and purge the queue - const queue = new sst.aws.Queue("MyQueue"); - new sst.aws.Function("MyQueueSeeder", { - handler: "queue.seeder", - link: [queue], - url: true, - }); - new sst.aws.Function("MyQueuePurger", { - handler: "queue.purger", - link: [queue], - url: true, - }); - - // Create a cluster and disable default scaling on CPU and memory utilization - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - const service = new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http" }], - }, - scaling: { - min: 1, - max: 5, - cpuUtilization: false, - memoryUtilization: false, - }, - }); - - // Create a scale up policy that scales up by 1 instance at a time - const scaleUpPolicy = new aws.appautoscaling.Policy("ScaleUpPolicy", { - serviceNamespace: service.nodes.autoScalingTarget.serviceNamespace, - scalableDimension: service.nodes.autoScalingTarget.scalableDimension, - resourceId: service.nodes.autoScalingTarget.resourceId, - policyType: "StepScaling", - stepScalingPolicyConfiguration: { - adjustmentType: "ChangeInCapacity", - cooldown: 5, - stepAdjustments: [ - { - metricIntervalLowerBound: "0", - scalingAdjustment: 1, - }, - ], - }, - }); - - // Create a scale down policy that scales down by 1 instance at a time - const scaleDownPolicy = new aws.appautoscaling.Policy("ScaleDownPolicy", { - serviceNamespace: service.nodes.autoScalingTarget.serviceNamespace, - scalableDimension: service.nodes.autoScalingTarget.scalableDimension, - resourceId: service.nodes.autoScalingTarget.resourceId, - policyType: "StepScaling", - stepScalingPolicyConfiguration: { - adjustmentType: "ChangeInCapacity", - cooldown: 5, - stepAdjustments: [ - { - metricIntervalUpperBound: "0", - scalingAdjustment: -1, - }, - ], - }, - }); - - // Create an alarm that scales up when the queue depth exceeds 3 messages - // and scales down when the queue depth is less than 3 messages - new aws.cloudwatch.MetricAlarm("QueueDepthAlarm", { - comparisonOperator: "GreaterThanThreshold", - evaluationPeriods: 1, - metricName: "ApproximateNumberOfMessagesVisible", - namespace: "AWS/SQS", - period: 10, - statistic: "Average", - threshold: 3, - dimensions: { - QueueName: queue.nodes.queue.name, - }, - alarmDescription: "Scale up when queue depth exceeds 3 messages", - alarmActions: [scaleUpPolicy.arn], - okActions: [scaleDownPolicy.arn], - }); - }, -}); diff --git a/examples/aws-cluster-internal/.dockerignore b/examples/aws-cluster-internal/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-cluster-internal/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-cluster-internal/Dockerfile b/examples/aws-cluster-internal/Dockerfile deleted file mode 100644 index 9cfff20241..0000000000 --- a/examples/aws-cluster-internal/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] \ No newline at end of file diff --git a/examples/aws-cluster-internal/index.mjs b/examples/aws-cluster-internal/index.mjs deleted file mode 100644 index dc532b9de3..0000000000 --- a/examples/aws-cluster-internal/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import express from "express"; - -const PORT = 80; - -const app = express(); - -app.get("/", async (req, res) => { - res.send("Hello World"); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-cluster-internal/package.json b/examples/aws-cluster-internal/package.json deleted file mode 100644 index 5b900c19c6..0000000000 --- a/examples/aws-cluster-internal/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-cluster-internal", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "express": "^4.21.1" - } -} diff --git a/examples/aws-cluster-internal/sst.config.ts b/examples/aws-cluster-internal/sst.config.ts deleted file mode 100644 index b218497fa3..0000000000 --- a/examples/aws-cluster-internal/sst.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// - -/** - * ## AWS Cluster private service - * - * Adds a private load balancer to a service by setting the `loadBalancer.public` prop to - * `false`. - * - * This allows you to create internal services that can only be accessed inside a VPC. - */ -export default $config({ - app(input) { - return { - name: "aws-cluster-internal", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - public: false, - ports: [{ listen: "80/http" }], - }, - }); - }, -}); diff --git a/examples/aws-cluster-spot/.dockerignore b/examples/aws-cluster-spot/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-cluster-spot/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-cluster-spot/Dockerfile b/examples/aws-cluster-spot/Dockerfile deleted file mode 100644 index 9cfff20241..0000000000 --- a/examples/aws-cluster-spot/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] \ No newline at end of file diff --git a/examples/aws-cluster-spot/index.mjs b/examples/aws-cluster-spot/index.mjs deleted file mode 100644 index dc532b9de3..0000000000 --- a/examples/aws-cluster-spot/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import express from "express"; - -const PORT = 80; - -const app = express(); - -app.get("/", async (req, res) => { - res.send("Hello World"); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-cluster-spot/package.json b/examples/aws-cluster-spot/package.json deleted file mode 100644 index 4efa76a9ce..0000000000 --- a/examples/aws-cluster-spot/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-cluster-spot", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "express": "^4.21.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-cluster-spot/sst.config.ts b/examples/aws-cluster-spot/sst.config.ts deleted file mode 100644 index c3dc6f0d3f..0000000000 --- a/examples/aws-cluster-spot/sst.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// - -/** - * ## AWS Cluster Spot capacity - * - * This example, shows how to use the Fargate Spot capacity provider for your services. - * - * We have it set to use only Fargate Spot instances for all non-production stages. Learn more - * about the [`capacity`](/docs/component/aws/cluster#capacity) prop. - */ -export default $config({ - app(input) { - return { - name: "aws-cluster-spot", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http" }], - }, - capacity: $app.stage === "production" ? undefined : "spot", - }); - }, -}); diff --git a/examples/aws-cluster-vpclink/.dockerignore b/examples/aws-cluster-vpclink/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-cluster-vpclink/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-cluster-vpclink/Dockerfile b/examples/aws-cluster-vpclink/Dockerfile deleted file mode 100644 index 9cfff20241..0000000000 --- a/examples/aws-cluster-vpclink/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] \ No newline at end of file diff --git a/examples/aws-cluster-vpclink/index.mjs b/examples/aws-cluster-vpclink/index.mjs deleted file mode 100644 index dc532b9de3..0000000000 --- a/examples/aws-cluster-vpclink/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import express from "express"; - -const PORT = 80; - -const app = express(); - -app.get("/", async (req, res) => { - res.send("Hello World"); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-cluster-vpclink/package.json b/examples/aws-cluster-vpclink/package.json deleted file mode 100644 index dfafa8b64a..0000000000 --- a/examples/aws-cluster-vpclink/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-cluster-vpclink", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "express": "^4.21.1" - } -} diff --git a/examples/aws-cluster-vpclink/sst.config.ts b/examples/aws-cluster-vpclink/sst.config.ts deleted file mode 100644 index f616f0017d..0000000000 --- a/examples/aws-cluster-vpclink/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## AWS Cluster with API Gateway - * - * Expose a service through API Gateway HTTP API using a VPC link. - * - * This is an alternative to using a load balancer. Since API Gateway is pay per request, it - * works out a lot cheaper for services that don't get a lot of traffic. - * - * You need to specify which port in your service will be exposed through API Gateway. - * - * ```ts title="sst.config.ts" {4} - * const service = new sst.aws.Service("MyService", { - * cluster, - * serviceRegistry: { - * port: 80, - * }, - * }); - * ``` - * - * A couple of things to note: - * - * 1. Your API Gateway HTTP API also needs to be in the **same VPC** as the service. - * - * 2. You also need to verify that your VPC's [**availability zones support VPC link**](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vpc-links.html#http-api-vpc-link-availability). - * - * 3. Run `aws ec2 describe-availability-zones` to get a list of AZs for your - * account. - * - * 4. Only list the AZ ID's that support VPC link. - * ```ts title="sst.config.ts" {4} - * vpc: { - * az: ["eu-west-3a", "eu-west-3c"] - * } - * ``` - * If the VPC picks an AZ automatically that doesn't support VPC link, you'll get - * the following error: - * ``` - * operation error ApiGatewayV2: BadRequestException: Subnet is in Availability - * Zone 'euw3-az2' where service is not available - * ``` - */ -export default $config({ - app(input) { - return { - name: "aws-cluster-vpclink", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { - // Pick at least two AZs that support VPC link - // az: ["eu-west-3a", "eu-west-3c"], - }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - const service = new sst.aws.Service("MyService", { - cluster, - serviceRegistry: { - port: 80, - }, - }); - - const api = new sst.aws.ApiGatewayV2("MyApi", { vpc }); - api.routePrivate("$default", service.nodes.cloudmapService.arn); - }, -}); diff --git a/examples/aws-cognito/index.ts b/examples/aws-cognito/index.ts deleted file mode 100644 index ce0c87f62d..0000000000 --- a/examples/aws-cognito/index.ts +++ /dev/null @@ -1 +0,0 @@ -export async function handler() {} diff --git a/examples/aws-cognito/package.json b/examples/aws-cognito/package.json deleted file mode 100644 index 0710943f9c..0000000000 --- a/examples/aws-cognito/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-cognito", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-cognito/sst.config.ts b/examples/aws-cognito/sst.config.ts deleted file mode 100644 index e1392fcf95..0000000000 --- a/examples/aws-cognito/sst.config.ts +++ /dev/null @@ -1,49 +0,0 @@ -/// - -/** - * ## AWS Cognito User Pool - * - * Create a Cognito User Pool with a hosted UI domain, client, and identity pool. - * - */ -export default $config({ - app(input) { - return { - name: "aws-cognito", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const userPool = new sst.aws.CognitoUserPool("MyUserPool", { - domain: { - prefix: `my-app-${$app.stage}`, - }, - triggers: { - preSignUp: { - handler: "index.handler", - }, - }, - }); - - const client = userPool.addClient("Web", { - callbackUrls: ['https://example.com/auth/callback'] - }); - - const identityPool = new sst.aws.CognitoIdentityPool("MyIdentityPool", { - userPools: [ - { - userPool: userPool.id, - client: client.id, - }, - ], - }); - - return { - UserPool: userPool.id, - Client: client.id, - IdentityPool: identityPool.id, - DomainUrl: userPool.domainUrl, - }; - }, -}); diff --git a/examples/aws-copy-files/.gitignore b/examples/aws-copy-files/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-copy-files/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-copy-files/files/foo.json b/examples/aws-copy-files/files/foo.json deleted file mode 100644 index c8c4105eb5..0000000000 --- a/examples/aws-copy-files/files/foo.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "foo": "bar" -} diff --git a/examples/aws-copy-files/index.ts b/examples/aws-copy-files/index.ts deleted file mode 100644 index ce0c87f62d..0000000000 --- a/examples/aws-copy-files/index.ts +++ /dev/null @@ -1 +0,0 @@ -export async function handler() {} diff --git a/examples/aws-copy-files/package.json b/examples/aws-copy-files/package.json deleted file mode 100644 index e343eb1f30..0000000000 --- a/examples/aws-copy-files/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-copy-files", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-copy-files/sst.config.ts b/examples/aws-copy-files/sst.config.ts deleted file mode 100644 index f828e9beab..0000000000 --- a/examples/aws-copy-files/sst.config.ts +++ /dev/null @@ -1,25 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-copy-files", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const fn = new sst.aws.Function("MyFunction", { - handler: "index.handler", - url: true, - copyFiles: [ - { - from: "./files", - }, - ], - }); - return { - url: fn.url, - }; - }, -}); diff --git a/examples/aws-copy-files/tsconfig.json b/examples/aws-copy-files/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-copy-files/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-dart-api/.gitignore b/examples/aws-dart-api/.gitignore deleted file mode 100644 index 214545df01..0000000000 --- a/examples/aws-dart-api/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# https://dart.dev/guides/libraries/private-files -# Created by `dart pub` -.dart_tool/ - -# Avoid committing pubspec.lock for library packages; see -# https://dart.dev/guides/libraries/private-files#pubspeclock. -pubspec.lock - -# sst -.sst diff --git a/examples/aws-dart-api/CHANGELOG.md b/examples/aws-dart-api/CHANGELOG.md deleted file mode 100644 index effe43c82c..0000000000 --- a/examples/aws-dart-api/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -## 1.0.0 - -- Initial version. diff --git a/examples/aws-dart-api/analysis_options.yaml b/examples/aws-dart-api/analysis_options.yaml deleted file mode 100644 index dee8927aaf..0000000000 --- a/examples/aws-dart-api/analysis_options.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# This file configures the static analysis results for your project (errors, -# warnings, and lints). -# -# This enables the 'recommended' set of lints from `package:lints`. -# This set helps identify many issues that may lead to problems when running -# or consuming Dart code, and enforces writing Dart using a single, idiomatic -# style and format. -# -# If you want a smaller set of lints you can change this to specify -# 'package:lints/core.yaml'. These are just the most critical lints -# (the recommended set includes the core lints). -# The core lints are also what is used by pub.dev for scoring packages. - -include: package:lints/recommended.yaml - -# Uncomment the following section to specify additional rules. - -# linter: -# rules: -# - camel_case_types - -# analyzer: -# exclude: -# - path/to/excluded/files/** - -# For more information about the core and recommended set of lints, see -# https://dart.dev/go/core-lints - -# For additional information about configuring this file, see -# https://dart.dev/guides/language/analysis-options diff --git a/examples/aws-dart-api/build.sh b/examples/aws-dart-api/build.sh deleted file mode 100755 index 4de7c08a2a..0000000000 --- a/examples/aws-dart-api/build.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh - -# Install dependencies -dart pub get - -# build the binary -dart compile exe lib/src/main.dart -o .build/bootstrap - -# Exit -exit \ No newline at end of file diff --git a/examples/aws-dart-api/lib/src/main.dart b/examples/aws-dart-api/lib/src/main.dart deleted file mode 100644 index 56eb949b05..0000000000 --- a/examples/aws-dart-api/lib/src/main.dart +++ /dev/null @@ -1,20 +0,0 @@ -import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import 'package:aws_lambda_dart_runtime/runtime/context.dart'; - -void main() async { - /// This demo's handling an API Gateway request. - hello(Context context, AwsApiGatewayEvent event) async { - final response = { - "message": "Hello from Dart!", - }; - return AwsApiGatewayResponse.fromJson(response); - } - - /// The Runtime is a singleton. You can define the handlers as you wish. - Runtime() - ..registerHandler( - 'hello', - hello, - ) - ..invoke(); -} diff --git a/examples/aws-dart-api/pubspec.yaml b/examples/aws-dart-api/pubspec.yaml deleted file mode 100644 index ed5c78ed7c..0000000000 --- a/examples/aws-dart-api/pubspec.yaml +++ /dev/null @@ -1,16 +0,0 @@ -name: aws_dart_api -description: A starting point for an AWS Serverless Api using Dart and SST ION. -version: 1.0.0 -publish_to: none - -environment: - sdk: ^3.4.0 - -dependencies: - aws_lambda_dart_runtime: - git: - url: https://github.com/katallaxie/aws-lambda-dart-runtime - -dev_dependencies: - lints: ^3.0.0 - test: ^1.24.0 diff --git a/examples/aws-dart-api/sst.config.ts b/examples/aws-dart-api/sst.config.ts deleted file mode 100644 index d9b4232604..0000000000 --- a/examples/aws-dart-api/sst.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-dart-api", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const api = new sst.aws.ApiGatewayV2("MyApi"); - api.route("GET /", { - runtime: "provided.al2023", - architecture: process.arch === "arm64" ? "arm64" : "x86_64", - bundle: build(), - handler: "hello", - }); - }, -}); - -function build() { - require("child_process").execSync(` -mkdir -p .build -docker run -v $PWD:/app -w /app --entrypoint ./build.sh dart:stable-sdk -`); - return `.build/`; -} diff --git a/examples/aws-dead-letter-queue/package.json b/examples/aws-dead-letter-queue/package.json deleted file mode 100644 index f2b2de79e4..0000000000 --- a/examples/aws-dead-letter-queue/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-dead-letter-queue", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "@types/aws-lambda": "^8.10.149", - "sst": "file:../../sdk/js" - }, - "dependencies": { - "@aws-sdk/client-sqs": "^3.515.0" - } -} diff --git a/examples/aws-dead-letter-queue/publisher.ts b/examples/aws-dead-letter-queue/publisher.ts deleted file mode 100644 index 3d71dac18d..0000000000 --- a/examples/aws-dead-letter-queue/publisher.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from "sst"; -import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs"; -const client = new SQSClient(); - -export const handler = async (event) => { - // send a message - await client.send( - new SendMessageCommand({ - QueueUrl: Resource.MyQueue.url, - MessageBody: "Hello from the subscriber", - }) - ); - - return { - statusCode: 200, - body: JSON.stringify({ status: "sent" }, null, 2), - }; -}; diff --git a/examples/aws-dead-letter-queue/sst.config.ts b/examples/aws-dead-letter-queue/sst.config.ts deleted file mode 100644 index c9ebbb6f2b..0000000000 --- a/examples/aws-dead-letter-queue/sst.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -/// - -/** - * ## Subscribe to queues with dead-letter queue - * - * Messages not processed successfully by the primary subscriber function will be sent to the dead-letter queue after the retry limit is reached. - */ -export default $config({ - app(input) { - return { - name: "aws-dead-letter-queue", - home: "aws", - removal: input.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - // create dead letter queue - const dlq = new sst.aws.Queue("DeadLetterQueue"); - dlq.subscribe("subscriber.dlq"); - - // create main queue - const queue = new sst.aws.Queue("MyQueue", { - dlq: dlq.arn, - }); - queue.subscribe("subscriber.main"); - - const app = new sst.aws.Function("MyApp", { - handler: "publisher.handler", - link: [queue], - url: true, - }); - - return { - app: app.url, - queue: queue.url, - dlq: dlq.url, - }; - }, -}); diff --git a/examples/aws-dead-letter-queue/subscriber.ts b/examples/aws-dead-letter-queue/subscriber.ts deleted file mode 100644 index c4b7967f0f..0000000000 --- a/examples/aws-dead-letter-queue/subscriber.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { SQSEvent, SQSHandler } from "aws-lambda"; - -export const main = async (event) => { - console.log(event); - throw new Error("Manual error"); -}; - -export const dlq: SQSHandler = async (event: SQSEvent) => { - console.log(event); - return; -}; diff --git a/examples/aws-deno-redis/.dockerignore b/examples/aws-deno-redis/.dockerignore deleted file mode 100644 index fa2aea8208..0000000000 --- a/examples/aws-deno-redis/.dockerignore +++ /dev/null @@ -1 +0,0 @@ -.sst diff --git a/examples/aws-deno-redis/.gitignore b/examples/aws-deno-redis/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-deno-redis/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-deno-redis/Dockerfile b/examples/aws-deno-redis/Dockerfile deleted file mode 100644 index b5d22eb996..0000000000 --- a/examples/aws-deno-redis/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM denoland/deno - -EXPOSE 8000 - -USER deno - -WORKDIR /app - -ADD . /app - -RUN deno install --entrypoint main.ts - -CMD ["run", "--allow-all", "main.ts"] diff --git a/examples/aws-deno-redis/deno.json b/examples/aws-deno-redis/deno.json deleted file mode 100644 index 322530bdf8..0000000000 --- a/examples/aws-deno-redis/deno.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "tasks": { - "dev": "deno run --watch --allow-all main.ts" - }, - "imports": { - "@std/assert": "jsr:@std/assert@1", - "ioredis": "npm:ioredis@^5.4.1", - "sst": "npm:sst@latest" - } -} diff --git a/examples/aws-deno-redis/main.ts b/examples/aws-deno-redis/main.ts deleted file mode 100644 index 54cc884fe1..0000000000 --- a/examples/aws-deno-redis/main.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - }, -); - -Deno.serve(async (_req) => { - const counter = await redis.incr("counter"); - return new Response(`Hit counter: ${counter}`); -}); diff --git a/examples/aws-deno-redis/main_test.ts b/examples/aws-deno-redis/main_test.ts deleted file mode 100644 index 3d981e9bed..0000000000 --- a/examples/aws-deno-redis/main_test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { assertEquals } from "@std/assert"; -import { add } from "./main.ts"; - -Deno.test(function addTest() { - assertEquals(add(2, 3), 5); -}); diff --git a/examples/aws-deno-redis/sst.config.ts b/examples/aws-deno-redis/sst.config.ts deleted file mode 100644 index ab583c5152..0000000000 --- a/examples/aws-deno-redis/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## AWS Deno Redis - * - * Creates a hit counter app with Deno and Redis. - * - * This deploys Deno as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "8000/http" }], - * }, - * dev: { - * command: "deno task dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * sst dev - * ``` - * - * Now if you go to `http://localhost:8000` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it using `sst deploy --stage production` using a `Dockerfile` - * that's included in the example. - */ -export default $config({ - app(input) { - return { - name: "aws-deno-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "8000/http" }], - }, - dev: { - command: "deno task dev", - }, - }); - }, -}); diff --git a/examples/aws-deno/.dockerignore b/examples/aws-deno/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-deno/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-deno/.gitignore b/examples/aws-deno/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-deno/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-deno/Dockerfile b/examples/aws-deno/Dockerfile deleted file mode 100644 index b5d22eb996..0000000000 --- a/examples/aws-deno/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM denoland/deno - -EXPOSE 8000 - -USER deno - -WORKDIR /app - -ADD . /app - -RUN deno install --entrypoint main.ts - -CMD ["run", "--allow-all", "main.ts"] diff --git a/examples/aws-deno/deno.json b/examples/aws-deno/deno.json deleted file mode 100644 index bfc899069e..0000000000 --- a/examples/aws-deno/deno.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "tasks": { - "dev": "deno run --allow-all --watch main.ts" - }, - "imports": { - "@aws-sdk/client-s3": "npm:@aws-sdk/client-s3@^3.705.0", - "@aws-sdk/lib-storage": "npm:@aws-sdk/lib-storage@^3.705.0", - "@aws-sdk/s3-request-presigner": "npm:@aws-sdk/s3-request-presigner@^3.705.0", - "@std/assert": "jsr:@std/assert@1", - "sst": "npm:sst@latest" - } -} diff --git a/examples/aws-deno/main.ts b/examples/aws-deno/main.ts deleted file mode 100644 index 1518555c6a..0000000000 --- a/examples/aws-deno/main.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { Resource } from "sst"; -import { - S3Client, - GetObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; -import { Upload } from "@aws-sdk/lib-storage"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; - -const s3 = new S3Client(); - -Deno.serve(async (req) => { - const url = new URL(req.url); - - if (url.pathname === "/" && req.method === "GET") { - return new Response("Hello World!"); - } - - if (url.pathname === "/" && req.method === "POST") { - const formData: FormData = await req.formData(); - const file: File | null = formData?.get("file") as File; - - const params = { - Bucket: Resource.MyBucket.name, - ContentType: file.type, - Key: file.name, - Body: file, - }; - const upload = new Upload({ - params, - client: s3, - }); - await upload.done(); - - return new Response("File uploaded successfully."); - } - - if (url.pathname === "/latest" && req.method === "GET") { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0), - )[0]; - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - return Response.redirect(await getSignedUrl(s3, command)); - } - - return new Response("404!"); -}); diff --git a/examples/aws-deno/sst.config.ts b/examples/aws-deno/sst.config.ts deleted file mode 100644 index a414477373..0000000000 --- a/examples/aws-deno/sst.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-deno", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: "80/http", forward: "8000/http" }], - }, - dev: { - command: "deno task dev", - }, - }); - }, -}); diff --git a/examples/aws-drizzle-migrations/.gitignore b/examples/aws-drizzle-migrations/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-drizzle-migrations/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-drizzle-migrations/drizzle.config.ts b/examples/aws-drizzle-migrations/drizzle.config.ts deleted file mode 100644 index 373785baed..0000000000 --- a/examples/aws-drizzle-migrations/drizzle.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Resource } from "sst"; -import { defineConfig } from "drizzle-kit"; - -export default defineConfig({ - dialect: "postgresql", - // Pick up all our schema files - schema: ["./src/**/*.sql.ts"], - out: "./migrations", - dbCredentials: { - ssl: { - rejectUnauthorized: false, - }, - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, - }, -}); diff --git a/examples/aws-drizzle-migrations/migrations/0000_lethal_justin_hammer.sql b/examples/aws-drizzle-migrations/migrations/0000_lethal_justin_hammer.sql deleted file mode 100644 index db52d6f17f..0000000000 --- a/examples/aws-drizzle-migrations/migrations/0000_lethal_justin_hammer.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE IF NOT EXISTS "todo" ( - "id" serial PRIMARY KEY NOT NULL, - "title" text NOT NULL, - "description" text -); diff --git a/examples/aws-drizzle-migrations/migrations/meta/0000_snapshot.json b/examples/aws-drizzle-migrations/migrations/meta/0000_snapshot.json deleted file mode 100644 index 816f447c30..0000000000 --- a/examples/aws-drizzle-migrations/migrations/meta/0000_snapshot.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "id": "89cd0e0e-59a6-42ec-a876-c44671efc130", - "prevId": "00000000-0000-0000-0000-000000000000", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.todo": { - "name": "todo", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {} - } - }, - "enums": {}, - "schemas": {}, - "sequences": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/examples/aws-drizzle-migrations/migrations/meta/_journal.json b/examples/aws-drizzle-migrations/migrations/meta/_journal.json deleted file mode 100644 index d1f9a2ea91..0000000000 --- a/examples/aws-drizzle-migrations/migrations/meta/_journal.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "version": "7", - "dialect": "postgresql", - "entries": [ - { - "idx": 0, - "version": "7", - "when": 1729181504948, - "tag": "0000_lethal_justin_hammer", - "breakpoints": true - } - ] -} \ No newline at end of file diff --git a/examples/aws-drizzle-migrations/package.json b/examples/aws-drizzle-migrations/package.json deleted file mode 100644 index 1e6443a3ed..0000000000 --- a/examples/aws-drizzle-migrations/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-drizzle-migrations", - "version": "0.0.0", - "type": "module", - "scripts": { - "db": "sst shell drizzle-kit" - }, - "dependencies": { - "@types/aws-lambda": "^8.10.142", - "@types/pg": "^8.11.10", - "drizzle-kit": "^0.26.2", - "drizzle-orm": "^0.35.1", - "pg": "^8.13.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-drizzle-migrations/src/api.ts b/examples/aws-drizzle-migrations/src/api.ts deleted file mode 100644 index 1cfb345fc0..0000000000 --- a/examples/aws-drizzle-migrations/src/api.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { db } from "./drizzle"; -import { todo } from "./todo.sql"; -import { APIGatewayProxyEventV2 } from "aws-lambda"; - -export const handler = async (evt: APIGatewayProxyEventV2) => { - if (evt.requestContext.http.method === "GET") { - const result = await db.select().from(todo).execute(); - - return { - statusCode: 200, - body: JSON.stringify(result, null, 2), - }; - } - - if (evt.requestContext.http.method === "POST") { - const result = await db - .insert(todo) - .values({ title: "Todo", description: crypto.randomUUID() }) - .returning() - .execute(); - - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } -}; diff --git a/examples/aws-drizzle-migrations/src/drizzle.ts b/examples/aws-drizzle-migrations/src/drizzle.ts deleted file mode 100644 index c556a2c74a..0000000000 --- a/examples/aws-drizzle-migrations/src/drizzle.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { drizzle } from "drizzle-orm/node-postgres"; -import { Pool } from "pg"; -import { Resource } from "sst"; -import * as schema from "./todo.sql"; - -const pool = new Pool({ - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, -}); - -export const db = drizzle(pool, { schema }); diff --git a/examples/aws-drizzle-migrations/src/migrator.ts b/examples/aws-drizzle-migrations/src/migrator.ts deleted file mode 100644 index d24594b9f2..0000000000 --- a/examples/aws-drizzle-migrations/src/migrator.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { db } from "./drizzle"; -import { migrate } from "drizzle-orm/postgres-js/migrator"; - -export const handler = async (event: any) => { - await migrate(db, { - migrationsFolder: "./migrations", - }); -}; \ No newline at end of file diff --git a/examples/aws-drizzle-migrations/src/scrap.ts b/examples/aws-drizzle-migrations/src/scrap.ts deleted file mode 100644 index ab59ad1118..0000000000 --- a/examples/aws-drizzle-migrations/src/scrap.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { eq } from "drizzle-orm"; -import { db } from "./drizzle"; -import { user } from "./todo.sql"; - -const uuid = "d997d46d-5769-4c78-9a35-93acadbe6076"; -await db.query.user.findMany({ - where: eq(user.id, uuid), - with: { - todos: { - with: { - todo: true, - }, - }, - }, -}); diff --git a/examples/aws-drizzle-migrations/src/todo.sql.ts b/examples/aws-drizzle-migrations/src/todo.sql.ts deleted file mode 100644 index 593829b61b..0000000000 --- a/examples/aws-drizzle-migrations/src/todo.sql.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { text, serial, pgTable } from "drizzle-orm/pg-core"; - -export const todo = pgTable("todo", { - id: serial("id").primaryKey(), - title: text("title").notNull(), - description: text("description"), -}); diff --git a/examples/aws-drizzle-migrations/sst.config.ts b/examples/aws-drizzle-migrations/sst.config.ts deleted file mode 100644 index c19a4bb35c..0000000000 --- a/examples/aws-drizzle-migrations/sst.config.ts +++ /dev/null @@ -1,95 +0,0 @@ -/// - -/** - * ## Drizzle migrations in CI/CD - * - * An example on how to run Drizzle migrations as a part of your CI/CD. - * - * Start by creating a function that runs migrations. - * - * ```ts title="sst.config.ts" - * const migrator = new sst.aws.Function("DatabaseMigrator", { - * handler: "src/migrator.handler", - * link: [rds], - * vpc, - * copyFiles: [ - * { - * from: "migrations", - * to: "./migrations", - * }, - * ], - * }); - * ``` - * - * Where `src/migrator.ts` looks like. - * - * ```ts title="src/migrator.ts" - * import { db } from "./drizzle"; - * import { migrate } from "drizzle-orm/postgres-js/migrator"; - * - * export const handler = async (event: any) => { - * await migrate(db, { - * migrationsFolder: "./migrations", - * }); - * }; - * ``` - * - * And we can set it up to run on every deploy. - * - * ```ts title="sst.config.ts" - * if (!$dev){ - * new aws.lambda.Invocation("DatabaseMigratorInvocation", { - * input: Date.now().toString(), - * functionName: migrator.name, - * }); - * } - * ``` - * - * We use the current time to make sure the function runs on every deploy. - */ -export default $config({ - app(input) { - return { - name: "aws-drizzle-migrations", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true, nat: "ec2" }); - const rds = new sst.aws.Postgres("MyPostgres", { vpc, proxy: true }); - - new sst.aws.Function("MyApi", { - vpc, - url: true, - link: [rds], - handler: "src/api.handler", - }); - - const migrator = new sst.aws.Function("DatabaseMigrator", { - handler: "src/migrator.handler", - link: [rds], - vpc, - copyFiles: [ - { - from: "migrations", - to: "./migrations", - }, - ], - }); - - if (!$dev) { - new aws.lambda.Invocation("DatabaseMigratorInvocation", { - input: Date.now().toString(), - functionName: migrator.name, - }); - } - - new sst.x.DevCommand("Studio", { - link: [rds], - dev: { - command: "npx drizzle-kit studio", - }, - }); - }, -}); diff --git a/examples/aws-drizzle-migrations/tsconfig.json b/examples/aws-drizzle-migrations/tsconfig.json deleted file mode 100644 index aee0ec940f..0000000000 --- a/examples/aws-drizzle-migrations/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "strict": true - } -} diff --git a/examples/aws-drizzle/.gitignore b/examples/aws-drizzle/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-drizzle/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-drizzle/drizzle.config.ts b/examples/aws-drizzle/drizzle.config.ts deleted file mode 100644 index 373785baed..0000000000 --- a/examples/aws-drizzle/drizzle.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Resource } from "sst"; -import { defineConfig } from "drizzle-kit"; - -export default defineConfig({ - dialect: "postgresql", - // Pick up all our schema files - schema: ["./src/**/*.sql.ts"], - out: "./migrations", - dbCredentials: { - ssl: { - rejectUnauthorized: false, - }, - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, - }, -}); diff --git a/examples/aws-drizzle/migrations/0000_lethal_justin_hammer.sql b/examples/aws-drizzle/migrations/0000_lethal_justin_hammer.sql deleted file mode 100644 index db52d6f17f..0000000000 --- a/examples/aws-drizzle/migrations/0000_lethal_justin_hammer.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE IF NOT EXISTS "todo" ( - "id" serial PRIMARY KEY NOT NULL, - "title" text NOT NULL, - "description" text -); diff --git a/examples/aws-drizzle/migrations/meta/0000_snapshot.json b/examples/aws-drizzle/migrations/meta/0000_snapshot.json deleted file mode 100644 index 816f447c30..0000000000 --- a/examples/aws-drizzle/migrations/meta/0000_snapshot.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "id": "89cd0e0e-59a6-42ec-a876-c44671efc130", - "prevId": "00000000-0000-0000-0000-000000000000", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.todo": { - "name": "todo", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {} - } - }, - "enums": {}, - "schemas": {}, - "sequences": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/examples/aws-drizzle/migrations/meta/_journal.json b/examples/aws-drizzle/migrations/meta/_journal.json deleted file mode 100644 index d1f9a2ea91..0000000000 --- a/examples/aws-drizzle/migrations/meta/_journal.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "version": "7", - "dialect": "postgresql", - "entries": [ - { - "idx": 0, - "version": "7", - "when": 1729181504948, - "tag": "0000_lethal_justin_hammer", - "breakpoints": true - } - ] -} \ No newline at end of file diff --git a/examples/aws-drizzle/package.json b/examples/aws-drizzle/package.json deleted file mode 100644 index fde9d0b941..0000000000 --- a/examples/aws-drizzle/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-drizzle", - "version": "0.0.0", - "type": "module", - "scripts": { - "db": "sst shell drizzle-kit" - }, - "dependencies": { - "@types/aws-lambda": "^8.10.142", - "@types/pg": "^8.11.10", - "drizzle-kit": "^0.26.2", - "drizzle-orm": "^0.35.1", - "pg": "^8.13.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-drizzle/src/api.ts b/examples/aws-drizzle/src/api.ts deleted file mode 100644 index 1cfb345fc0..0000000000 --- a/examples/aws-drizzle/src/api.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { db } from "./drizzle"; -import { todo } from "./todo.sql"; -import { APIGatewayProxyEventV2 } from "aws-lambda"; - -export const handler = async (evt: APIGatewayProxyEventV2) => { - if (evt.requestContext.http.method === "GET") { - const result = await db.select().from(todo).execute(); - - return { - statusCode: 200, - body: JSON.stringify(result, null, 2), - }; - } - - if (evt.requestContext.http.method === "POST") { - const result = await db - .insert(todo) - .values({ title: "Todo", description: crypto.randomUUID() }) - .returning() - .execute(); - - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } -}; diff --git a/examples/aws-drizzle/src/drizzle.ts b/examples/aws-drizzle/src/drizzle.ts deleted file mode 100644 index c556a2c74a..0000000000 --- a/examples/aws-drizzle/src/drizzle.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { drizzle } from "drizzle-orm/node-postgres"; -import { Pool } from "pg"; -import { Resource } from "sst"; -import * as schema from "./todo.sql"; - -const pool = new Pool({ - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, -}); - -export const db = drizzle(pool, { schema }); diff --git a/examples/aws-drizzle/src/scrap.ts b/examples/aws-drizzle/src/scrap.ts deleted file mode 100644 index ab59ad1118..0000000000 --- a/examples/aws-drizzle/src/scrap.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { eq } from "drizzle-orm"; -import { db } from "./drizzle"; -import { user } from "./todo.sql"; - -const uuid = "d997d46d-5769-4c78-9a35-93acadbe6076"; -await db.query.user.findMany({ - where: eq(user.id, uuid), - with: { - todos: { - with: { - todo: true, - }, - }, - }, -}); diff --git a/examples/aws-drizzle/src/todo.sql.ts b/examples/aws-drizzle/src/todo.sql.ts deleted file mode 100644 index 593829b61b..0000000000 --- a/examples/aws-drizzle/src/todo.sql.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { text, serial, pgTable } from "drizzle-orm/pg-core"; - -export const todo = pgTable("todo", { - id: serial("id").primaryKey(), - title: text("title").notNull(), - description: text("description"), -}); diff --git a/examples/aws-drizzle/sst.config.ts b/examples/aws-drizzle/sst.config.ts deleted file mode 100644 index cc3b885b7c..0000000000 --- a/examples/aws-drizzle/sst.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-drizzle", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true, nat: "ec2" }); - const rds = new sst.aws.Postgres("MyPostgres", { vpc, proxy: true }); - - new sst.aws.Function("MyApi", { - vpc, - url: true, - link: [rds], - handler: "src/api.handler", - }); - - new sst.x.DevCommand("Studio", { - link: [rds], - dev: { - command: "npx drizzle-kit studio", - }, - }); - }, -}); diff --git a/examples/aws-drizzle/tsconfig.json b/examples/aws-drizzle/tsconfig.json deleted file mode 100644 index aee0ec940f..0000000000 --- a/examples/aws-drizzle/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "strict": true - } -} diff --git a/examples/aws-dsql-drizzle/.gitignore b/examples/aws-dsql-drizzle/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-dsql-drizzle/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-dsql-drizzle/drizzle.config.ts b/examples/aws-dsql-drizzle/drizzle.config.ts deleted file mode 100644 index ba08a3f2c4..0000000000 --- a/examples/aws-dsql-drizzle/drizzle.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from "sst"; -import { defineConfig } from "drizzle-kit"; - -export default defineConfig({ - dialect: "postgresql", - schema: ["./src/**/*.sql.ts"], - out: "./migrations", - dbCredentials: { - host: Resource.MyCluster.endpoint, - port: 5432, - user: "admin", - password: process.env.DSQL_TOKEN!, - database: "postgres", - ssl: { - rejectUnauthorized: false, - }, - }, -}); diff --git a/examples/aws-dsql-drizzle/package.json b/examples/aws-dsql-drizzle/package.json deleted file mode 100644 index 6b24eb27a5..0000000000 --- a/examples/aws-dsql-drizzle/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "aws-dsql-drizzle", - "version": "0.0.0", - "type": "module", - "scripts": { - "db": "sst shell drizzle-kit" - }, - "dependencies": { - "@aws-sdk/credential-providers": "^3.844.0", - "@aws-sdk/dsql-signer": "^3.844.0", - "@aws/aurora-dsql-node-postgres-connector": "^0.1.8", - "@types/aws-lambda": "^8.10.142", - "@types/pg": "^8.11.10", - "drizzle-kit": "^0.26.2", - "drizzle-orm": "^0.35.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-dsql-drizzle/push.ts b/examples/aws-dsql-drizzle/push.ts deleted file mode 100644 index 8481e544ad..0000000000 --- a/examples/aws-dsql-drizzle/push.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { DsqlSigner } from "@aws-sdk/dsql-signer"; -import { Resource } from "sst"; -import { execSync } from "child_process"; - -const signer = new DsqlSigner({ - region: Resource.MyCluster.region, - hostname: Resource.MyCluster.endpoint, -}); - -const token = await signer.getDbConnectAdminAuthToken(); - -execSync("bunx drizzle-kit push", { - stdio: "inherit", - env: { - ...process.env, - DSQL_TOKEN: token, - }, -}); diff --git a/examples/aws-dsql-drizzle/src/api.ts b/examples/aws-dsql-drizzle/src/api.ts deleted file mode 100644 index 1cfb345fc0..0000000000 --- a/examples/aws-dsql-drizzle/src/api.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { db } from "./drizzle"; -import { todo } from "./todo.sql"; -import { APIGatewayProxyEventV2 } from "aws-lambda"; - -export const handler = async (evt: APIGatewayProxyEventV2) => { - if (evt.requestContext.http.method === "GET") { - const result = await db.select().from(todo).execute(); - - return { - statusCode: 200, - body: JSON.stringify(result, null, 2), - }; - } - - if (evt.requestContext.http.method === "POST") { - const result = await db - .insert(todo) - .values({ title: "Todo", description: crypto.randomUUID() }) - .returning() - .execute(); - - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } -}; diff --git a/examples/aws-dsql-drizzle/src/drizzle.ts b/examples/aws-dsql-drizzle/src/drizzle.ts deleted file mode 100644 index 705e8e91e7..0000000000 --- a/examples/aws-dsql-drizzle/src/drizzle.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { drizzle } from "drizzle-orm/node-postgres"; -import { AuroraDSQLPool } from "@aws/aurora-dsql-node-postgres-connector"; -import { Resource } from "sst"; -import * as schema from "./todo.sql"; - -const pool = new AuroraDSQLPool({ - host: Resource.MyCluster.endpoint, - user: "admin", -}); - -export const db = drizzle(pool, { schema }); diff --git a/examples/aws-dsql-drizzle/src/todo.sql.ts b/examples/aws-dsql-drizzle/src/todo.sql.ts deleted file mode 100644 index b04e165a5c..0000000000 --- a/examples/aws-dsql-drizzle/src/todo.sql.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { text, bigint, pgTable } from "drizzle-orm/pg-core"; - -export const todo = pgTable("todo", { - id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(), - title: text("title").notNull(), - description: text("description"), -}); diff --git a/examples/aws-dsql-drizzle/sst.config.ts b/examples/aws-dsql-drizzle/sst.config.ts deleted file mode 100644 index 4edaefc62a..0000000000 --- a/examples/aws-dsql-drizzle/sst.config.ts +++ /dev/null @@ -1,66 +0,0 @@ -/// - -/** - * ## AWS Aurora DSQL with Drizzle - * - * In this example, we use Drizzle ORM with an Aurora DSQL cluster. - * - * ```ts title="sst.config.ts" - * const cluster = new sst.aws.Dsql("MyCluster"); - * ``` - * - * And link it to a Lambda function. - * - * ```ts title="sst.config.ts" {4} - * new sst.aws.Function("MyApi", { - * handler: "src/api.handler", - * link: [cluster], - * url: true, - * }); - * ``` - * - * Push the Drizzle schema to the database. - * - * ```bash - * sst shell -- bun run push.ts - * ``` - * - * Now in the function we can connect to the cluster using Drizzle with the DSQL connector. - * Learn more about [DSQL Node.js connectors](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/SECTION_Node-js-connectors.html). - * - * ```ts title="src/drizzle.ts" - * import { drizzle } from "drizzle-orm/node-postgres"; - * import { AuroraDSQLPool } from "@aws/aurora-dsql-node-postgres-connector"; - * import { Resource } from "sst"; - * - * const pool = new AuroraDSQLPool({ - * host: Resource.MyCluster.endpoint, - * user: "admin", - * }); - * - * export const db = drizzle(pool, { schema }); - * ``` - */ -export default $config({ - app(input) { - return { - name: "aws-dsql-drizzle", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const cluster = new sst.aws.Dsql("MyCluster"); - - new sst.aws.Function("MyApi", { - handler: "src/api.handler", - link: [cluster], - url: true, - }); - - return { - endpoint: cluster.endpoint, - region: cluster.region, - }; - }, -}); diff --git a/examples/aws-dsql-drizzle/tsconfig.json b/examples/aws-dsql-drizzle/tsconfig.json deleted file mode 100644 index aee0ec940f..0000000000 --- a/examples/aws-dsql-drizzle/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "strict": true - } -} diff --git a/examples/aws-dsql-multiregion/.gitignore b/examples/aws-dsql-multiregion/.gitignore deleted file mode 100644 index 2060062401..0000000000 --- a/examples/aws-dsql-multiregion/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# sst -.sst -bun.lock \ No newline at end of file diff --git a/examples/aws-dsql-multiregion/lambda.ts b/examples/aws-dsql-multiregion/lambda.ts deleted file mode 100644 index 28e5441dd8..0000000000 --- a/examples/aws-dsql-multiregion/lambda.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { AuroraDSQLClient } from "@aws/aurora-dsql-node-postgres-connector"; -import { Resource } from "sst"; - -async function connectToCluster(endpoint: string) { - const client = new AuroraDSQLClient({ - host: endpoint, - user: "admin", - }); - - await client.connect(); - const result = await client.query("SELECT NOW() as now"); - await client.end(); - - return result.rows[0].now; -} - -export const handler = async () => { - try { - const usEast1Time = await connectToCluster(Resource.MultiRegion.endpoint); - - const usEast2Time = await connectToCluster(Resource.MultiRegion.peer.endpoint); - - return { - statusCode: 200, - body: JSON.stringify({ - message: "Successfully connected to both DSQL clusters.", - usEast1Time, - usEast2Time, - }), - }; - } catch (error) { - console.error("Error accessing DSQL clusters:", error); - return { - statusCode: 500, - body: JSON.stringify({ - error: "Failed to access DSQL clusters", - details: error instanceof Error ? error.message : String(error), - }), - }; - } -}; diff --git a/examples/aws-dsql-multiregion/package.json b/examples/aws-dsql-multiregion/package.json deleted file mode 100644 index ad0e8cdc63..0000000000 --- a/examples/aws-dsql-multiregion/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-dsql-multiregion", - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "sst dev", - "deploy": "sst deploy", - "remove": "sst remove" - }, - "dependencies": { - "@aws-sdk/credential-providers": "^3.844.0", - "@aws/aurora-dsql-node-postgres-connector": "^0.1.8", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.133", - "@types/pg": "^8.10.9" - } -} diff --git a/examples/aws-dsql-multiregion/sst.config.ts b/examples/aws-dsql-multiregion/sst.config.ts deleted file mode 100644 index 8d09ff4867..0000000000 --- a/examples/aws-dsql-multiregion/sst.config.ts +++ /dev/null @@ -1,82 +0,0 @@ -/// - -/** - * ## AWS Aurora DSQL Multi-Region - * - * In this example, we deploy a multi-region Aurora DSQL cluster and connect to both - * clusters from a Lambda function. - * - * :::note - * Multi-region with VPCs is not currently supported. - * ::: - * - * Create the cluster with a witness region and a peer region. The witness must differ - * from both cluster regions. - * - * ```ts title="sst.config.ts" - * const cluster = new sst.aws.Dsql("MultiRegion", { - * regions: { - * witness: "us-west-2", - * peer: "us-east-2", - * }, - * }); - * ``` - * - * Connect to both clusters from your function using the DSQL connector. - * Learn more about [DSQL Node.js connectors](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/SECTION_Node-js-connectors.html). - * - * ```ts title="lambda.ts" - * import { AuroraDSQLClient } from "@aws/aurora-dsql-node-postgres-connector"; - * import { Resource } from "sst"; - * - * async function connectToCluster(endpoint: string) { - * const client = new AuroraDSQLClient({ host: endpoint, user: "admin" }); - * await client.connect(); - * return client; - * } - * - * // Cluster in us-east-1 - * const usEast1 = await connectToCluster(Resource.MultiRegion.endpoint); - * - * // Cluster in us-east-2 - * const usEast2 = await connectToCluster(Resource.MultiRegion.peer.endpoint); - * ``` - */ - -export default $config({ - app(input) { - return { - name: "aws-dsql-multiregion", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - aws: { region: "us-east-1" }, - }, - }; - }, - async run() { - const cluster = new sst.aws.Dsql("MultiRegion", { - backup: true, - regions: { - witness: "us-west-2", - peer: "us-east-2", - }, - }); - - const fn = new sst.aws.Function("MyFunction", { - handler: "lambda.handler", - link: [cluster], - url: true, - }); - - return { - url: fn.url, - arn: cluster.arn, - endpoint: cluster.endpoint, - region: cluster.region, - peerArn: cluster.peer.arn, - peerEndpoint: cluster.peer.endpoint, - peerRegion: cluster.peer.region, - }; - }, -}); diff --git a/examples/aws-dsql-vpc/.gitignore b/examples/aws-dsql-vpc/.gitignore deleted file mode 100644 index 2060062401..0000000000 --- a/examples/aws-dsql-vpc/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# sst -.sst -bun.lock \ No newline at end of file diff --git a/examples/aws-dsql-vpc/lambda.ts b/examples/aws-dsql-vpc/lambda.ts deleted file mode 100644 index 6c8c676be8..0000000000 --- a/examples/aws-dsql-vpc/lambda.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { AuroraDSQLClient } from "@aws/aurora-dsql-node-postgres-connector"; -import { Resource } from "sst"; - -export const handler = async () => { - try { - const client = new AuroraDSQLClient({ - host: Resource.MyCluster.endpoint, - user: "admin", - }); - - await client.connect(); - const now = await client.query("SELECT NOW() as now"); - await client.end(); - - return { - statusCode: 200, - body: JSON.stringify({ - message: "Successfully connected to DSQL cluster.", - now: now.rows[0].now, - }), - }; - } catch (error) { - console.error("Error accessing DSQL cluster:", error); - return { - statusCode: 500, - body: JSON.stringify({ - error: "Failed to access DSQL cluster", - details: error instanceof Error ? error.message : String(error), - }), - }; - } -}; diff --git a/examples/aws-dsql-vpc/package.json b/examples/aws-dsql-vpc/package.json deleted file mode 100644 index fe05e2ec1b..0000000000 --- a/examples/aws-dsql-vpc/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-dsql-vpc", - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "sst dev", - "deploy": "sst deploy", - "remove": "sst remove" - }, - "dependencies": { - "@aws-sdk/credential-providers": "^3.844.0", - "@aws/aurora-dsql-node-postgres-connector": "^0.1.8", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.133", - "@types/pg": "^8.10.9" - } -} diff --git a/examples/aws-dsql-vpc/sst.config.ts b/examples/aws-dsql-vpc/sst.config.ts deleted file mode 100644 index 390c868187..0000000000 --- a/examples/aws-dsql-vpc/sst.config.ts +++ /dev/null @@ -1,84 +0,0 @@ -/// - -/** - * ## AWS Aurora DSQL in a VPC - * - * In this example, we connect to an Aurora DSQL cluster privately from a Lambda - * function using VPC endpoints, without routing traffic over the public internet. - * - * Create a VPC, then create the cluster with a connection endpoint inside it. - * - * ```ts title="sst.config.ts" - * const vpc = new sst.aws.Vpc("MyVpc"); - * - * const cluster = new sst.aws.Dsql("MyCluster", { - * vpc: { - * instance: vpc, - * endpoints: { connection: true }, - * }, - * }); - * ``` - * - * Link the cluster to a function that's also in the VPC. The linked `endpoint` will - * automatically resolve to the private VPC endpoint hostname instead of the public one. - * - * ```ts title="sst.config.ts" - * new sst.aws.Function("MyFunction", { - * handler: "lambda.handler", - * vpc, - * link: [cluster], - * }); - * ``` - * - * Connect from your function using the DSQL connector — no config changes needed. - * Learn more about [DSQL Node.js connectors](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/SECTION_Node-js-connectors.html). - * - * ```ts title="lambda.ts" - * import { AuroraDSQLClient } from "@aws/aurora-dsql-node-postgres-connector"; - * import { Resource } from "sst"; - * - * const client = new AuroraDSQLClient({ - * host: Resource.MyCluster.endpoint, - * user: "admin", - * }); - * - * await client.connect(); - * const result = await client.query("SELECT NOW()"); - * await client.end(); - * ``` - */ - -export default $config({ - app(input) { - return { - name: "aws-dsql-vpc", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("singleClusterVpc"); - - const cluster = new sst.aws.Dsql("MyCluster", { - vpc: { - instance: vpc, - endpoints: { - connection: true, - management: false, - }, - }, - }); - - const fn = new sst.aws.Function("MyFunction", { - handler: "lambda.handler", - vpc, - link: [cluster], - url: true, - }); - - return { - endpoint: cluster.endpoint, - region: cluster.region, - }; - }, -}); diff --git a/examples/aws-dsql/.gitignore b/examples/aws-dsql/.gitignore deleted file mode 100644 index 2060062401..0000000000 --- a/examples/aws-dsql/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# sst -.sst -bun.lock \ No newline at end of file diff --git a/examples/aws-dsql/lambda.ts b/examples/aws-dsql/lambda.ts deleted file mode 100644 index 6c8c676be8..0000000000 --- a/examples/aws-dsql/lambda.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { AuroraDSQLClient } from "@aws/aurora-dsql-node-postgres-connector"; -import { Resource } from "sst"; - -export const handler = async () => { - try { - const client = new AuroraDSQLClient({ - host: Resource.MyCluster.endpoint, - user: "admin", - }); - - await client.connect(); - const now = await client.query("SELECT NOW() as now"); - await client.end(); - - return { - statusCode: 200, - body: JSON.stringify({ - message: "Successfully connected to DSQL cluster.", - now: now.rows[0].now, - }), - }; - } catch (error) { - console.error("Error accessing DSQL cluster:", error); - return { - statusCode: 500, - body: JSON.stringify({ - error: "Failed to access DSQL cluster", - details: error instanceof Error ? error.message : String(error), - }), - }; - } -}; diff --git a/examples/aws-dsql/package.json b/examples/aws-dsql/package.json deleted file mode 100644 index 3038223d17..0000000000 --- a/examples/aws-dsql/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-dsql", - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "sst dev", - "deploy": "sst deploy", - "remove": "sst remove" - }, - "dependencies": { - "@aws-sdk/credential-providers": "^3.844.0", - "@aws/aurora-dsql-node-postgres-connector": "^0.1.8", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.133", - "@types/pg": "^8.10.9" - } -} diff --git a/examples/aws-dsql/sst.config.ts b/examples/aws-dsql/sst.config.ts deleted file mode 100644 index cc3477e4f3..0000000000 --- a/examples/aws-dsql/sst.config.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -/** - * ## AWS Aurora DSQL - * - * In this example, we deploy an Aurora DSQL cluster. - * - * ```ts title="sst.config.ts" - * const cluster = new sst.aws.Dsql("MyCluster"); - * ``` - * - * And link it to a Lambda function. - * - * ```ts title="sst.config.ts" {4} - * new sst.aws.Function("MyFunction", { - * handler: "lambda.handler", - * link: [cluster], - * url: true, - * }); - * ``` - * - * Now in the function we can connect to the cluster using the DSQL connector. - * Learn more about [DSQL Node.js connectors](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/SECTION_Node-js-connectors.html). - * - * ```ts title="lambda.ts" - * import { AuroraDSQLClient } from "@aws/aurora-dsql-node-postgres-connector"; - * import { Resource } from "sst"; - * - * const client = new AuroraDSQLClient({ - * host: Resource.MyCluster.endpoint, - * user: "admin", - * }); - * - * await client.connect(); - * const result = await client.query("SELECT NOW()"); - * await client.end(); - * ``` - */ - -export default $config({ - app(input) { - return { - name: "aws-dsql", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const cluster = new sst.aws.Dsql("MyCluster", {}); - - const fn = new sst.aws.Function("MyFunction", { - handler: "lambda.handler", - link: [cluster], - url: true, - }); - - return { - endpoint: cluster.endpoint, - region: cluster.region, - }; - }, -}); \ No newline at end of file diff --git a/examples/aws-dynamo-composite-keys/creator.ts b/examples/aws-dynamo-composite-keys/creator.ts deleted file mode 100644 index 4a9365b223..0000000000 --- a/examples/aws-dynamo-composite-keys/creator.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Resource } from "sst"; -import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; -const client = new DynamoDBClient(); - -export const handler = async () => { - await client.send( - new PutItemCommand({ - TableName: Resource.MyTable.name, - Item: { - userId: { S: "user1" }, - noteId: { S: Date.now().toString() }, - region: { S: "us-east" }, - category: { S: "notes" }, - createdAt: { N: Date.now().toString() }, - }, - }) - ); - - return { - statusCode: 200, - body: JSON.stringify({ status: "sent" }, null, 2), - }; -}; diff --git a/examples/aws-dynamo-composite-keys/package.json b/examples/aws-dynamo-composite-keys/package.json deleted file mode 100644 index 1269793242..0000000000 --- a/examples/aws-dynamo-composite-keys/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-dynamo-composite-keys", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "sst": "file:../../sdk/js" - }, - "dependencies": { - "@aws-sdk/client-dynamodb": "^3.515.0" - } -} diff --git a/examples/aws-dynamo-composite-keys/reader.ts b/examples/aws-dynamo-composite-keys/reader.ts deleted file mode 100644 index dfb2b1527b..0000000000 --- a/examples/aws-dynamo-composite-keys/reader.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Resource } from "sst"; -import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb"; -const client = new DynamoDBClient(); - -export const handler = async () => { - const result = await client.send( - new QueryCommand({ - TableName: Resource.MyTable.name, - IndexName: "RegionCategoryIndex", - KeyConditionExpression: "#r = :region AND #c = :category", - ExpressionAttributeNames: { - "#r": "region", - "#c": "category", - }, - ExpressionAttributeValues: { - ":region": { S: "us-east" }, - ":category": { S: "notes" }, - }, - }) - ); - - return { - statusCode: 200, - body: JSON.stringify(result.Items, null, 2), - }; -}; diff --git a/examples/aws-dynamo-composite-keys/sst.config.ts b/examples/aws-dynamo-composite-keys/sst.config.ts deleted file mode 100644 index dfea2ec245..0000000000 --- a/examples/aws-dynamo-composite-keys/sst.config.ts +++ /dev/null @@ -1,52 +0,0 @@ -/// - -/** - * ## DynamoDB composite keys - * - * Create a DynamoDB table with multi-attribute composite keys in a global secondary index. - */ -export default $config({ - app(input) { - return { - name: "aws-dynamo-composite-keys", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const table = new sst.aws.Dynamo("MyTable", { - fields: { - userId: "string", - noteId: "string", - region: "string", - category: "string", - createdAt: "number", - }, - primaryIndex: { hashKey: "userId", rangeKey: "noteId" }, - globalIndexes: { - RegionCategoryIndex: { - hashKey: ["region", "category"], - rangeKey: "createdAt", - }, - }, - }); - - const creator = new sst.aws.Function("MyCreator", { - handler: "creator.handler", - link: [table], - url: true, - }); - - const reader = new sst.aws.Function("MyReader", { - handler: "reader.handler", - link: [table], - url: true, - }); - - return { - creator: creator.url, - reader: reader.url, - table: table.name, - }; - }, -}); diff --git a/examples/aws-dynamo/creator.ts b/examples/aws-dynamo/creator.ts deleted file mode 100644 index f90ac02884..0000000000 --- a/examples/aws-dynamo/creator.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Resource } from "sst"; -import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; -const client = new DynamoDBClient(); - -export const handler = async (event) => { - await client.send( - new PutItemCommand({ - TableName: Resource.MyTable.name, - Item: { - id: { S: Date.now().toString() }, - message: { S: "Hello" }, - }, - }) - ); - - return { - statusCode: 200, - body: JSON.stringify({ status: "sent" }, null, 2), - }; -}; diff --git a/examples/aws-dynamo/package.json b/examples/aws-dynamo/package.json deleted file mode 100644 index fd944c5262..0000000000 --- a/examples/aws-dynamo/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-dynamo", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "sst": "file:../../sdk/js" - }, - "dependencies": { - "@aws-sdk/client-dynamodb": "^3.515.0" - } -} diff --git a/examples/aws-dynamo/reader.ts b/examples/aws-dynamo/reader.ts deleted file mode 100644 index fd68d74ea7..0000000000 --- a/examples/aws-dynamo/reader.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Resource } from "sst"; -import { DynamoDBClient, ScanCommand } from "@aws-sdk/client-dynamodb"; -const client = new DynamoDBClient(); - -export const handler = async () => { - const result = await client.send( - new ScanCommand({ - TableName: Resource.MyTable.name, - }) - ); - - return { - statusCode: 200, - body: JSON.stringify(result.Items, null, 2), - }; -}; diff --git a/examples/aws-dynamo/sst.config.ts b/examples/aws-dynamo/sst.config.ts deleted file mode 100644 index 9d9ff5d5b2..0000000000 --- a/examples/aws-dynamo/sst.config.ts +++ /dev/null @@ -1,56 +0,0 @@ -/// - -/** - * ## DynamoDB streams - * - * Create a DynamoDB table, enable streams, and subscribe to it with a function. - */ -export default $config({ - app(input) { - return { - name: "aws-dynamo", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const table = new sst.aws.Dynamo("MyTable", { - fields: { - id: "string", - }, - primaryIndex: { hashKey: "id" }, - stream: "new-and-old-images", - }); - table.subscribe("MySubscriber", "subscriber.handler", { - filters: [ - { - dynamodb: { - NewImage: { - message: { - S: ["Hello"], - }, - }, - }, - }, - ], - }); - - const creator = new sst.aws.Function("MyCreator", { - handler: "creator.handler", - link: [table], - url: true, - }); - - const reader = new sst.aws.Function("MyReader", { - handler: "reader.handler", - link: [table], - url: true, - }); - - return { - creator: creator.url, - reader: reader.url, - table: table.name, - }; - }, -}); diff --git a/examples/aws-dynamo/subscriber.ts b/examples/aws-dynamo/subscriber.ts deleted file mode 100644 index 342cf63a05..0000000000 --- a/examples/aws-dynamo/subscriber.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const handler = async (event) => { - console.log(JSON.stringify(event, null, 2)); - return "ok"; -}; diff --git a/examples/aws-ec2-pulumi/package.json b/examples/aws-ec2-pulumi/package.json deleted file mode 100644 index b4ad3bd51e..0000000000 --- a/examples/aws-ec2-pulumi/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-ec2-pulumi", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "sst": "file:../../sdk/js" - }, - "dependencies": { - } -} diff --git a/examples/aws-ec2-pulumi/sst.config.ts b/examples/aws-ec2-pulumi/sst.config.ts deleted file mode 100644 index 0987879b00..0000000000 --- a/examples/aws-ec2-pulumi/sst.config.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// - -/** - * ## EC2 with Pulumi - * - * Use raw Pulumi resources to create an EC2 instance. - */ -export default $config({ - app(input) { - return { - name: "aws-ec2-pulumi", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - // Notice you don't need to import pulumi, it is already part of sst. - const securityGroup = new aws.ec2.SecurityGroup("web-secgrp", { - ingress: [ - { - protocol: "tcp", - fromPort: 80, - toPort: 80, - cidrBlocks: ["0.0.0.0/0"], - }, - ], - }); - - // Find the latest Ubuntu AMI - const ami = aws.ec2.getAmi({ - filters: [ - { - name: "name", - values: ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"], - }, - ], - mostRecent: true, - owners: ["099720109477"], // Canonical - }); - - // User data to set up a simple web server - const userData = `#!/bin/bash - echo "Hello, World!" > index.html - nohup python3 -m http.server 80 &`; - - // Create an EC2 instance - const server = new aws.ec2.Instance("web-server", { - instanceType: "t2.micro", - ami: ami.then((ami) => ami.id), - userData: userData, - vpcSecurityGroupIds: [securityGroup.id], - associatePublicIpAddress: true, - }); - - return { - app: server.publicIp, - }; - }, -}); diff --git a/examples/aws-efs-sqlite/.gitignore b/examples/aws-efs-sqlite/.gitignore deleted file mode 100644 index 9b1ee42e84..0000000000 --- a/examples/aws-efs-sqlite/.gitignore +++ /dev/null @@ -1,175 +0,0 @@ -# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore - -# Logs - -logs -_.log -npm-debug.log_ -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -.pnpm-debug.log* - -# Caches - -.cache - -# Diagnostic reports (https://nodejs.org/api/report.html) - -report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json - -# Runtime data - -pids -_.pid -_.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover - -lib-cov - -# Coverage directory used by tools like istanbul - -coverage -*.lcov - -# nyc test coverage - -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) - -.grunt - -# Bower dependency directory (https://bower.io/) - -bower_components - -# node-waf configuration - -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) - -build/Release - -# Dependency directories - -node_modules/ -jspm_packages/ - -# Snowpack dependency directory (https://snowpack.dev/) - -web_modules/ - -# TypeScript cache - -*.tsbuildinfo - -# Optional npm cache directory - -.npm - -# Optional eslint cache - -.eslintcache - -# Optional stylelint cache - -.stylelintcache - -# Microbundle cache - -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history - -.node_repl_history - -# Output of 'npm pack' - -*.tgz - -# Yarn Integrity file - -.yarn-integrity - -# dotenv environment variable files - -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# parcel-bundler cache (https://parceljs.org/) - -.parcel-cache - -# Next.js build output - -.next -out - -# Nuxt.js build / generate output - -.nuxt -dist - -# Gatsby files - -# Comment in the public line in if your project uses Gatsby and not Next.js - -# https://nextjs.org/blog/next-9-1#public-directory-support - -# public - -# vuepress build output - -.vuepress/dist - -# vuepress v2.x temp and cache directory - -.temp - -# Docusaurus cache and generated files - -.docusaurus - -# Serverless directories - -.serverless/ - -# FuseBox cache - -.fusebox/ - -# DynamoDB Local files - -.dynamodb/ - -# TernJS port file - -.tern-port - -# Stores VSCode versions used for testing VSCode extensions - -.vscode-test - -# yarn v2 - -.yarn/cache -.yarn/unplugged -.yarn/build-state.yml -.yarn/install-state.gz -.pnp.* - -# IntelliJ based IDEs -.idea - -# Finder (MacOS) folder config -.DS_Store diff --git a/examples/aws-efs-sqlite/index.ts b/examples/aws-efs-sqlite/index.ts deleted file mode 100644 index f407e5a1fd..0000000000 --- a/examples/aws-efs-sqlite/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -import sqlite3 from "better-sqlite3"; -const db = sqlite3("/mnt/efs/mydb.sqlite"); - -export const handler = async () => { - db.exec(` - CREATE TABLE IF NOT EXISTS visits ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - timestamp TEXT NOT NULL - ); - `); - - // Record a visit - db.prepare("INSERT INTO visits (timestamp) VALUES (CURRENT_TIMESTAMP)").run(); - - // Get recent visits - const visits = db - .prepare("SELECT * FROM visits ORDER BY timestamp DESC LIMIT 10") - .all(); - - return { - statusCode: 200, - body: JSON.stringify({ "10 Most recent visits": visits }, null, 2), - }; -}; diff --git a/examples/aws-efs-sqlite/package.json b/examples/aws-efs-sqlite/package.json deleted file mode 100644 index 821d9ef6ab..0000000000 --- a/examples/aws-efs-sqlite/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-efs-sqlite", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "better-sqlite3": "^11.4.0" - } -} diff --git a/examples/aws-efs-sqlite/sst.config.ts b/examples/aws-efs-sqlite/sst.config.ts deleted file mode 100644 index ec903fa266..0000000000 --- a/examples/aws-efs-sqlite/sst.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -/// - -/** - * ## AWS EFS with SQLite - * - * Mount an EFS file system to a function and write to a SQLite database. - * - * ```js title="index.ts" - * const db = sqlite3("/mnt/efs/mydb.sqlite"); - * ``` - * - * The file system is mounted to `/mnt/efs` in the function. - * - * :::note - * Given the performance of EFS, it's not recommended to use it for databases. - * ::: - * - * This example is for demonstration purposes only. It's not recommended to use - * EFS for databases in production. - */ -export default $config({ - app(input) { - return { - name: "aws-efs-sqlite", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // NAT Gateways are required for Lambda functions - const vpc = new sst.aws.Vpc("MyVpc", { nat: "managed" }); - - // Create an EFS file system to store the SQLite database - const efs = new sst.aws.Efs("MyEfs", { vpc }); - - // Create a Lambda function that queries the database - new sst.aws.Function("MyFunction", { - vpc, - url: true, - volume: { - efs, - path: "/mnt/efs", - }, - handler: "index.handler", - nodejs: { - install: ["better-sqlite3"], - }, - }); - }, -}); diff --git a/examples/aws-efs-sqlite/tsconfig.json b/examples/aws-efs-sqlite/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-efs-sqlite/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-efs-surrealdb/.gitignore b/examples/aws-efs-surrealdb/.gitignore deleted file mode 100644 index f3c8b5fb20..0000000000 --- a/examples/aws-efs-surrealdb/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ - -# sst -.sst - -.envrc -shell.nix -pnpm-* \ No newline at end of file diff --git a/examples/aws-efs-surrealdb/index.ts b/examples/aws-efs-surrealdb/index.ts deleted file mode 100644 index fe20791598..0000000000 --- a/examples/aws-efs-surrealdb/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -import Surreal from "surrealdb"; -import { Resource } from "sst"; - -export const handler = async () => { - const endpoint = `http://${Resource.MyConfig.host}:${Resource.MyConfig.port}`; - - console.log(`Connecting to`, endpoint); - - const db = new Surreal(); - await db.connect(endpoint); - - await db.use({ - namespace: Resource.MyConfig.namespace, - database: Resource.MyConfig.database, - }); - - await db.signin({ - username: Resource.MyConfig.username, - password: Resource.MyConfig.password, - }); - - await db.query(`INSERT INTO visits { when: time::now() }`); - - const visits = await db.query( - `SELECT * FROM visits ORDER BY when DESC LIMIT 10` - ); - - return { - statusCode: 200, - body: JSON.stringify({ "10 Most recent visits": visits[0] }, null, 2), - }; -}; diff --git a/examples/aws-efs-surrealdb/package.json b/examples/aws-efs-surrealdb/package.json deleted file mode 100644 index adccacafad..0000000000 --- a/examples/aws-efs-surrealdb/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-efs-surrealdb", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sst": "file:../../sdk/js", - "surrealdb": "^1.0.1" - } -} diff --git a/examples/aws-efs-surrealdb/sst.config.ts b/examples/aws-efs-surrealdb/sst.config.ts deleted file mode 100644 index d68d38b264..0000000000 --- a/examples/aws-efs-surrealdb/sst.config.ts +++ /dev/null @@ -1,106 +0,0 @@ -/// -/** - * ## AWS EFS with SurrealDB - * - * We use the SurrealDB docker image to run a server in a container and use EFS as the file - * system. - * - * ```ts title="sst.config.ts" - * const server = new sst.aws.Service("MyService", { - * cluster, - * architecture: "arm64", - * image: "surrealdb/surrealdb:v2.0.2", - * // ... - * volumes: [ - * { efs, path: "/data" }, - * ], - * }); - * ``` - * - * We then connect to the server from a Lambda function. - * - * ```js title="index.ts" - * const endpoint = `http://${Resource.MyConfig.host}:${Resource.MyConfig.port}`; - * - * const db = new Surreal(); - * await db.connect(endpoint); - * ``` - * - * This uses the SurrealDB client to connect to the server. - * - * :::note - * Given the performance of EFS, it's not recommended to use it for databases. - * ::: - * - * This example is for demonstration purposes only. It's not recommended to use - * EFS for databases in production. - */ -export default $config({ - app(input) { - return { - name: "aws-efs-surrealdb", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { "@pulumi/random": "4.16.7" }, - }; - }, - async run() { - const { RandomPassword } = await import("@pulumi/random"); - - // SurrealDB Credentials - const PORT = 8080; - const NAMESPACE = "test"; - const DATABASE = "test"; - const USERNAME = "root"; - const PASSWORD = new RandomPassword("Password", { - length: 32, - }).result; - - // NAT Gateways are required for Lambda functions - const vpc = new sst.aws.Vpc("MyVpc", { nat: "managed" }); - - // Store SurrealDB data in EFS - const efs = new sst.aws.Efs("MyEfs", { vpc }); - - // Run SurrealDB server in a container - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - const server = new sst.aws.Service("MyService", { - cluster, - architecture: "arm64", - image: "surrealdb/surrealdb:v2.0.2", - command: [ - "start", - "--bind", - $interpolate`0.0.0.0:${PORT}`, - "--log", - "info", - "--user", - USERNAME, - "--pass", - PASSWORD, - "surrealkv://data/data.skv", - "--allow-scripting", - ], - volumes: [{ efs, path: "/data" }], - }); - - // Lambda client to connect to SurrealDB - const config = new sst.Linkable("MyConfig", { - properties: { - username: USERNAME, - password: PASSWORD, - namespace: NAMESPACE, - database: DATABASE, - port: PORT, - host: server.service, - }, - }); - - new sst.aws.Function("MyApp", { - handler: "index.handler", - link: [config], - url: true, - vpc, - }); - }, -}); diff --git a/examples/aws-efs-surrealdb/tsconfig.json b/examples/aws-efs-surrealdb/tsconfig.json deleted file mode 100644 index 9e26dfeeb6..0000000000 --- a/examples/aws-efs-surrealdb/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/examples/aws-efs/.dockerignore b/examples/aws-efs/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-efs/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-efs/Dockerfile b/examples/aws-efs/Dockerfile deleted file mode 100644 index fdf9535d4a..0000000000 --- a/examples/aws-efs/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY service.mjs /app -COPY common.mjs /app - -ENTRYPOINT ["node", "service.mjs"] \ No newline at end of file diff --git a/examples/aws-efs/common.mjs b/examples/aws-efs/common.mjs deleted file mode 100644 index 3edae33c5e..0000000000 --- a/examples/aws-efs/common.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { readFile, writeFile } from "fs/promises"; - -export async function increment() { - // read the counter file from EFS - let oldValue = 0; - try { - oldValue = parseInt(await readFile("/mnt/efs/counter", "utf8")); - oldValue = isNaN(oldValue) ? 0 : oldValue; - } catch (e) { - // file doesn't exist - } - - // increment the counter - const newValue = oldValue + 1; - - // write the counter file to EFS - await writeFile("/mnt/efs/counter", newValue.toString()); - - return newValue; -} diff --git a/examples/aws-efs/lambda.ts b/examples/aws-efs/lambda.ts deleted file mode 100644 index a77e93aa24..0000000000 --- a/examples/aws-efs/lambda.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { increment } from "./common.mjs"; - -export const handler = async () => { - const counter = await increment(); - console.log("COUNTER", counter); - return { - statusCode: 200, - body: JSON.stringify({ - counter, - }), - }; -}; diff --git a/examples/aws-efs/package.json b/examples/aws-efs/package.json deleted file mode 100644 index 50dfa020a3..0000000000 --- a/examples/aws-efs/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "aws-efs", - "version": "1.0.0", - "description": "", - "main": "index.js", - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "express": "^4.19.2" - } -} diff --git a/examples/aws-efs/service.mjs b/examples/aws-efs/service.mjs deleted file mode 100644 index 6f8866d20d..0000000000 --- a/examples/aws-efs/service.mjs +++ /dev/null @@ -1,18 +0,0 @@ -import express from "express"; -import { increment } from "./common.mjs"; - -const PORT = 80; - -const app = express(); - -app.get("/", async (req, res) => { - res.send( - JSON.stringify({ - counter: await increment(), - }) - ); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-efs/sst.config.ts b/examples/aws-efs/sst.config.ts deleted file mode 100644 index 352852780e..0000000000 --- a/examples/aws-efs/sst.config.ts +++ /dev/null @@ -1,58 +0,0 @@ -/// - -/** - * ## AWS EFS - * - * Mount an EFS file system to a function and a container. - * - * This allows both your function and the container to access the same file system. Here they - * both update a counter that's stored in the file system. - * - * ```js title="common.mjs" - * await writeFile("/mnt/efs/counter", newValue.toString()); - * ``` - * - * The file system is mounted to `/mnt/efs` in both the function and the container. - */ -export default $config({ - app(input) { - return { - name: "aws-efs", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // NAT Gateways are required for Lambda functions - const vpc = new sst.aws.Vpc("MyVpc", { nat: "managed" }); - - // Create an EFS file system to store a counter - const efs = new sst.aws.Efs("MyEfs", { vpc }); - - // Create a Lambda function that increments the counter - new sst.aws.Function("MyFunction", { - handler: "lambda.handler", - url: true, - vpc, - volume: { - efs, - path: "/mnt/efs", - }, - }); - - // Create a service that increments the same counter - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http" }], - }, - volumes: [ - { - efs, - path: "/mnt/efs", - }, - ], - }); - }, -}); diff --git a/examples/aws-email/package.json b/examples/aws-email/package.json deleted file mode 100644 index c24cf0273c..0000000000 --- a/examples/aws-email/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-email", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-sesv2": "^3.515.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.142" - } -} diff --git a/examples/aws-email/sender.ts b/examples/aws-email/sender.ts deleted file mode 100644 index a1c2827b1c..0000000000 --- a/examples/aws-email/sender.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Resource } from "sst"; -import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2"; - -const client = new SESv2Client(); - -export const handler = async () => { - await client.send( - new SendEmailCommand({ - FromEmailAddress: Resource.MyEmail.sender, - Destination: { - ToAddresses: [Resource.MyEmail.sender], - }, - Content: { - Simple: { - Subject: { - Data: "Hello World!", - }, - Body: { - Text: { - Data: "Sent from my SST app.", - }, - }, - }, - }, - }) - ); - - return { - statusCode: 200, - body: "Sent!" - }; -}; diff --git a/examples/aws-email/sst.config.ts b/examples/aws-email/sst.config.ts deleted file mode 100644 index bd9602537a..0000000000 --- a/examples/aws-email/sst.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-email", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const email = new sst.aws.Email("MyEmail", { - sender: "email@example.com", - }); - - const api = new sst.aws.Function("MyApi", { - handler: "sender.handler", - link: [email], - url: true, - }); - - return { - url: api.url, - }; - }, -}); diff --git a/examples/aws-email/tsconfig.json b/examples/aws-email/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-email/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-express-redis/.dockerignore b/examples/aws-express-redis/.dockerignore deleted file mode 100644 index ea0aaeeec9..0000000000 --- a/examples/aws-express-redis/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-express-redis/.gitignore b/examples/aws-express-redis/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-express-redis/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-express-redis/Dockerfile b/examples/aws-express-redis/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-express-redis/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-express-redis/index.mjs b/examples/aws-express-redis/index.mjs deleted file mode 100644 index a951c70253..0000000000 --- a/examples/aws-express-redis/index.mjs +++ /dev/null @@ -1,28 +0,0 @@ -import express from "express"; -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const PORT = 80; - -const app = express(); - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -app.get("/", async (req, res) => { - const counter = await redis.incr("counter"); - res.send(`Hit counter: ${counter}`); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-express-redis/package.json b/examples/aws-express-redis/package.json deleted file mode 100644 index 376035cecd..0000000000 --- a/examples/aws-express-redis/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-express-redis", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "express": "^4.21.0", - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-express-redis/sst.config.ts b/examples/aws-express-redis/sst.config.ts deleted file mode 100644 index edf565f96c..0000000000 --- a/examples/aws-express-redis/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## AWS Express Redis - * - * Creates a hit counter app with Express and Redis. - * - * This deploys Express as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {9} - * new sst.aws.Service("MyService", { - * cluster, - * loadBalancer: { - * ports: [{ listen: "80/http" }], - * }, - * dev: { - * command: "node --watch index.mjs", - * }, - * link: [redis], - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:80` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it using `npx sst deploy --stage production` using a `Dockerfile` - * that's included in the example. - */ -export default $config({ - app(input) { - return { - name: "aws-express-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http" }], - }, - dev: { - command: "node --watch index.mjs", - }, - }); - }, -}); diff --git a/examples/aws-express-redis/tsconfig.json b/examples/aws-express-redis/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-express-redis/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-express/.dockerignore b/examples/aws-express/.dockerignore deleted file mode 100644 index ea0aaeeec9..0000000000 --- a/examples/aws-express/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-express/.gitignore b/examples/aws-express/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-express/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-express/Dockerfile b/examples/aws-express/Dockerfile deleted file mode 100644 index 1d16aa3311..0000000000 --- a/examples/aws-express/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:lts-alpine - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-express/index.mjs b/examples/aws-express/index.mjs deleted file mode 100644 index 507250ec18..0000000000 --- a/examples/aws-express/index.mjs +++ /dev/null @@ -1,63 +0,0 @@ -import multer from "multer"; -import express from "express"; -import { Resource } from "sst"; -import { Upload } from "@aws-sdk/lib-storage"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { - S3Client, - GetObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; - -const PORT = 80; - -const app = express(); -const s3 = new S3Client({}); -const upload = multer({ storage: multer.memoryStorage() }); - -app.get("/", (req, res) => { - res.send("Hello World!") -}); - -app.post("/", upload.single("file"), async (req, res) => { - const file = req.file; - const params = { - Bucket: Resource.MyBucket.name, - ContentType: file.mimetype, - Key: file.originalname, - Body: file.buffer, - }; - - const upload = new Upload({ - params, - client: s3, - }); - - await upload.done(); - - res.status(200).send("File uploaded successfully."); -}); - -app.get("/latest", async (req, res) => { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - - const latestFile = objects.Contents.sort( - (a, b) => b.LastModified - a.LastModified, - )[0]; - - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(s3, command); - - res.redirect(url); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-express/package.json b/examples/aws-express/package.json deleted file mode 100644 index ad4e1fbccb..0000000000 --- a/examples/aws-express/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "aws-express", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-s3": "^3.705.0", - "@aws-sdk/lib-storage": "^3.705.0", - "@aws-sdk/s3-request-presigner": "^3.705.0", - "express": "^4.21.1", - "multer": "^1.4.5-lts.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.146" - } -} diff --git a/examples/aws-express/sst.config.ts b/examples/aws-express/sst.config.ts deleted file mode 100644 index 1dd9704d68..0000000000 --- a/examples/aws-express/sst.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-express", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: "80/http" }], - }, - dev: { - command: "node --watch index.mjs", - }, - }); - }, -}); diff --git a/examples/aws-express/tsconfig.json b/examples/aws-express/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-express/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-fastapi/.gitignore b/examples/aws-fastapi/.gitignore deleted file mode 100644 index 17ace783f5..0000000000 --- a/examples/aws-fastapi/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.sst -.venv \ No newline at end of file diff --git a/examples/aws-fastapi/core/pyproject.toml b/examples/aws-fastapi/core/pyproject.toml deleted file mode 100644 index 4d9ed5884e..0000000000 --- a/examples/aws-fastapi/core/pyproject.toml +++ /dev/null @@ -1,11 +0,0 @@ -[project] -name = "core" -version = "0.1.0" -description = "Add your description here" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -requires-python = "==3.11.*" -dependencies = ["requests>=2.32.3"] - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" diff --git a/examples/aws-fastapi/core/src/core/__init__.py b/examples/aws-fastapi/core/src/core/__init__.py deleted file mode 100644 index 437615c6c1..0000000000 --- a/examples/aws-fastapi/core/src/core/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from core.db import get_user - - -def hello() -> str: - return "Hello from core!" - - -__all__ = ["get_user", "hello"] diff --git a/examples/aws-fastapi/core/src/core/db.py b/examples/aws-fastapi/core/src/core/db.py deleted file mode 100644 index c719b87ba4..0000000000 --- a/examples/aws-fastapi/core/src/core/db.py +++ /dev/null @@ -1,5 +0,0 @@ -def get_user(user_id: str) -> dict: - return { - "user_id": user_id, - "name": "John Doe", - } diff --git a/examples/aws-fastapi/core/src/core/ping.py b/examples/aws-fastapi/core/src/core/ping.py deleted file mode 100644 index c13cfd5726..0000000000 --- a/examples/aws-fastapi/core/src/core/ping.py +++ /dev/null @@ -1,5 +0,0 @@ -import requests - - -def ping(): - return requests.get("https://api.github.com").status_code diff --git a/examples/aws-fastapi/functions/pyproject.toml b/examples/aws-fastapi/functions/pyproject.toml deleted file mode 100644 index ac5a78c4b8..0000000000 --- a/examples/aws-fastapi/functions/pyproject.toml +++ /dev/null @@ -1,14 +0,0 @@ -[project] -name = "functions" -version = "0.1.0" -description = "Lambda function handlers" -dependencies = ["core", "sst-sdk", "fastapi==0.115.8", "mangum==0.19.0"] -requires-python = "==3.11.*" - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[tool.uv.sources] -core = { workspace = true } -sst-sdk = { git = "https://github.com/anomalyco/sst.git", branch = "dev", subdirectory = "sdk/python" } diff --git a/examples/aws-fastapi/functions/src/functions/api.py b/examples/aws-fastapi/functions/src/functions/api.py deleted file mode 100644 index 56fb5c8fe7..0000000000 --- a/examples/aws-fastapi/functions/src/functions/api.py +++ /dev/null @@ -1,39 +0,0 @@ -from fastapi import FastAPI -from mangum import Mangum -from sst import Resource -from functions.shared import foo -from core.db import get_user -from core.ping import ping - -# Create FastAPI app with JSON configuration -app = FastAPI( - title="SST FastAPI App", - json_encoder=None # Use FastAPI's default JSON encoder -) - -# Create a route -@app.get("/") -async def root(): - print("Function invoked from Python") - - # Share code within the same workspace package - result = foo() - print(result) - - # Share code between workspace packages - res = ping() - user = get_user("1234") - print(user) - print("Ping result:", res) - - # Use the SST SDK to access resources - resource_value = Resource.MyLinkableValue.foo - print(f"Resource.MyLinkableValue.foo: {resource_value}") - - return { - "message": f"{resource_value} from Python!", - - } - -# Create handler for AWS Lambda with specific configuration -handler = Mangum(app, api_gateway_base_path=None, lifespan="off") diff --git a/examples/aws-fastapi/functions/src/functions/shared.py b/examples/aws-fastapi/functions/src/functions/shared.py deleted file mode 100644 index 1f022956c6..0000000000 --- a/examples/aws-fastapi/functions/src/functions/shared.py +++ /dev/null @@ -1,2 +0,0 @@ -def foo(): - return "bar" diff --git a/examples/aws-fastapi/package.json b/examples/aws-fastapi/package.json deleted file mode 100644 index ff07a387c7..0000000000 --- a/examples/aws-fastapi/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-fastapi", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-fastapi/pyproject.toml b/examples/aws-fastapi/pyproject.toml deleted file mode 100644 index c7a1678eeb..0000000000 --- a/examples/aws-fastapi/pyproject.toml +++ /dev/null @@ -1,16 +0,0 @@ -[project] -name = "aws-fastapi" -version = "0.1.0" -description = "A SST app" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -dependencies = [] - -# It is recommended to specify your python version to match your Lambda runtime otherwise you may -# encounter issues with dependencies. -requires-python = "==3.11.*" - -[tool.uv.workspace] -members = ["functions", "core"] - -[tool.uv.sources] -sst-sdk = { git = "https://github.com/anomalyco/sst.git", subdirectory = "sdk/python", branch = "dev" } diff --git a/examples/aws-fastapi/sst.config.ts b/examples/aws-fastapi/sst.config.ts deleted file mode 100644 index 4624a75bff..0000000000 --- a/examples/aws-fastapi/sst.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -/// - -/** - * ## FastAPI - * - * Deploy a Python FastAPI app as a Lambda function with a linked value. - */ -export default $config({ - app(input) { - return { - name: "aws-fastapi", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - aws: true, - }, - }; - }, - async run() { - const linkableValue = new sst.Linkable("MyLinkableValue", { - properties: { - foo: "Hello World", - }, - }); - - const fastapi = new sst.aws.Function("FastAPI", { - handler: "functions/src/functions/api.handler", - runtime: "python3.11", - url: true, - link: [linkableValue], - }); - - return { - fastapi: fastapi.url, - }; - }, -}); diff --git a/examples/aws-fastapi/tsconfig.json b/examples/aws-fastapi/tsconfig.json deleted file mode 100644 index 9e26dfeeb6..0000000000 --- a/examples/aws-fastapi/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/examples/aws-ffmpeg/.gitignore b/examples/aws-ffmpeg/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-ffmpeg/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-ffmpeg/clip.mp4 b/examples/aws-ffmpeg/clip.mp4 deleted file mode 100644 index 9efdbf0110..0000000000 Binary files a/examples/aws-ffmpeg/clip.mp4 and /dev/null differ diff --git a/examples/aws-ffmpeg/index.ts b/examples/aws-ffmpeg/index.ts deleted file mode 100644 index f0be094605..0000000000 --- a/examples/aws-ffmpeg/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -import path from "path"; -import ffmpeg from "ffmpeg-static"; -import { promises as fs } from "fs"; -import { spawnSync } from "child_process"; - -export async function handler() { - const videoPath = "clip.mp4"; - - const outputFile = "thumbnail.jpg"; - const outputPath = process.env.SST_DEV - ? outputFile - : path.join("/tmp", outputFile); - - const ffmpegParams = [ - "-ss", - "1", - "-i", - videoPath, - "-vf", - "thumbnail,scale=960:540", - "-vframes", - "1", - outputPath, - ]; - - spawnSync(ffmpeg, ffmpegParams, { stdio: "pipe" }); - - const img = await fs.readFile(outputPath); - const body = Buffer.from(img).toString("base64"); - - return { - body, - statusCode: 200, - isBase64Encoded: true, - headers: { - "Content-Type": "image/jpeg", - "Content-Disposition": "inline", - }, - }; -} diff --git a/examples/aws-ffmpeg/package.json b/examples/aws-ffmpeg/package.json deleted file mode 100644 index 4bee839366..0000000000 --- a/examples/aws-ffmpeg/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-ffmpeg", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "ffmpeg-static": "^5.2.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-ffmpeg/sst.config.ts b/examples/aws-ffmpeg/sst.config.ts deleted file mode 100644 index 01e1a3b46c..0000000000 --- a/examples/aws-ffmpeg/sst.config.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// - -/** - * ## FFmpeg in Lambda - * - * Uses [FFmpeg](https://ffmpeg.org/) to process videos. In this example, it takes a `clip.mp4` - * and grabs a single frame from it. - * - * :::tip - * You don't need to use a Lambda layer to use FFmpeg. - * ::: - * - * We use the [`ffmpeg-static`](https://www.npmjs.com/package/ffmpeg-static) package that - * contains pre-built binaries for all architectures. - * - * ```ts title="index.ts" - * import ffmpeg from "ffmpeg-static"; - * ``` - * - * We can use this to spawn a child process and run FFmpeg. - * - * ```ts title="index.ts" - * spawnSync(ffmpeg, ffmpegParams, { stdio: "pipe" }); - * ``` - * - * We don't need a layer when we deploy this because SST will use the right binary for the - * target Lambda architecture; including `arm64`. - * - * ```json title="sst.config.ts" - * { - * nodejs: { install: ["ffmpeg-static"] } - * } - * ``` - * - * All this is handled by [`nodejs.install`](/docs/component/aws/function#nodejs-install). - */ -export default $config({ - app(input) { - return { - name: "aws-ffmpeg", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const func = new sst.aws.Function("MyFunction", { - url: true, - memory: "2 GB", - timeout: "15 minutes", - handler: "index.handler", - copyFiles: [{ from: "clip.mp4" }], - nodejs: { install: ["ffmpeg-static"] }, - }); - - return { - url: func.url, - }; - }, -}); diff --git a/examples/aws-ffmpeg/tsconfig.json b/examples/aws-ffmpeg/tsconfig.json deleted file mode 100644 index 2f98042715..0000000000 --- a/examples/aws-ffmpeg/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "esModuleInterop": true - } -} diff --git a/examples/aws-flutter-web/.gitignore b/examples/aws-flutter-web/.gitignore deleted file mode 100644 index 41160e58d7..0000000000 --- a/examples/aws-flutter-web/.gitignore +++ /dev/null @@ -1,46 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -**/ios/Flutter/.last_build_id -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.pub-cache/ -.pub/ -/build/ - -# Symbolication related -app.*.symbols - -# Obfuscation related -app.*.map.json - -# Android Studio will place build artifacts here -/android/app/debug -/android/app/profile -/android/app/release - -# sst -.sst diff --git a/examples/aws-flutter-web/.metadata b/examples/aws-flutter-web/.metadata deleted file mode 100644 index cbf1dc0e0d..0000000000 --- a/examples/aws-flutter-web/.metadata +++ /dev/null @@ -1,45 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: "a14f74ff3a1cbd521163c5f03d68113d50af93d3" - channel: "stable" - -project_type: app - -# Tracks metadata for the flutter migrate command -migration: - platforms: - - platform: root - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - platform: android - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - platform: ios - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - platform: linux - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - platform: macos - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - platform: web - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - platform: windows - create_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - base_revision: a14f74ff3a1cbd521163c5f03d68113d50af93d3 - - # User provided section - - # List of Local paths (relative to this file) that should be - # ignored by the migrate tool. - # - # Files that are not part of the templates will be ignored by default. - unmanaged_files: - - 'lib/main.dart' - - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/examples/aws-flutter-web/analysis_options.yaml b/examples/aws-flutter-web/analysis_options.yaml deleted file mode 100644 index 0d2902135c..0000000000 --- a/examples/aws-flutter-web/analysis_options.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at https://dart.dev/lints. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/examples/aws-flutter-web/android/app/build.gradle b/examples/aws-flutter-web/android/app/build.gradle deleted file mode 100644 index b68da4a58e..0000000000 --- a/examples/aws-flutter-web/android/app/build.gradle +++ /dev/null @@ -1,58 +0,0 @@ -plugins { - id "com.android.application" - id "kotlin-android" - // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. - id "dev.flutter.flutter-gradle-plugin" -} - -def localProperties = new Properties() -def localPropertiesFile = rootProject.file("local.properties") -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader("UTF-8") { reader -> - localProperties.load(reader) - } -} - -def flutterVersionCode = localProperties.getProperty("flutter.versionCode") -if (flutterVersionCode == null) { - flutterVersionCode = "1" -} - -def flutterVersionName = localProperties.getProperty("flutter.versionName") -if (flutterVersionName == null) { - flutterVersionName = "1.0" -} - -android { - namespace = "com.example.aws_flutter_web" - compileSdk = flutter.compileSdkVersion - ndkVersion = flutter.ndkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId = "com.example.aws_flutter_web" - // You can update the following values to match your application needs. - // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. - minSdk = flutter.minSdkVersion - targetSdk = flutter.targetSdkVersion - versionCode = flutterVersionCode.toInteger() - versionName = flutterVersionName - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.debug - } - } -} - -flutter { - source = "../.." -} diff --git a/examples/aws-flutter-web/android/app/src/debug/AndroidManifest.xml b/examples/aws-flutter-web/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index 399f6981d5..0000000000 --- a/examples/aws-flutter-web/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/examples/aws-flutter-web/android/app/src/main/AndroidManifest.xml b/examples/aws-flutter-web/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index 6a5ac6fe10..0000000000 --- a/examples/aws-flutter-web/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/aws-flutter-web/android/app/src/main/kotlin/com/example/aws_flutter_web/MainActivity.kt b/examples/aws-flutter-web/android/app/src/main/kotlin/com/example/aws_flutter_web/MainActivity.kt deleted file mode 100644 index c85c87a074..0000000000 --- a/examples/aws-flutter-web/android/app/src/main/kotlin/com/example/aws_flutter_web/MainActivity.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.example.aws_flutter_web - -import io.flutter.embedding.android.FlutterActivity - -class MainActivity: FlutterActivity() diff --git a/examples/aws-flutter-web/android/app/src/main/res/values-night/styles.xml b/examples/aws-flutter-web/android/app/src/main/res/values-night/styles.xml deleted file mode 100644 index 06952be745..0000000000 --- a/examples/aws-flutter-web/android/app/src/main/res/values-night/styles.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - diff --git a/examples/aws-flutter-web/android/app/src/main/res/values/styles.xml b/examples/aws-flutter-web/android/app/src/main/res/values/styles.xml deleted file mode 100644 index cb1ef88056..0000000000 --- a/examples/aws-flutter-web/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - diff --git a/examples/aws-flutter-web/android/app/src/profile/AndroidManifest.xml b/examples/aws-flutter-web/android/app/src/profile/AndroidManifest.xml deleted file mode 100644 index 399f6981d5..0000000000 --- a/examples/aws-flutter-web/android/app/src/profile/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/examples/aws-flutter-web/android/build.gradle b/examples/aws-flutter-web/android/build.gradle deleted file mode 100644 index d2ffbffa4c..0000000000 --- a/examples/aws-flutter-web/android/build.gradle +++ /dev/null @@ -1,18 +0,0 @@ -allprojects { - repositories { - google() - mavenCentral() - } -} - -rootProject.buildDir = "../build" -subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(":app") -} - -tasks.register("clean", Delete) { - delete rootProject.buildDir -} diff --git a/examples/aws-flutter-web/android/gradle.properties b/examples/aws-flutter-web/android/gradle.properties deleted file mode 100644 index 3b5b324f6e..0000000000 --- a/examples/aws-flutter-web/android/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -org.gradle.jvmargs=-Xmx4G -XX:+HeapDumpOnOutOfMemoryError -android.useAndroidX=true -android.enableJetifier=true diff --git a/examples/aws-flutter-web/android/settings.gradle b/examples/aws-flutter-web/android/settings.gradle deleted file mode 100644 index 536165d35a..0000000000 --- a/examples/aws-flutter-web/android/settings.gradle +++ /dev/null @@ -1,25 +0,0 @@ -pluginManagement { - def flutterSdkPath = { - def properties = new Properties() - file("local.properties").withInputStream { properties.load(it) } - def flutterSdkPath = properties.getProperty("flutter.sdk") - assert flutterSdkPath != null, "flutter.sdk not set in local.properties" - return flutterSdkPath - }() - - includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") - - repositories { - google() - mavenCentral() - gradlePluginPortal() - } -} - -plugins { - id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "7.3.0" apply false - id "org.jetbrains.kotlin.android" version "1.7.10" apply false -} - -include ":app" diff --git a/examples/aws-flutter-web/ios/.gitignore b/examples/aws-flutter-web/ios/.gitignore deleted file mode 100644 index 7a7f9873ad..0000000000 --- a/examples/aws-flutter-web/ios/.gitignore +++ /dev/null @@ -1,34 +0,0 @@ -**/dgph -*.mode1v3 -*.mode2v3 -*.moved-aside -*.pbxuser -*.perspectivev3 -**/*sync/ -.sconsign.dblite -.tags* -**/.vagrant/ -**/DerivedData/ -Icon? -**/Pods/ -**/.symlinks/ -profile -xcuserdata -**/.generated/ -Flutter/App.framework -Flutter/Flutter.framework -Flutter/Flutter.podspec -Flutter/Generated.xcconfig -Flutter/ephemeral/ -Flutter/app.flx -Flutter/app.zip -Flutter/flutter_assets/ -Flutter/flutter_export_environment.sh -ServiceDefinitions.json -Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!default.mode1v3 -!default.mode2v3 -!default.pbxuser -!default.perspectivev3 diff --git a/examples/aws-flutter-web/ios/Runner.xcodeproj/project.pbxproj b/examples/aws-flutter-web/ios/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index 332b360542..0000000000 --- a/examples/aws-flutter-web/ios/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,616 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXBuildFile section */ - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 97C146E61CF9000F007C117D /* Project object */; - proxyType = 1; - remoteGlobalIDString = 97C146ED1CF9000F007C117D; - remoteInfo = Runner; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 9705A1C41CF9048500538489 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; - 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; - 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 97C146EB1CF9000F007C117D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 331C8082294A63A400263BE5 /* RunnerTests */ = { - isa = PBXGroup; - children = ( - 331C807B294A618700263BE5 /* RunnerTests.swift */, - ); - path = RunnerTests; - sourceTree = ""; - }; - 9740EEB11CF90186004384FC /* Flutter */ = { - isa = PBXGroup; - children = ( - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 9740EEB31CF90195004384FC /* Generated.xcconfig */, - ); - name = Flutter; - sourceTree = ""; - }; - 97C146E51CF9000F007C117D = { - isa = PBXGroup; - children = ( - 9740EEB11CF90186004384FC /* Flutter */, - 97C146F01CF9000F007C117D /* Runner */, - 97C146EF1CF9000F007C117D /* Products */, - 331C8082294A63A400263BE5 /* RunnerTests */, - ); - sourceTree = ""; - }; - 97C146EF1CF9000F007C117D /* Products */ = { - isa = PBXGroup; - children = ( - 97C146EE1CF9000F007C117D /* Runner.app */, - 331C8081294A63A400263BE5 /* RunnerTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 97C146F01CF9000F007C117D /* Runner */ = { - isa = PBXGroup; - children = ( - 97C146FA1CF9000F007C117D /* Main.storyboard */, - 97C146FD1CF9000F007C117D /* Assets.xcassets */, - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, - 97C147021CF9000F007C117D /* Info.plist */, - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, - ); - path = Runner; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 331C8080294A63A400263BE5 /* RunnerTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; - buildPhases = ( - 331C807D294A63A400263BE5 /* Sources */, - 331C807F294A63A400263BE5 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 331C8086294A63A400263BE5 /* PBXTargetDependency */, - ); - name = RunnerTests; - productName = RunnerTests; - productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 97C146ED1CF9000F007C117D /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 9740EEB61CF901F6004384FC /* Run Script */, - 97C146EA1CF9000F007C117D /* Sources */, - 97C146EB1CF9000F007C117D /* Frameworks */, - 97C146EC1CF9000F007C117D /* Resources */, - 9705A1C41CF9048500538489 /* Embed Frameworks */, - 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Runner; - productName = Runner; - productReference = 97C146EE1CF9000F007C117D /* Runner.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 97C146E61CF9000F007C117D /* Project object */ = { - isa = PBXProject; - attributes = { - BuildIndependentTargetsInParallel = YES; - LastUpgradeCheck = 1510; - ORGANIZATIONNAME = ""; - TargetAttributes = { - 331C8080294A63A400263BE5 = { - CreatedOnToolsVersion = 14.0; - TestTargetID = 97C146ED1CF9000F007C117D; - }; - 97C146ED1CF9000F007C117D = { - CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 1100; - }; - }; - }; - buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 97C146E51CF9000F007C117D; - productRefGroup = 97C146EF1CF9000F007C117D /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 97C146ED1CF9000F007C117D /* Runner */, - 331C8080294A63A400263BE5 /* RunnerTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 331C807F294A63A400263BE5 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 97C146EC1CF9000F007C117D /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", - ); - name = "Thin Binary"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; - }; - 9740EEB61CF901F6004384FC /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 331C807D294A63A400263BE5 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 97C146EA1CF9000F007C117D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 97C146ED1CF9000F007C117D /* Runner */; - targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 97C146FA1CF9000F007C117D /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C146FB1CF9000F007C117D /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C147001CF9000F007C117D /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 249021D3217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SUPPORTED_PLATFORMS = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Profile; - }; - 249021D4217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - ENABLE_BITCODE = NO; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Profile; - }; - 331C8088294A63A400263BE5 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; - }; - name = Debug; - }; - 331C8089294A63A400263BE5 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; - }; - name = Release; - }; - 331C808A294A63A400263BE5 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; - }; - name = Profile; - }; - 97C147031CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 97C147041CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SUPPORTED_PLATFORMS = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 97C147061CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - ENABLE_BITCODE = NO; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Debug; - }; - 97C147071CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - ENABLE_BITCODE = NO; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 331C8088294A63A400263BE5 /* Debug */, - 331C8089294A63A400263BE5 /* Release */, - 331C808A294A63A400263BE5 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147031CF9000F007C117D /* Debug */, - 97C147041CF9000F007C117D /* Release */, - 249021D3217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147061CF9000F007C117D /* Debug */, - 97C147071CF9000F007C117D /* Release */, - 249021D4217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 97C146E61CF9000F007C117D /* Project object */; -} diff --git a/examples/aws-flutter-web/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/aws-flutter-web/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index 8e3ca5dfe1..0000000000 --- a/examples/aws-flutter-web/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d36b1fab2d..0000000000 --- a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png deleted file mode 100644 index 7353c41ecf..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png deleted file mode 100644 index 797d452e45..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png deleted file mode 100644 index 6ed2d933e1..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png deleted file mode 100644 index 4cd7b0099c..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png deleted file mode 100644 index fe730945a0..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png deleted file mode 100644 index 321773cd85..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png deleted file mode 100644 index 797d452e45..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png deleted file mode 100644 index 502f463a9b..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png deleted file mode 100644 index 0ec3034392..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png deleted file mode 100644 index 0ec3034392..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png deleted file mode 100644 index e9f5fea27c..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png deleted file mode 100644 index 84ac32ae7d..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png deleted file mode 100644 index 8953cba090..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png deleted file mode 100644 index 0467bf12aa..0000000000 Binary files a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and /dev/null differ diff --git a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/examples/aws-flutter-web/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json deleted file mode 100644 index 0bedcf2fd4..0000000000 --- a/examples/aws-flutter-web/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "LaunchImage.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/examples/aws-flutter-web/ios/RunnerTests/RunnerTests.swift b/examples/aws-flutter-web/ios/RunnerTests/RunnerTests.swift deleted file mode 100644 index 86a7c3b1b6..0000000000 --- a/examples/aws-flutter-web/ios/RunnerTests/RunnerTests.swift +++ /dev/null @@ -1,12 +0,0 @@ -import Flutter -import UIKit -import XCTest - -class RunnerTests: XCTestCase { - - func testExample() { - // If you add code to the Runner application, consider adding tests here. - // See https://developer.apple.com/documentation/xctest for more information about using XCTest. - } - -} diff --git a/examples/aws-flutter-web/lib/main.dart b/examples/aws-flutter-web/lib/main.dart deleted file mode 100644 index 8e94089121..0000000000 --- a/examples/aws-flutter-web/lib/main.dart +++ /dev/null @@ -1,125 +0,0 @@ -import 'package:flutter/material.dart'; - -void main() { - runApp(const MyApp()); -} - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - // This widget is the root of your application. - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'Flutter Demo', - theme: ThemeData( - // This is the theme of your application. - // - // TRY THIS: Try running your application with "flutter run". You'll see - // the application has a purple toolbar. Then, without quitting the app, - // try changing the seedColor in the colorScheme below to Colors.green - // and then invoke "hot reload" (save your changes or press the "hot - // reload" button in a Flutter-supported IDE, or press "r" if you used - // the command line to start the app). - // - // Notice that the counter didn't reset back to zero; the application - // state is not lost during the reload. To reset the state, use hot - // restart instead. - // - // This works for code too, not just values: Most code changes can be - // tested with just a hot reload. - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const MyHomePage(title: 'Flutter Demo Home Page'), - ); - } -} - -class MyHomePage extends StatefulWidget { - const MyHomePage({super.key, required this.title}); - - // This widget is the home page of your application. It is stateful, meaning - // that it has a State object (defined below) that contains fields that affect - // how it looks. - - // This class is the configuration for the state. It holds the values (in this - // case the title) provided by the parent (in this case the App widget) and - // used by the build method of the State. Fields in a Widget subclass are - // always marked "final". - - final String title; - - @override - State createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State { - int _counter = 0; - - void _incrementCounter() { - setState(() { - // This call to setState tells the Flutter framework that something has - // changed in this State, which causes it to rerun the build method below - // so that the display can reflect the updated values. If we changed - // _counter without calling setState(), then the build method would not be - // called again, and so nothing would appear to happen. - _counter++; - }); - } - - @override - Widget build(BuildContext context) { - // This method is rerun every time setState is called, for instance as done - // by the _incrementCounter method above. - // - // The Flutter framework has been optimized to make rerunning build methods - // fast, so that you can just rebuild anything that needs updating rather - // than having to individually change instances of widgets. - return Scaffold( - appBar: AppBar( - // TRY THIS: Try changing the color here to a specific color (to - // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar - // change color while the other colors stay the same. - backgroundColor: Theme.of(context).colorScheme.inversePrimary, - // Here we take the value from the MyHomePage object that was created by - // the App.build method, and use it to set our appbar title. - title: Text(widget.title), - ), - body: Center( - // Center is a layout widget. It takes a single child and positions it - // in the middle of the parent. - child: Column( - // Column is also a layout widget. It takes a list of children and - // arranges them vertically. By default, it sizes itself to fit its - // children horizontally, and tries to be as tall as its parent. - // - // Column has various properties to control how it sizes itself and - // how it positions its children. Here we use mainAxisAlignment to - // center the children vertically; the main axis here is the vertical - // axis because Columns are vertical (the cross axis would be - // horizontal). - // - // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" - // action in the IDE, or press "p" in the console), to see the - // wireframe for each widget. - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text( - 'You have pushed the button this many times:', - ), - Text( - '$_counter', - style: Theme.of(context).textTheme.headlineMedium, - ), - ], - ), - ), - floatingActionButton: FloatingActionButton( - onPressed: _incrementCounter, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), // This trailing comma makes auto-formatting nicer for build methods. - ); - } -} diff --git a/examples/aws-flutter-web/linux/.gitignore b/examples/aws-flutter-web/linux/.gitignore deleted file mode 100644 index d3896c9844..0000000000 --- a/examples/aws-flutter-web/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/examples/aws-flutter-web/linux/CMakeLists.txt b/examples/aws-flutter-web/linux/CMakeLists.txt deleted file mode 100644 index a147894dec..0000000000 --- a/examples/aws-flutter-web/linux/CMakeLists.txt +++ /dev/null @@ -1,145 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "aws_flutter_web") -# The unique GTK application identifier for this application. See: -# https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "com.example.aws_flutter_web") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Load bundled libraries from the lib/ directory relative to the binary. -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Root filesystem for cross-building. -if(FLUTTER_TARGET_PLATFORM_SYSROOT) - set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endif() - -# Define build configuration options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Define the application target. To change its name, change BINARY_NAME above, -# not the value here, or `flutter run` will no longer work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add dependency libraries. Add any application-specific dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) - -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) - install(FILES "${bundled_library}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endforeach(bundled_library) - -# Copy the native assets provided by the build.dart from all packages. -set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") -install(DIRECTORY "${NATIVE_ASSETS_DIR}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/examples/aws-flutter-web/linux/flutter/CMakeLists.txt b/examples/aws-flutter-web/linux/flutter/CMakeLists.txt deleted file mode 100644 index d5bd01648a..0000000000 --- a/examples/aws-flutter-web/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/examples/aws-flutter-web/linux/flutter/generated_plugin_registrant.cc b/examples/aws-flutter-web/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index e71a16d23d..0000000000 --- a/examples/aws-flutter-web/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,11 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - - -void fl_register_plugins(FlPluginRegistry* registry) { -} diff --git a/examples/aws-flutter-web/linux/flutter/generated_plugin_registrant.h b/examples/aws-flutter-web/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index e0f0a47bc0..0000000000 --- a/examples/aws-flutter-web/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/examples/aws-flutter-web/linux/flutter/generated_plugins.cmake b/examples/aws-flutter-web/linux/flutter/generated_plugins.cmake deleted file mode 100644 index 2e1de87a7e..0000000000 --- a/examples/aws-flutter-web/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,23 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/examples/aws-flutter-web/linux/main.cc b/examples/aws-flutter-web/linux/main.cc deleted file mode 100644 index e7c5c54370..0000000000 --- a/examples/aws-flutter-web/linux/main.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/examples/aws-flutter-web/linux/my_application.cc b/examples/aws-flutter-web/linux/my_application.cc deleted file mode 100644 index 809b553a5a..0000000000 --- a/examples/aws-flutter-web/linux/my_application.cc +++ /dev/null @@ -1,124 +0,0 @@ -#include "my_application.h" - -#include -#ifdef GDK_WINDOWING_X11 -#include -#endif - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; - char** dart_entrypoint_arguments; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - MyApplication* self = MY_APPLICATION(application); - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // if future cases occur). - gboolean use_header_bar = TRUE; -#ifdef GDK_WINDOWING_X11 - GdkScreen* screen = gtk_window_get_screen(window); - if (GDK_IS_X11_SCREEN(screen)) { - const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } - } -#endif - if (use_header_bar) { - GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "aws_flutter_web"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - } else { - gtk_window_set_title(window, "aws_flutter_web"); - } - - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -// Implements GApplication::local_command_line. -static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { - MyApplication* self = MY_APPLICATION(application); - // Strip out the first argument as it is the binary name. - self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); - - g_autoptr(GError) error = nullptr; - if (!g_application_register(application, nullptr, &error)) { - g_warning("Failed to register: %s", error->message); - *exit_status = 1; - return TRUE; - } - - g_application_activate(application); - *exit_status = 0; - - return TRUE; -} - -// Implements GApplication::startup. -static void my_application_startup(GApplication* application) { - //MyApplication* self = MY_APPLICATION(object); - - // Perform any actions required at application startup. - - G_APPLICATION_CLASS(my_application_parent_class)->startup(application); -} - -// Implements GApplication::shutdown. -static void my_application_shutdown(GApplication* application) { - //MyApplication* self = MY_APPLICATION(object); - - // Perform any actions required at application shutdown. - - G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); -} - -// Implements GObject::dispose. -static void my_application_dispose(GObject* object) { - MyApplication* self = MY_APPLICATION(object); - g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); - G_OBJECT_CLASS(my_application_parent_class)->dispose(object); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; - G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; - G_APPLICATION_CLASS(klass)->startup = my_application_startup; - G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; - G_OBJECT_CLASS(klass)->dispose = my_application_dispose; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - "flags", G_APPLICATION_NON_UNIQUE, - nullptr)); -} diff --git a/examples/aws-flutter-web/linux/my_application.h b/examples/aws-flutter-web/linux/my_application.h deleted file mode 100644 index 72271d5e41..0000000000 --- a/examples/aws-flutter-web/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/examples/aws-flutter-web/macos/.gitignore b/examples/aws-flutter-web/macos/.gitignore deleted file mode 100644 index 746adbb6b9..0000000000 --- a/examples/aws-flutter-web/macos/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -# Flutter-related -**/Flutter/ephemeral/ -**/Pods/ - -# Xcode-related -**/dgph -**/xcuserdata/ diff --git a/examples/aws-flutter-web/macos/Runner.xcodeproj/project.pbxproj b/examples/aws-flutter-web/macos/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index 1745b1b23b..0000000000 --- a/examples/aws-flutter-web/macos/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,705 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXAggregateTarget section */ - 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { - isa = PBXAggregateTarget; - buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; - buildPhases = ( - 33CC111E2044C6BF0003C045 /* ShellScript */, - ); - dependencies = ( - ); - name = "Flutter Assemble"; - productName = FLX; - }; -/* End PBXAggregateTarget section */ - -/* Begin PBXBuildFile section */ - 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC10EC2044A3C60003C045; - remoteInfo = Runner; - }; - 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC111A2044C6BA0003C045; - remoteInfo = FLX; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 33CC110E2044A8840003C045 /* Bundle Framework */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Bundle Framework"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* aws_flutter_web.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "aws_flutter_web.app"; sourceTree = BUILT_PRODUCTS_DIR; }; - 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; - 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; - 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; - 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; - 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; - 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 331C80D2294CF70F00263BE5 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 33CC10EA2044A3C60003C045 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 331C80D6294CF71000263BE5 /* RunnerTests */ = { - isa = PBXGroup; - children = ( - 331C80D7294CF71000263BE5 /* RunnerTests.swift */, - ); - path = RunnerTests; - sourceTree = ""; - }; - 33BA886A226E78AF003329D5 /* Configs */ = { - isa = PBXGroup; - children = ( - 33E5194F232828860026EE4D /* AppInfo.xcconfig */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, - ); - path = Configs; - sourceTree = ""; - }; - 33CC10E42044A3C60003C045 = { - isa = PBXGroup; - children = ( - 33FAB671232836740065AC1E /* Runner */, - 33CEB47122A05771004F2AC0 /* Flutter */, - 331C80D6294CF71000263BE5 /* RunnerTests */, - 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - ); - sourceTree = ""; - }; - 33CC10EE2044A3C60003C045 /* Products */ = { - isa = PBXGroup; - children = ( - 33CC10ED2044A3C60003C045 /* aws_flutter_web.app */, - 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 33CC11242044D66E0003C045 /* Resources */ = { - isa = PBXGroup; - children = ( - 33CC10F22044A3C60003C045 /* Assets.xcassets */, - 33CC10F42044A3C60003C045 /* MainMenu.xib */, - 33CC10F72044A3C60003C045 /* Info.plist */, - ); - name = Resources; - path = ..; - sourceTree = ""; - }; - 33CEB47122A05771004F2AC0 /* Flutter */ = { - isa = PBXGroup; - children = ( - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, - ); - path = Flutter; - sourceTree = ""; - }; - 33FAB671232836740065AC1E /* Runner */ = { - isa = PBXGroup; - children = ( - 33CC10F02044A3C60003C045 /* AppDelegate.swift */, - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, - 33E51913231747F40026EE4D /* DebugProfile.entitlements */, - 33E51914231749380026EE4D /* Release.entitlements */, - 33CC11242044D66E0003C045 /* Resources */, - 33BA886A226E78AF003329D5 /* Configs */, - ); - path = Runner; - sourceTree = ""; - }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 331C80D4294CF70F00263BE5 /* RunnerTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; - buildPhases = ( - 331C80D1294CF70F00263BE5 /* Sources */, - 331C80D2294CF70F00263BE5 /* Frameworks */, - 331C80D3294CF70F00263BE5 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 331C80DA294CF71000263BE5 /* PBXTargetDependency */, - ); - name = RunnerTests; - productName = RunnerTests; - productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 33CC10EC2044A3C60003C045 /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 33CC10E92044A3C60003C045 /* Sources */, - 33CC10EA2044A3C60003C045 /* Frameworks */, - 33CC10EB2044A3C60003C045 /* Resources */, - 33CC110E2044A8840003C045 /* Bundle Framework */, - 3399D490228B24CF009A79C7 /* ShellScript */, - ); - buildRules = ( - ); - dependencies = ( - 33CC11202044C79F0003C045 /* PBXTargetDependency */, - ); - name = Runner; - productName = Runner; - productReference = 33CC10ED2044A3C60003C045 /* aws_flutter_web.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 33CC10E52044A3C60003C045 /* Project object */ = { - isa = PBXProject; - attributes = { - BuildIndependentTargetsInParallel = YES; - LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1510; - ORGANIZATIONNAME = ""; - TargetAttributes = { - 331C80D4294CF70F00263BE5 = { - CreatedOnToolsVersion = 14.0; - TestTargetID = 33CC10EC2044A3C60003C045; - }; - 33CC10EC2044A3C60003C045 = { - CreatedOnToolsVersion = 9.2; - LastSwiftMigration = 1100; - ProvisioningStyle = Automatic; - SystemCapabilities = { - com.apple.Sandbox = { - enabled = 1; - }; - }; - }; - 33CC111A2044C6BA0003C045 = { - CreatedOnToolsVersion = 9.2; - ProvisioningStyle = Manual; - }; - }; - }; - buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 33CC10E42044A3C60003C045; - productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 33CC10EC2044A3C60003C045 /* Runner */, - 331C80D4294CF70F00263BE5 /* RunnerTests */, - 33CC111A2044C6BA0003C045 /* Flutter Assemble */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 331C80D3294CF70F00263BE5 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 33CC10EB2044A3C60003C045 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3399D490228B24CF009A79C7 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - ); - outputFileListPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; - }; - 33CC111E2044C6BF0003C045 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - Flutter/ephemeral/FlutterInputs.xcfilelist, - ); - inputPaths = ( - Flutter/ephemeral/tripwire, - ); - outputFileListPaths = ( - Flutter/ephemeral/FlutterOutputs.xcfilelist, - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 331C80D1294CF70F00263BE5 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 33CC10E92044A3C60003C045 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC10EC2044A3C60003C045 /* Runner */; - targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; - }; - 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; - targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { - isa = PBXVariantGroup; - children = ( - 33CC10F52044A3C60003C045 /* Base */, - ); - name = MainMenu.xib; - path = Runner; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 331C80DB294CF71000263BE5 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/aws_flutter_web.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/aws_flutter_web"; - }; - name = Debug; - }; - 331C80DC294CF71000263BE5 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/aws_flutter_web.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/aws_flutter_web"; - }; - name = Release; - }; - 331C80DD294CF71000263BE5 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.awsFlutterWeb.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/aws_flutter_web.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/aws_flutter_web"; - }; - name = Profile; - }; - 338D0CE9231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEAD_CODE_STRIPPING = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Profile; - }; - 338D0CEA231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Profile; - }; - 338D0CEB231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Profile; - }; - 33CC10F92044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEAD_CODE_STRIPPING = YES; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 33CC10FA2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEAD_CODE_STRIPPING = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Release; - }; - 33CC10FC2044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - }; - name = Debug; - }; - 33CC10FD2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Release; - }; - 33CC111C2044C6BA0003C045 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 33CC111D2044C6BA0003C045 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 331C80DB294CF71000263BE5 /* Debug */, - 331C80DC294CF71000263BE5 /* Release */, - 331C80DD294CF71000263BE5 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10F92044A3C60003C045 /* Debug */, - 33CC10FA2044A3C60003C045 /* Release */, - 338D0CE9231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10FC2044A3C60003C045 /* Debug */, - 33CC10FD2044A3C60003C045 /* Release */, - 338D0CEA231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC111C2044C6BA0003C045 /* Debug */, - 33CC111D2044C6BA0003C045 /* Release */, - 338D0CEB231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 33CC10E52044A3C60003C045 /* Project object */; -} diff --git a/examples/aws-flutter-web/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/examples/aws-flutter-web/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index d57ff0ed0a..0000000000 --- a/examples/aws-flutter-web/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index a2ec33f19f..0000000000 --- a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "images" : [ - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_16.png", - "scale" : "1x" - }, - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "2x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "1x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_64.png", - "scale" : "2x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_128.png", - "scale" : "1x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "2x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "1x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "2x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "1x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_1024.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png deleted file mode 100644 index 82b6f9d9a3..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png deleted file mode 100644 index 13b35eba55..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png deleted file mode 100644 index 0a3f5fa40f..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png deleted file mode 100644 index bdb57226d5..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png deleted file mode 100644 index f083318e09..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png deleted file mode 100644 index 326c0e72c9..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png deleted file mode 100644 index 2f1632cfdd..0000000000 Binary files a/examples/aws-flutter-web/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png and /dev/null differ diff --git a/examples/aws-flutter-web/macos/RunnerTests/RunnerTests.swift b/examples/aws-flutter-web/macos/RunnerTests/RunnerTests.swift deleted file mode 100644 index 61f3bd1fc5..0000000000 --- a/examples/aws-flutter-web/macos/RunnerTests/RunnerTests.swift +++ /dev/null @@ -1,12 +0,0 @@ -import Cocoa -import FlutterMacOS -import XCTest - -class RunnerTests: XCTestCase { - - func testExample() { - // If you add code to the Runner application, consider adding tests here. - // See https://developer.apple.com/documentation/xctest for more information about using XCTest. - } - -} diff --git a/examples/aws-flutter-web/pubspec.lock b/examples/aws-flutter-web/pubspec.lock deleted file mode 100644 index 5a8354a000..0000000000 --- a/examples/aws-flutter-web/pubspec.lock +++ /dev/null @@ -1,213 +0,0 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - async: - dependency: transitive - description: - name: async - sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" - url: "https://pub.dev" - source: hosted - version: "2.11.0" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" - url: "https://pub.dev" - source: hosted - version: "2.1.1" - characters: - dependency: transitive - description: - name: characters - sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" - url: "https://pub.dev" - source: hosted - version: "1.3.0" - clock: - dependency: transitive - description: - name: clock - sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf - url: "https://pub.dev" - source: hosted - version: "1.1.1" - collection: - dependency: transitive - description: - name: collection - sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a - url: "https://pub.dev" - source: hosted - version: "1.18.0" - cupertino_icons: - dependency: "direct main" - description: - name: cupertino_icons - sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 - url: "https://pub.dev" - source: hosted - version: "1.0.8" - fake_async: - dependency: transitive - description: - name: fake_async - sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" - url: "https://pub.dev" - source: hosted - version: "1.3.1" - flutter: - dependency: "direct main" - description: flutter - source: sdk - version: "0.0.0" - flutter_lints: - dependency: "direct dev" - description: - name: flutter_lints - sha256: "9e8c3858111da373efc5aa341de011d9bd23e2c5c5e0c62bccf32438e192d7b1" - url: "https://pub.dev" - source: hosted - version: "3.0.2" - flutter_test: - dependency: "direct dev" - description: flutter - source: sdk - version: "0.0.0" - leak_tracker: - dependency: transitive - description: - name: leak_tracker - sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" - url: "https://pub.dev" - source: hosted - version: "10.0.4" - leak_tracker_flutter_testing: - dependency: transitive - description: - name: leak_tracker_flutter_testing - sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" - url: "https://pub.dev" - source: hosted - version: "3.0.3" - leak_tracker_testing: - dependency: transitive - description: - name: leak_tracker_testing - sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" - url: "https://pub.dev" - source: hosted - version: "3.0.1" - lints: - dependency: transitive - description: - name: lints - sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 - url: "https://pub.dev" - source: hosted - version: "3.0.0" - matcher: - dependency: transitive - description: - name: matcher - sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb - url: "https://pub.dev" - source: hosted - version: "0.12.16+1" - material_color_utilities: - dependency: transitive - description: - name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" - url: "https://pub.dev" - source: hosted - version: "0.8.0" - meta: - dependency: transitive - description: - name: meta - sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" - url: "https://pub.dev" - source: hosted - version: "1.12.0" - path: - dependency: transitive - description: - name: path - sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" - url: "https://pub.dev" - source: hosted - version: "1.9.0" - sky_engine: - dependency: transitive - description: flutter - source: sdk - version: "0.0.99" - source_span: - dependency: transitive - description: - name: source_span - sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" - url: "https://pub.dev" - source: hosted - version: "1.10.0" - stack_trace: - dependency: transitive - description: - name: stack_trace - sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" - url: "https://pub.dev" - source: hosted - version: "1.11.1" - stream_channel: - dependency: transitive - description: - name: stream_channel - sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 - url: "https://pub.dev" - source: hosted - version: "2.1.2" - string_scanner: - dependency: transitive - description: - name: string_scanner - sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" - url: "https://pub.dev" - source: hosted - version: "1.2.0" - term_glyph: - dependency: transitive - description: - name: term_glyph - sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 - url: "https://pub.dev" - source: hosted - version: "1.2.1" - test_api: - dependency: transitive - description: - name: test_api - sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" - url: "https://pub.dev" - source: hosted - version: "0.7.0" - vector_math: - dependency: transitive - description: - name: vector_math - sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" - url: "https://pub.dev" - source: hosted - version: "2.1.4" - vm_service: - dependency: transitive - description: - name: vm_service - sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" - url: "https://pub.dev" - source: hosted - version: "14.2.1" -sdks: - dart: ">=3.4.1 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" diff --git a/examples/aws-flutter-web/pubspec.yaml b/examples/aws-flutter-web/pubspec.yaml deleted file mode 100644 index b2467bbe68..0000000000 --- a/examples/aws-flutter-web/pubspec.yaml +++ /dev/null @@ -1,90 +0,0 @@ -name: aws_flutter_web -description: "A new Flutter project." -# The following line prevents the package from being accidentally published to -# pub.dev using `flutter pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev - -# The following defines the version and build number for your application. -# A version number is three numbers separated by dots, like 1.2.43 -# followed by an optional build number separated by a +. -# Both the version and the builder number may be overridden in flutter -# build by specifying --build-name and --build-number, respectively. -# In Android, build-name is used as versionName while build-number used as versionCode. -# Read more about Android versioning at https://developer.android.com/studio/publish/versioning -# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -# In Windows, build-name is used as the major, minor, and patch parts -# of the product and file versions while build-number is used as the build suffix. -version: 1.0.0+1 - -environment: - sdk: '>=3.4.1 <4.0.0' - -# Dependencies specify other packages that your package needs in order to work. -# To automatically upgrade your package dependencies to the latest versions -# consider running `flutter pub upgrade --major-versions`. Alternatively, -# dependencies can be manually updated by changing the version numbers below to -# the latest version available on pub.dev. To see which dependencies have newer -# versions available, run `flutter pub outdated`. -dependencies: - flutter: - sdk: flutter - - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.6 - -dev_dependencies: - flutter_test: - sdk: flutter - - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. - flutter_lints: ^3.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. -flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages diff --git a/examples/aws-flutter-web/sst.config.ts b/examples/aws-flutter-web/sst.config.ts deleted file mode 100644 index 688d10a07c..0000000000 --- a/examples/aws-flutter-web/sst.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -/// - -/** - * ## Flutter web - * - * Deploy a Flutter web app as a static site to S3 and CloudFront. - */ -export default $config({ - app(input) { - return { - name: "aws-flutter-web", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.StaticSite("MySite", { - build: { - command: "flutter build web", - output: "build/web", - }, - }); - }, -}); diff --git a/examples/aws-flutter-web/web/index.html b/examples/aws-flutter-web/web/index.html deleted file mode 100644 index 4ba5cb2465..0000000000 --- a/examples/aws-flutter-web/web/index.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - aws_flutter_web - - - - - - diff --git a/examples/aws-flutter-web/web/manifest.json b/examples/aws-flutter-web/web/manifest.json deleted file mode 100644 index c27ccaa1dc..0000000000 --- a/examples/aws-flutter-web/web/manifest.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "aws_flutter_web", - "short_name": "aws_flutter_web", - "start_url": ".", - "display": "standalone", - "background_color": "#0175C2", - "theme_color": "#0175C2", - "description": "A new Flutter project.", - "orientation": "portrait-primary", - "prefer_related_applications": false, - "icons": [ - { - "src": "icons/Icon-192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "icons/Icon-512.png", - "sizes": "512x512", - "type": "image/png" - }, - { - "src": "icons/Icon-maskable-192.png", - "sizes": "192x192", - "type": "image/png", - "purpose": "maskable" - }, - { - "src": "icons/Icon-maskable-512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "maskable" - } - ] -} diff --git a/examples/aws-flutter-web/windows/.gitignore b/examples/aws-flutter-web/windows/.gitignore deleted file mode 100644 index d492d0d98c..0000000000 --- a/examples/aws-flutter-web/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -flutter/ephemeral/ - -# Visual Studio user-specific files. -*.suo -*.user -*.userosscache -*.sln.docstates - -# Visual Studio build-related files. -x64/ -x86/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ diff --git a/examples/aws-flutter-web/windows/CMakeLists.txt b/examples/aws-flutter-web/windows/CMakeLists.txt deleted file mode 100644 index d98ad262f1..0000000000 --- a/examples/aws-flutter-web/windows/CMakeLists.txt +++ /dev/null @@ -1,108 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.14) -project(aws_flutter_web LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "aws_flutter_web") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(VERSION 3.14...3.25) - -# Define build configuration option. -get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(IS_MULTICONFIG) - set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" - CACHE STRING "" FORCE) -else() - if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") - endif() -endif() -# Define settings for the Profile build mode. -set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") -set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") -set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") -set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") - -# Use Unicode for all projects. -add_definitions(-DUNICODE -D_UNICODE) - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_17) - target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") - target_compile_options(${TARGET} PRIVATE /EHsc) - target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") - target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Application build; see runner/CMakeLists.txt. -add_subdirectory("runner") - - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# Support files are copied into place next to the executable, so that it can -# run in place. This is done instead of making a separate bundle (as on Linux) -# so that building and running from within Visual Studio will work. -set(BUILD_BUNDLE_DIR "$") -# Make the "install" step default, as it's required to run. -set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -if(PLUGIN_BUNDLED_LIBRARIES) - install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() - -# Copy the native assets provided by the build.dart from all packages. -set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") -install(DIRECTORY "${NATIVE_ASSETS_DIR}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - CONFIGURATIONS Profile;Release - COMPONENT Runtime) diff --git a/examples/aws-flutter-web/windows/flutter/CMakeLists.txt b/examples/aws-flutter-web/windows/flutter/CMakeLists.txt deleted file mode 100644 index 903f4899d6..0000000000 --- a/examples/aws-flutter-web/windows/flutter/CMakeLists.txt +++ /dev/null @@ -1,109 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.14) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. -set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") - -# Set fallback configurations for older versions of the flutter tool. -if (NOT DEFINED FLUTTER_TARGET_PLATFORM) - set(FLUTTER_TARGET_PLATFORM "windows-x64") -endif() - -# === Flutter Library === -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "flutter_export.h" - "flutter_windows.h" - "flutter_messenger.h" - "flutter_plugin_registrar.h" - "flutter_texture_registrar.h" -) -list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") -add_dependencies(flutter flutter_assemble) - -# === Wrapper === -list(APPEND CPP_WRAPPER_SOURCES_CORE - "core_implementations.cc" - "standard_codec.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_PLUGIN - "plugin_registrar.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_APP - "flutter_engine.cc" - "flutter_view_controller.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") - -# Wrapper sources needed for a plugin. -add_library(flutter_wrapper_plugin STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} -) -apply_standard_settings(flutter_wrapper_plugin) -set_target_properties(flutter_wrapper_plugin PROPERTIES - POSITION_INDEPENDENT_CODE ON) -set_target_properties(flutter_wrapper_plugin PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) -target_include_directories(flutter_wrapper_plugin PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_plugin flutter_assemble) - -# Wrapper sources needed for the runner. -add_library(flutter_wrapper_app STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_APP} -) -apply_standard_settings(flutter_wrapper_app) -target_link_libraries(flutter_wrapper_app PUBLIC flutter) -target_include_directories(flutter_wrapper_app PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_app flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") -set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} - ${PHONY_OUTPUT} - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" - ${FLUTTER_TARGET_PLATFORM} $ - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} -) diff --git a/examples/aws-flutter-web/windows/flutter/generated_plugin_registrant.cc b/examples/aws-flutter-web/windows/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 8b6d4680af..0000000000 --- a/examples/aws-flutter-web/windows/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,11 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - - -void RegisterPlugins(flutter::PluginRegistry* registry) { -} diff --git a/examples/aws-flutter-web/windows/flutter/generated_plugin_registrant.h b/examples/aws-flutter-web/windows/flutter/generated_plugin_registrant.h deleted file mode 100644 index dc139d85a9..0000000000 --- a/examples/aws-flutter-web/windows/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void RegisterPlugins(flutter::PluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/examples/aws-flutter-web/windows/flutter/generated_plugins.cmake b/examples/aws-flutter-web/windows/flutter/generated_plugins.cmake deleted file mode 100644 index b93c4c30c1..0000000000 --- a/examples/aws-flutter-web/windows/flutter/generated_plugins.cmake +++ /dev/null @@ -1,23 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/examples/aws-flutter-web/windows/runner/CMakeLists.txt b/examples/aws-flutter-web/windows/runner/CMakeLists.txt deleted file mode 100644 index 394917c053..0000000000 --- a/examples/aws-flutter-web/windows/runner/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -cmake_minimum_required(VERSION 3.14) -project(runner LANGUAGES CXX) - -# Define the application target. To change its name, change BINARY_NAME in the -# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer -# work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} WIN32 - "flutter_window.cpp" - "main.cpp" - "utils.cpp" - "win32_window.cpp" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" - "Runner.rc" - "runner.exe.manifest" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add preprocessor definitions for the build version. -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") - -# Disable Windows macros that collide with C++ standard library functions. -target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") - -# Add dependency libraries and include directories. Add any application-specific -# dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) -target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") -target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/examples/aws-flutter-web/windows/runner/Runner.rc b/examples/aws-flutter-web/windows/runner/Runner.rc deleted file mode 100644 index 92f602fc3c..0000000000 --- a/examples/aws-flutter-web/windows/runner/Runner.rc +++ /dev/null @@ -1,121 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#pragma code_page(65001) -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_APP_ICON ICON "resources\\app_icon.ico" - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) -#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD -#else -#define VERSION_AS_NUMBER 1,0,0,0 -#endif - -#if defined(FLUTTER_VERSION) -#define VERSION_AS_STRING FLUTTER_VERSION -#else -#define VERSION_AS_STRING "1.0.0" -#endif - -VS_VERSION_INFO VERSIONINFO - FILEVERSION VERSION_AS_NUMBER - PRODUCTVERSION VERSION_AS_NUMBER - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_APP - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "CompanyName", "com.example" "\0" - VALUE "FileDescription", "aws_flutter_web" "\0" - VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "aws_flutter_web" "\0" - VALUE "LegalCopyright", "Copyright (C) 2024 com.example. All rights reserved." "\0" - VALUE "OriginalFilename", "aws_flutter_web.exe" "\0" - VALUE "ProductName", "aws_flutter_web" "\0" - VALUE "ProductVersion", VERSION_AS_STRING "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/examples/aws-flutter-web/windows/runner/flutter_window.cpp b/examples/aws-flutter-web/windows/runner/flutter_window.cpp deleted file mode 100644 index 955ee3038f..0000000000 --- a/examples/aws-flutter-web/windows/runner/flutter_window.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "flutter_window.h" - -#include - -#include "flutter/generated_plugin_registrant.h" - -FlutterWindow::FlutterWindow(const flutter::DartProject& project) - : project_(project) {} - -FlutterWindow::~FlutterWindow() {} - -bool FlutterWindow::OnCreate() { - if (!Win32Window::OnCreate()) { - return false; - } - - RECT frame = GetClientArea(); - - // The size here must match the window dimensions to avoid unnecessary surface - // creation / destruction in the startup path. - flutter_controller_ = std::make_unique( - frame.right - frame.left, frame.bottom - frame.top, project_); - // Ensure that basic setup of the controller was successful. - if (!flutter_controller_->engine() || !flutter_controller_->view()) { - return false; - } - RegisterPlugins(flutter_controller_->engine()); - SetChildContent(flutter_controller_->view()->GetNativeWindow()); - - flutter_controller_->engine()->SetNextFrameCallback([&]() { - this->Show(); - }); - - // Flutter can complete the first frame before the "show window" callback is - // registered. The following call ensures a frame is pending to ensure the - // window is shown. It is a no-op if the first frame hasn't completed yet. - flutter_controller_->ForceRedraw(); - - return true; -} - -void FlutterWindow::OnDestroy() { - if (flutter_controller_) { - flutter_controller_ = nullptr; - } - - Win32Window::OnDestroy(); -} - -LRESULT -FlutterWindow::MessageHandler(HWND hwnd, UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - // Give Flutter, including plugins, an opportunity to handle window messages. - if (flutter_controller_) { - std::optional result = - flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, - lparam); - if (result) { - return *result; - } - } - - switch (message) { - case WM_FONTCHANGE: - flutter_controller_->engine()->ReloadSystemFonts(); - break; - } - - return Win32Window::MessageHandler(hwnd, message, wparam, lparam); -} diff --git a/examples/aws-flutter-web/windows/runner/flutter_window.h b/examples/aws-flutter-web/windows/runner/flutter_window.h deleted file mode 100644 index 6da0652f05..0000000000 --- a/examples/aws-flutter-web/windows/runner/flutter_window.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef RUNNER_FLUTTER_WINDOW_H_ -#define RUNNER_FLUTTER_WINDOW_H_ - -#include -#include - -#include - -#include "win32_window.h" - -// A window that does nothing but host a Flutter view. -class FlutterWindow : public Win32Window { - public: - // Creates a new FlutterWindow hosting a Flutter view running |project|. - explicit FlutterWindow(const flutter::DartProject& project); - virtual ~FlutterWindow(); - - protected: - // Win32Window: - bool OnCreate() override; - void OnDestroy() override; - LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, - LPARAM const lparam) noexcept override; - - private: - // The project to run. - flutter::DartProject project_; - - // The Flutter instance hosted by this window. - std::unique_ptr flutter_controller_; -}; - -#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/examples/aws-flutter-web/windows/runner/main.cpp b/examples/aws-flutter-web/windows/runner/main.cpp deleted file mode 100644 index 420f00b523..0000000000 --- a/examples/aws-flutter-web/windows/runner/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include - -#include "flutter_window.h" -#include "utils.h" - -int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, - _In_ wchar_t *command_line, _In_ int show_command) { - // Attach to console when present (e.g., 'flutter run') or create a - // new console when running with a debugger. - if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { - CreateAndAttachConsole(); - } - - // Initialize COM, so that it is available for use in the library and/or - // plugins. - ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - - flutter::DartProject project(L"data"); - - std::vector command_line_arguments = - GetCommandLineArguments(); - - project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); - - FlutterWindow window(project); - Win32Window::Point origin(10, 10); - Win32Window::Size size(1280, 720); - if (!window.Create(L"aws_flutter_web", origin, size)) { - return EXIT_FAILURE; - } - window.SetQuitOnClose(true); - - ::MSG msg; - while (::GetMessage(&msg, nullptr, 0, 0)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - } - - ::CoUninitialize(); - return EXIT_SUCCESS; -} diff --git a/examples/aws-flutter-web/windows/runner/resource.h b/examples/aws-flutter-web/windows/runner/resource.h deleted file mode 100644 index 66a65d1e4a..0000000000 --- a/examples/aws-flutter-web/windows/runner/resource.h +++ /dev/null @@ -1,16 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Runner.rc -// -#define IDI_APP_ICON 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/examples/aws-flutter-web/windows/runner/resources/app_icon.ico b/examples/aws-flutter-web/windows/runner/resources/app_icon.ico deleted file mode 100644 index c04e20caf6..0000000000 Binary files a/examples/aws-flutter-web/windows/runner/resources/app_icon.ico and /dev/null differ diff --git a/examples/aws-flutter-web/windows/runner/runner.exe.manifest b/examples/aws-flutter-web/windows/runner/runner.exe.manifest deleted file mode 100644 index a42ea7687c..0000000000 --- a/examples/aws-flutter-web/windows/runner/runner.exe.manifest +++ /dev/null @@ -1,20 +0,0 @@ - - - - - PerMonitorV2 - - - - - - - - - - - - - - - diff --git a/examples/aws-flutter-web/windows/runner/utils.cpp b/examples/aws-flutter-web/windows/runner/utils.cpp deleted file mode 100644 index 3a0b46511a..0000000000 --- a/examples/aws-flutter-web/windows/runner/utils.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "utils.h" - -#include -#include -#include -#include - -#include - -void CreateAndAttachConsole() { - if (::AllocConsole()) { - FILE *unused; - if (freopen_s(&unused, "CONOUT$", "w", stdout)) { - _dup2(_fileno(stdout), 1); - } - if (freopen_s(&unused, "CONOUT$", "w", stderr)) { - _dup2(_fileno(stdout), 2); - } - std::ios::sync_with_stdio(); - FlutterDesktopResyncOutputStreams(); - } -} - -std::vector GetCommandLineArguments() { - // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. - int argc; - wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); - if (argv == nullptr) { - return std::vector(); - } - - std::vector command_line_arguments; - - // Skip the first argument as it's the binary name. - for (int i = 1; i < argc; i++) { - command_line_arguments.push_back(Utf8FromUtf16(argv[i])); - } - - ::LocalFree(argv); - - return command_line_arguments; -} - -std::string Utf8FromUtf16(const wchar_t* utf16_string) { - if (utf16_string == nullptr) { - return std::string(); - } - unsigned int target_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr) - -1; // remove the trailing null character - int input_length = (int)wcslen(utf16_string); - std::string utf8_string; - if (target_length == 0 || target_length > utf8_string.max_size()) { - return utf8_string; - } - utf8_string.resize(target_length); - int converted_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - input_length, utf8_string.data(), target_length, nullptr, nullptr); - if (converted_length == 0) { - return std::string(); - } - return utf8_string; -} diff --git a/examples/aws-flutter-web/windows/runner/utils.h b/examples/aws-flutter-web/windows/runner/utils.h deleted file mode 100644 index 3879d54755..0000000000 --- a/examples/aws-flutter-web/windows/runner/utils.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef RUNNER_UTILS_H_ -#define RUNNER_UTILS_H_ - -#include -#include - -// Creates a console for the process, and redirects stdout and stderr to -// it for both the runner and the Flutter library. -void CreateAndAttachConsole(); - -// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string -// encoded in UTF-8. Returns an empty std::string on failure. -std::string Utf8FromUtf16(const wchar_t* utf16_string); - -// Gets the command line arguments passed in as a std::vector, -// encoded in UTF-8. Returns an empty std::vector on failure. -std::vector GetCommandLineArguments(); - -#endif // RUNNER_UTILS_H_ diff --git a/examples/aws-flutter-web/windows/runner/win32_window.cpp b/examples/aws-flutter-web/windows/runner/win32_window.cpp deleted file mode 100644 index 60608d0fe5..0000000000 --- a/examples/aws-flutter-web/windows/runner/win32_window.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "win32_window.h" - -#include -#include - -#include "resource.h" - -namespace { - -/// Window attribute that enables dark mode window decorations. -/// -/// Redefined in case the developer's machine has a Windows SDK older than -/// version 10.0.22000.0. -/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute -#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE -#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 -#endif - -constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; - -/// Registry key for app theme preference. -/// -/// A value of 0 indicates apps should use dark mode. A non-zero or missing -/// value indicates apps should use light mode. -constexpr const wchar_t kGetPreferredBrightnessRegKey[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; -constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; - -// The number of Win32Window objects that currently exist. -static int g_active_window_count = 0; - -using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); - -// Scale helper to convert logical scaler values to physical using passed in -// scale factor -int Scale(int source, double scale_factor) { - return static_cast(source * scale_factor); -} - -// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. -// This API is only needed for PerMonitor V1 awareness mode. -void EnableFullDpiSupportIfAvailable(HWND hwnd) { - HMODULE user32_module = LoadLibraryA("User32.dll"); - if (!user32_module) { - return; - } - auto enable_non_client_dpi_scaling = - reinterpret_cast( - GetProcAddress(user32_module, "EnableNonClientDpiScaling")); - if (enable_non_client_dpi_scaling != nullptr) { - enable_non_client_dpi_scaling(hwnd); - } - FreeLibrary(user32_module); -} - -} // namespace - -// Manages the Win32Window's window class registration. -class WindowClassRegistrar { - public: - ~WindowClassRegistrar() = default; - - // Returns the singleton registrar instance. - static WindowClassRegistrar* GetInstance() { - if (!instance_) { - instance_ = new WindowClassRegistrar(); - } - return instance_; - } - - // Returns the name of the window class, registering the class if it hasn't - // previously been registered. - const wchar_t* GetWindowClass(); - - // Unregisters the window class. Should only be called if there are no - // instances of the window. - void UnregisterWindowClass(); - - private: - WindowClassRegistrar() = default; - - static WindowClassRegistrar* instance_; - - bool class_registered_ = false; -}; - -WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; - -const wchar_t* WindowClassRegistrar::GetWindowClass() { - if (!class_registered_) { - WNDCLASS window_class{}; - window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - window_class.lpszClassName = kWindowClassName; - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.cbClsExtra = 0; - window_class.cbWndExtra = 0; - window_class.hInstance = GetModuleHandle(nullptr); - window_class.hIcon = - LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); - window_class.hbrBackground = 0; - window_class.lpszMenuName = nullptr; - window_class.lpfnWndProc = Win32Window::WndProc; - RegisterClass(&window_class); - class_registered_ = true; - } - return kWindowClassName; -} - -void WindowClassRegistrar::UnregisterWindowClass() { - UnregisterClass(kWindowClassName, nullptr); - class_registered_ = false; -} - -Win32Window::Win32Window() { - ++g_active_window_count; -} - -Win32Window::~Win32Window() { - --g_active_window_count; - Destroy(); -} - -bool Win32Window::Create(const std::wstring& title, - const Point& origin, - const Size& size) { - Destroy(); - - const wchar_t* window_class = - WindowClassRegistrar::GetInstance()->GetWindowClass(); - - const POINT target_point = {static_cast(origin.x), - static_cast(origin.y)}; - HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); - UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); - double scale_factor = dpi / 96.0; - - HWND window = CreateWindow( - window_class, title.c_str(), WS_OVERLAPPEDWINDOW, - Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), - Scale(size.width, scale_factor), Scale(size.height, scale_factor), - nullptr, nullptr, GetModuleHandle(nullptr), this); - - if (!window) { - return false; - } - - UpdateTheme(window); - - return OnCreate(); -} - -bool Win32Window::Show() { - return ShowWindow(window_handle_, SW_SHOWNORMAL); -} - -// static -LRESULT CALLBACK Win32Window::WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - if (message == WM_NCCREATE) { - auto window_struct = reinterpret_cast(lparam); - SetWindowLongPtr(window, GWLP_USERDATA, - reinterpret_cast(window_struct->lpCreateParams)); - - auto that = static_cast(window_struct->lpCreateParams); - EnableFullDpiSupportIfAvailable(window); - that->window_handle_ = window; - } else if (Win32Window* that = GetThisFromHandle(window)) { - return that->MessageHandler(window, message, wparam, lparam); - } - - return DefWindowProc(window, message, wparam, lparam); -} - -LRESULT -Win32Window::MessageHandler(HWND hwnd, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - switch (message) { - case WM_DESTROY: - window_handle_ = nullptr; - Destroy(); - if (quit_on_close_) { - PostQuitMessage(0); - } - return 0; - - case WM_DPICHANGED: { - auto newRectSize = reinterpret_cast(lparam); - LONG newWidth = newRectSize->right - newRectSize->left; - LONG newHeight = newRectSize->bottom - newRectSize->top; - - SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, - newHeight, SWP_NOZORDER | SWP_NOACTIVATE); - - return 0; - } - case WM_SIZE: { - RECT rect = GetClientArea(); - if (child_content_ != nullptr) { - // Size and position the child window. - MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, - rect.bottom - rect.top, TRUE); - } - return 0; - } - - case WM_ACTIVATE: - if (child_content_ != nullptr) { - SetFocus(child_content_); - } - return 0; - - case WM_DWMCOLORIZATIONCOLORCHANGED: - UpdateTheme(hwnd); - return 0; - } - - return DefWindowProc(window_handle_, message, wparam, lparam); -} - -void Win32Window::Destroy() { - OnDestroy(); - - if (window_handle_) { - DestroyWindow(window_handle_); - window_handle_ = nullptr; - } - if (g_active_window_count == 0) { - WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); - } -} - -Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); -} - -void Win32Window::SetChildContent(HWND content) { - child_content_ = content; - SetParent(content, window_handle_); - RECT frame = GetClientArea(); - - MoveWindow(content, frame.left, frame.top, frame.right - frame.left, - frame.bottom - frame.top, true); - - SetFocus(child_content_); -} - -RECT Win32Window::GetClientArea() { - RECT frame; - GetClientRect(window_handle_, &frame); - return frame; -} - -HWND Win32Window::GetHandle() { - return window_handle_; -} - -void Win32Window::SetQuitOnClose(bool quit_on_close) { - quit_on_close_ = quit_on_close; -} - -bool Win32Window::OnCreate() { - // No-op; provided for subclasses. - return true; -} - -void Win32Window::OnDestroy() { - // No-op; provided for subclasses. -} - -void Win32Window::UpdateTheme(HWND const window) { - DWORD light_mode; - DWORD light_mode_size = sizeof(light_mode); - LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, - kGetPreferredBrightnessRegValue, - RRF_RT_REG_DWORD, nullptr, &light_mode, - &light_mode_size); - - if (result == ERROR_SUCCESS) { - BOOL enable_dark_mode = light_mode == 0; - DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, - &enable_dark_mode, sizeof(enable_dark_mode)); - } -} diff --git a/examples/aws-flutter-web/windows/runner/win32_window.h b/examples/aws-flutter-web/windows/runner/win32_window.h deleted file mode 100644 index e901dde684..0000000000 --- a/examples/aws-flutter-web/windows/runner/win32_window.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef RUNNER_WIN32_WINDOW_H_ -#define RUNNER_WIN32_WINDOW_H_ - -#include - -#include -#include -#include - -// A class abstraction for a high DPI-aware Win32 Window. Intended to be -// inherited from by classes that wish to specialize with custom -// rendering and input handling -class Win32Window { - public: - struct Point { - unsigned int x; - unsigned int y; - Point(unsigned int x, unsigned int y) : x(x), y(y) {} - }; - - struct Size { - unsigned int width; - unsigned int height; - Size(unsigned int width, unsigned int height) - : width(width), height(height) {} - }; - - Win32Window(); - virtual ~Win32Window(); - - // Creates a win32 window with |title| that is positioned and sized using - // |origin| and |size|. New windows are created on the default monitor. Window - // sizes are specified to the OS in physical pixels, hence to ensure a - // consistent size this function will scale the inputted width and height as - // as appropriate for the default monitor. The window is invisible until - // |Show| is called. Returns true if the window was created successfully. - bool Create(const std::wstring& title, const Point& origin, const Size& size); - - // Show the current window. Returns true if the window was successfully shown. - bool Show(); - - // Release OS resources associated with window. - void Destroy(); - - // Inserts |content| into the window tree. - void SetChildContent(HWND content); - - // Returns the backing Window handle to enable clients to set icon and other - // window properties. Returns nullptr if the window has been destroyed. - HWND GetHandle(); - - // If true, closing this window will quit the application. - void SetQuitOnClose(bool quit_on_close); - - // Return a RECT representing the bounds of the current client area. - RECT GetClientArea(); - - protected: - // Processes and route salient window messages for mouse handling, - // size change and DPI. Delegates handling of these to member overloads that - // inheriting classes can handle. - virtual LRESULT MessageHandler(HWND window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Called when CreateAndShow is called, allowing subclass window-related - // setup. Subclasses should return false if setup fails. - virtual bool OnCreate(); - - // Called when Destroy is called. - virtual void OnDestroy(); - - private: - friend class WindowClassRegistrar; - - // OS callback called by message pump. Handles the WM_NCCREATE message which - // is passed when the non-client area is being created and enables automatic - // non-client DPI scaling so that the non-client area automatically - // responds to changes in DPI. All other messages are handled by - // MessageHandler. - static LRESULT CALLBACK WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Retrieves a class instance pointer for |window| - static Win32Window* GetThisFromHandle(HWND const window) noexcept; - - // Update the window frame's theme to match the system theme. - static void UpdateTheme(HWND const window); - - bool quit_on_close_ = false; - - // window handle for top level window. - HWND window_handle_ = nullptr; - - // window handle for hosted content. - HWND child_content_ = nullptr; -}; - -#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/examples/aws-go-api-gateway-v2/package.json b/examples/aws-go-api-gateway-v2/package.json deleted file mode 100644 index 73e5fb2b94..0000000000 --- a/examples/aws-go-api-gateway-v2/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "aws-go-api-gateway-v2", - "module": "index.ts", - "type": "module", - "devDependencies": { - "@types/aws-lambda": "8.10.146", - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5.0.0" - }, - "dependencies": { - "sst": "file:../../sdk/js" - }, - "scripts": { - "dev": "bun sst dev" - } -} \ No newline at end of file diff --git a/examples/aws-go-api-gateway-v2/src/go.mod b/examples/aws-go-api-gateway-v2/src/go.mod deleted file mode 100644 index 518c0cb85f..0000000000 --- a/examples/aws-go-api-gateway-v2/src/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module sst-go-api - -go 1.23.3 - -require ( - github.com/aws/aws-lambda-go v1.47.0 // indirect - github.com/awslabs/aws-lambda-go-api-proxy v0.16.2 // indirect -) diff --git a/examples/aws-go-api-gateway-v2/src/go.sum b/examples/aws-go-api-gateway-v2/src/go.sum deleted file mode 100644 index 778c713c31..0000000000 --- a/examples/aws-go-api-gateway-v2/src/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/aws/aws-lambda-go v1.47.0 h1:0H8s0vumYx/YKs4sE7YM0ktwL2eWse+kfopsRI1sXVI= -github.com/aws/aws-lambda-go v1.47.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= -github.com/awslabs/aws-lambda-go-api-proxy v0.16.2 h1:CJyGEyO1CIwOnXTU40urf0mchf6t3voxpvUDikOU9LY= -github.com/awslabs/aws-lambda-go-api-proxy v0.16.2/go.mod h1:vxxjwBHe/KbgFeNlAP/Tvp4SsVRL3WQamcWRxqVh0z0= diff --git a/examples/aws-go-api-gateway-v2/src/main.go b/examples/aws-go-api-gateway-v2/src/main.go deleted file mode 100644 index 4ec3d6b278..0000000000 --- a/examples/aws-go-api-gateway-v2/src/main.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "encoding/json" - "net/http" - - "github.com/aws/aws-lambda-go/lambda" - "github.com/awslabs/aws-lambda-go-api-proxy/httpadapter" -) - -func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) { - encoder := json.NewEncoder(w) - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(code) - encoder.Encode(payload) - -} - -func router() *http.ServeMux { - mux := http.NewServeMux() - - mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - respondWithJSON(w, http.StatusOK, map[string]string{"message": "hello world"}) - return - }) - mux.HandleFunc("/my-ping", func(w http.ResponseWriter, r *http.Request) { - respondWithJSON(w, http.StatusOK, map[string]string{"message": "pong"}) - return - }) - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - respondWithJSON(w, http.StatusNotFound, map[string]string{"message": "not found"}) - return - }) - mux.HandleFunc("/{$}", func(w http.ResponseWriter, r *http.Request) { - respondWithJSON(w, http.StatusOK, map[string]string{"message": "home page"}) - }) - - return mux -} - -func main() { - - lambda.Start(httpadapter.NewV2(router()).ProxyWithContext) - -} diff --git a/examples/aws-go-api-gateway-v2/sst.config.ts b/examples/aws-go-api-gateway-v2/sst.config.ts deleted file mode 100644 index 4eb7a35105..0000000000 --- a/examples/aws-go-api-gateway-v2/sst.config.ts +++ /dev/null @@ -1,54 +0,0 @@ -/// - -/** - * ## AWS ApiGatewayV2 Go - * - * Uses [aws-lambda-go-api-proxy](https://github.com/awslabs/aws-lambda-go-api-proxy/tree/master) to allow you to run a Go API with API Gateway V2. - * - * :::tip - * We use the `aws-lambda-go-api-proxy` package to handle the API Gateway V2 event. - * ::: - * - * So you write your Go function as you normally would and then use the package to handle the API Gateway V2 event. - * - * ```go title="main.go" - * import ( - * "github.com/aws/aws-lambda-go/lambda" - * "github.com/awslabs/aws-lambda-go-api-proxy/httpadapter" - * ) - * - * func router() *http.ServeMux { - * mux := http.NewServeMux() - * - * mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - * w.Header().Set("Content-Type", "application/json") - * w.WriteHeader(http.StatusOK) - * w.Write([]byte(`{"message": "hello world"}`)) - * }) - * - * return mux - * } - * - * func main() { - * lambda.Start(httpadapter.NewV2(router()).ProxyWithContext) - * } - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-go-api-gateway-v2", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const api = new sst.aws.ApiGatewayV2("GoApi"); - - api.route("$default", { - handler: "src/", - runtime: "go", - }); - }, -}); diff --git a/examples/aws-go-api-gateway-v2/tsconfig.json b/examples/aws-go-api-gateway-v2/tsconfig.json deleted file mode 100644 index fd521c7b05..0000000000 --- a/examples/aws-go-api-gateway-v2/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - // Enable latest features - "lib": ["ESNext"], - "target": "ESNext", - "module": "ESNext", - "moduleDetection": "force", - "allowJs": true, - - // Bundler mode - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "noEmit": true, - - // Best practices - "strict": true, - "skipLibCheck": true, - "noFallthroughCasesInSwitch": true, - - // Some stricter flags (disabled by default) - "noUnusedLocals": false, - "noUnusedParameters": false, - "noPropertyAccessFromIndexSignature": false - } -} diff --git a/examples/aws-go-lambda-bucket-presigned-url/package.json b/examples/aws-go-lambda-bucket-presigned-url/package.json deleted file mode 100644 index 4c65464398..0000000000 --- a/examples/aws-go-lambda-bucket-presigned-url/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-go-lambda-bucket-presigned-url", - "module": "index.ts", - "type": "module", - "devDependencies": { - "@types/aws-lambda": "8.10.146", - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5.0.0" - }, - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-go-lambda-bucket-presigned-url/src/go.mod b/examples/aws-go-lambda-bucket-presigned-url/src/go.mod deleted file mode 100644 index 6325fc595d..0000000000 --- a/examples/aws-go-lambda-bucket-presigned-url/src/go.mod +++ /dev/null @@ -1,31 +0,0 @@ -module sst-go-file-upload - -go 1.23.3 - -require ( - github.com/aws/aws-lambda-go v1.47.0 - github.com/aws/aws-sdk-go v1.44.298 - github.com/aws/aws-sdk-go-v2/config v1.28.7 - github.com/aws/aws-sdk-go-v2/service/s3 v1.71.1 - github.com/google/uuid v1.6.0 - github.com/sst/sst/v3 v3.4.27 -) - -require ( - github.com/aws/aws-sdk-go-v2 v1.32.7 // indirect - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.7 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.17.48 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.26 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.4.7 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 // indirect - github.com/aws/smithy-go v1.22.1 // indirect -) diff --git a/examples/aws-go-lambda-bucket-presigned-url/src/go.sum b/examples/aws-go-lambda-bucket-presigned-url/src/go.sum deleted file mode 100644 index 8d659a9d1d..0000000000 --- a/examples/aws-go-lambda-bucket-presigned-url/src/go.sum +++ /dev/null @@ -1,87 +0,0 @@ -github.com/aws/aws-lambda-go v1.47.0 h1:0H8s0vumYx/YKs4sE7YM0ktwL2eWse+kfopsRI1sXVI= -github.com/aws/aws-lambda-go v1.47.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= -github.com/aws/aws-sdk-go v1.44.298 h1:5qTxdubgV7PptZJmp/2qDwD2JL187ePL7VOxsSh1i3g= -github.com/aws/aws-sdk-go v1.44.298/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= -github.com/aws/aws-sdk-go-v2 v1.32.7 h1:ky5o35oENWi0JYWUZkB7WYvVPP+bcRF5/Iq7JWSb5Rw= -github.com/aws/aws-sdk-go-v2 v1.32.7/go.mod h1:P5WJBrYqqbWVaOxgH0X/FYYD47/nooaPOZPlQdmiN2U= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.7 h1:lL7IfaFzngfx0ZwUGOZdsFFnQ5uLvR0hWqqhyE7Q9M8= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.7/go.mod h1:QraP0UcVlQJsmHfioCrveWOC1nbiWUl3ej08h4mXWoc= -github.com/aws/aws-sdk-go-v2/config v1.28.7 h1:GduUnoTXlhkgnxTD93g1nv4tVPILbdNQOzav+Wpg7AE= -github.com/aws/aws-sdk-go-v2/config v1.28.7/go.mod h1:vZGX6GVkIE8uECSUHB6MWAUsd4ZcG2Yq/dMa4refR3M= -github.com/aws/aws-sdk-go-v2/credentials v1.17.48 h1:IYdLD1qTJ0zanRavulofmqut4afs45mOWEI+MzZtTfQ= -github.com/aws/aws-sdk-go-v2/credentials v1.17.48/go.mod h1:tOscxHN3CGmuX9idQ3+qbkzrjVIx32lqDSU1/0d/qXs= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 h1:kqOrpojG71DxJm/KDPO+Z/y1phm1JlC8/iT+5XRmAn8= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22/go.mod h1:NtSFajXVVL8TA2QNngagVZmUtXciyrHOt7xgz4faS/M= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 h1:I/5wmGMffY4happ8NOCuIUEWGUvvFp5NSeQcXl9RHcI= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26/go.mod h1:FR8f4turZtNy6baO0KJ5FJUmXH/cSkI9fOngs0yl6mA= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 h1:zXFLuEuMMUOvEARXFUVJdfqZ4bvvSgdGRq/ATcrQxzM= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26/go.mod h1:3o2Wpy0bogG1kyOPrgkXA8pgIfEEv0+m19O9D5+W8y8= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 h1:VaRN3TlFdd6KxX1x3ILT5ynH6HvKgqdiXoTxAF4HQcQ= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1/go.mod h1:FbtygfRFze9usAadmnGJNc8KsP346kEe+y2/oyhGAGc= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.26 h1:GeNJsIFHB+WW5ap2Tec4K6dzcVTsRbsT1Lra46Hv9ME= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.26/go.mod h1:zfgMpwHDXX2WGoG84xG2H+ZlPTkJUU4YUvx2svLQYWo= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 h1:iXtILhvDxB6kPvEXgsDhGaZCSC6LQET5ZHSdJozeI0Y= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1/go.mod h1:9nu0fVANtYiAePIBh2/pFUSwtJ402hLnp854CNoDOeE= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.4.7 h1:tB4tNw83KcajNAzaIMhkhVI2Nt8fAZd5A5ro113FEMY= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.4.7/go.mod h1:lvpyBGkZ3tZ9iSsUIcC2EWp+0ywa7aK3BLT+FwZi+mQ= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 h1:8eUsivBQzZHqe/3FE+cqwfH+0p5Jo8PFM/QYQSmeZ+M= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7/go.mod h1:kLPQvGUmxn/fqiCrDeohwG33bq2pQpGeY62yRO6Nrh0= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.7 h1:Hi0KGbrnr57bEHWM0bJ1QcBzxLrL/k2DHvGYhb8+W1w= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.7/go.mod h1:wKNgWgExdjjrm4qvfbTorkvocEstaoDl4WCvGfeCy9c= -github.com/aws/aws-sdk-go-v2/service/s3 v1.71.1 h1:aOVVZJgWbaH+EJYPvEgkNhCEbXXvH7+oML36oaPK3zE= -github.com/aws/aws-sdk-go-v2/service/s3 v1.71.1/go.mod h1:r+xl5yzMk9083rMR+sJ5TYj9Tihvf/l1oxzZXDgGj2Q= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 h1:CvuUmnXI7ebaUAhbJcDy9YQx8wHR69eZ9I7q5hszt/g= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.8/go.mod h1:XDeGv1opzwm8ubxddF0cgqkZWsyOtw4lr6dxwmb6YQg= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 h1:F2rBfNAL5UyswqoeWv9zs74N/NanhK16ydHW1pahX6E= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7/go.mod h1:JfyQ0g2JG8+Krq0EuZNnRwX0mU0HrwY/tG6JNfcqh4k= -github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 h1:Xgv/hyNgvLda/M9l9qxXc4UFSgppnRczLxlMs5Ae/QY= -github.com/aws/aws-sdk-go-v2/service/sts v1.33.3/go.mod h1:5Gn+d+VaaRgsjewpMvGazt0WfcFO+Md4wLOuBfGR9Bc= -github.com/aws/smithy-go v1.22.1 h1:/HPHZQ0g7f4eUeK6HKglFz8uwVfZKgoI25rb/J+dnro= -github.com/aws/smithy-go v1.22.1/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sst/sst/v3 v3.4.27 h1:LRPqw1HRhLZQ8EoL8rXacOkavZlf1k/Am8CZ0uEdMXg= -github.com/sst/sst/v3 v3.4.27/go.mod h1:rxQ4Pi7xaYAbyfLt0rFREzQDLE72clWKxudGKG9Xpt4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/examples/aws-go-lambda-bucket-presigned-url/src/main.go b/examples/aws-go-lambda-bucket-presigned-url/src/main.go deleted file mode 100644 index 2604490c67..0000000000 --- a/examples/aws-go-lambda-bucket-presigned-url/src/main.go +++ /dev/null @@ -1,98 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "os" - "time" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/s3" - "github.com/aws/aws-sdk-go/aws" - "github.com/google/uuid" - "github.com/sst/sst/v3/sdk/golang/resource" -) - -type App struct { - client *s3.Client - presignedClient *s3.PresignClient - bucketName string -} - -func NewApp() *App { - cfg, err := config.LoadDefaultConfig(context.Background(), func(opts *config.LoadOptions) error { - opts.Region = os.Getenv("AWS_REGION") - return nil - }) - if err != nil { - panic(err) - } - client := s3.NewFromConfig(cfg) - presignedClient := s3.NewPresignClient(client) - - bucketName, err := resource.Get("Bucket", "name") - if err != nil { - panic(err) - } - - return &App{ - client: client, - presignedClient: presignedClient, - bucketName: bucketName.(string), - } -} - -func (app *App) handler(ctx context.Context, r events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { - - filename := r.QueryStringParameters["filename"] - filetype := r.QueryStringParameters["filetype"] - - id := uuid.New() - key := fmt.Sprintf("%s-%s", id, filename) - - url, err := app.presignedClient.PresignPutObject(context.Background(), &s3.PutObjectInput{ - Bucket: aws.String(app.bucketName), - Key: aws.String(key), - ContentType: aws.String(filetype), - }, func(opts *s3.PresignOptions) { - opts.Expires = 600 * time.Second // 10 minutes - }) - - if err != nil { - return apiErrorResponse(http.StatusInternalServerError, "Internal Server Error"), nil - } - - var response struct { - URL string `json:"url"` - } - response.URL = url.URL - body, err := json.Marshal(response) - if err != nil { - return apiErrorResponse(http.StatusInternalServerError, "Internal Server Error"), nil - } - - return events.APIGatewayV2HTTPResponse{ - StatusCode: http.StatusOK, - Headers: map[string]string{"Content-Type": "application/json"}, - Body: string(body), - }, nil - -} - -func main() { - app := NewApp() - lambda.Start(app.handler) -} - -func apiErrorResponse(statusCode int, message string) events.APIGatewayV2HTTPResponse { - body, _ := json.Marshal(map[string]string{"message": message}) - return events.APIGatewayV2HTTPResponse{ - StatusCode: statusCode, - Headers: map[string]string{"Content-Type": "application/json"}, - Body: string(body), - } -} diff --git a/examples/aws-go-lambda-bucket-presigned-url/sst.config.ts b/examples/aws-go-lambda-bucket-presigned-url/sst.config.ts deleted file mode 100644 index 0ad00c8fdb..0000000000 --- a/examples/aws-go-lambda-bucket-presigned-url/sst.config.ts +++ /dev/null @@ -1,52 +0,0 @@ -/// - -/** - * ## AWS Lambda Go S3 Presigned - * - * Generates a presigned URL for the linked S3 bucket in a Go Lambda function. - * - * Configure the S3 Client and the PresignedClient. - * - * ```go title="main.go" - * cfg, err := config.LoadDefaultConfig(context.TODO()) - * if err != nil { - * panic(err) - * } - * - * client := s3.NewFromConfig(cfg) - * presignedClient := s3.NewPresignClient(client) - * ``` - * - * Generate the presigned URL. - * - * ```go title="main.go" - * bucketName, err := resource.Get("Bucket", "name") - * if err != nil { - * panic(err) - * } - * url, err := presignedClient.PresignPutObject(context.TODO(), &s3.PutObjectInput{ - * Bucket: aws.String(bucket.(string)), - * Key: aws.String(key), - * }) - * ``` - */ -export default $config({ - app(input) { - return { - name: "aws-go-lambda-bucket-presigned-url", - removal: "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("Bucket"); - - const api = new sst.aws.ApiGatewayV2("Api"); - - api.route("GET /upload-url", { - handler: "src/", - runtime: "go", - link: [bucket], - }); - }, -}); diff --git a/examples/aws-go-lambda-bucket-presigned-url/tsconfig.json b/examples/aws-go-lambda-bucket-presigned-url/tsconfig.json deleted file mode 100644 index df2b488923..0000000000 --- a/examples/aws-go-lambda-bucket-presigned-url/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - // Enable latest features - "lib": ["ESNext"], - "target": "ESNext", - "module": "ESNext", - "moduleDetection": "force", - "jsx": "react-jsx", - "allowJs": true, - - // Bundler mode - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "noEmit": true, - - // Best practices - "strict": true, - "skipLibCheck": true, - "noFallthroughCasesInSwitch": true, - - // Some stricter flags - "noUnusedLocals": true, - "noUnusedParameters": true, - "noPropertyAccessFromIndexSignature": true - } -} diff --git a/examples/aws-go-lambda-dynamo/package.json b/examples/aws-go-lambda-dynamo/package.json deleted file mode 100644 index d230289740..0000000000 --- a/examples/aws-go-lambda-dynamo/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "aws-go-lambda-dynamo", - "module": "index.ts", - "type": "module", - "devDependencies": { - "@types/aws-lambda": "8.10.146", - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5.0.0" - }, - "dependencies": { - "sst": "file:../../sdk/js" - }, - "scripts": { - "dev": "bun sst dev" - } -} diff --git a/examples/aws-go-lambda-dynamo/src/go.mod b/examples/aws-go-lambda-dynamo/src/go.mod deleted file mode 100644 index 9cde0324f9..0000000000 --- a/examples/aws-go-lambda-dynamo/src/go.mod +++ /dev/null @@ -1,28 +0,0 @@ -module sst-go-lambda-dynamo - -go 1.23.3 - -require ( - github.com/aws/aws-lambda-go v1.47.0 // indirect - github.com/aws/aws-sdk-go-v2 v1.32.7 // indirect - github.com/aws/aws-sdk-go-v2/config v1.28.7 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.17.48 // indirect - github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue v1.15.22 // indirect - github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression v1.7.57 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 // indirect - github.com/aws/aws-sdk-go-v2/service/dynamodb v1.38.1 // indirect - github.com/aws/aws-sdk-go-v2/service/dynamodbstreams v1.24.10 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.10.7 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 // indirect - github.com/aws/smithy-go v1.22.1 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/sst/sst/v3 v3.4.27 // indirect -) diff --git a/examples/aws-go-lambda-dynamo/src/go.sum b/examples/aws-go-lambda-dynamo/src/go.sum deleted file mode 100644 index 81468832e1..0000000000 --- a/examples/aws-go-lambda-dynamo/src/go.sum +++ /dev/null @@ -1,50 +0,0 @@ -github.com/aws/aws-lambda-go v1.47.0 h1:0H8s0vumYx/YKs4sE7YM0ktwL2eWse+kfopsRI1sXVI= -github.com/aws/aws-lambda-go v1.47.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= -github.com/aws/aws-sdk-go-v2 v1.32.7 h1:ky5o35oENWi0JYWUZkB7WYvVPP+bcRF5/Iq7JWSb5Rw= -github.com/aws/aws-sdk-go-v2 v1.32.7/go.mod h1:P5WJBrYqqbWVaOxgH0X/FYYD47/nooaPOZPlQdmiN2U= -github.com/aws/aws-sdk-go-v2/config v1.28.7 h1:GduUnoTXlhkgnxTD93g1nv4tVPILbdNQOzav+Wpg7AE= -github.com/aws/aws-sdk-go-v2/config v1.28.7/go.mod h1:vZGX6GVkIE8uECSUHB6MWAUsd4ZcG2Yq/dMa4refR3M= -github.com/aws/aws-sdk-go-v2/credentials v1.17.48 h1:IYdLD1qTJ0zanRavulofmqut4afs45mOWEI+MzZtTfQ= -github.com/aws/aws-sdk-go-v2/credentials v1.17.48/go.mod h1:tOscxHN3CGmuX9idQ3+qbkzrjVIx32lqDSU1/0d/qXs= -github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue v1.15.22 h1:p2LDiYhvM9mMExEY1meHMAmjmVlzD1J1jVG+fGut+mE= -github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue v1.15.22/go.mod h1:fo5T2fYMHVF2rHrym50h7Ue/+SECRJlUHUFZLjSX18g= -github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression v1.7.57 h1:5Pkmgr/HIgteZAXGHln1Y1X7wpI9+fyLe7T88utRRPk= -github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression v1.7.57/go.mod h1:bCsUt9VsF1M4bb3ZKnpq88rvvq/XxtBJSt6/QUZzIKU= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22 h1:kqOrpojG71DxJm/KDPO+Z/y1phm1JlC8/iT+5XRmAn8= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.22/go.mod h1:NtSFajXVVL8TA2QNngagVZmUtXciyrHOt7xgz4faS/M= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26 h1:I/5wmGMffY4happ8NOCuIUEWGUvvFp5NSeQcXl9RHcI= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.26/go.mod h1:FR8f4turZtNy6baO0KJ5FJUmXH/cSkI9fOngs0yl6mA= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26 h1:zXFLuEuMMUOvEARXFUVJdfqZ4bvvSgdGRq/ATcrQxzM= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.26/go.mod h1:3o2Wpy0bogG1kyOPrgkXA8pgIfEEv0+m19O9D5+W8y8= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 h1:VaRN3TlFdd6KxX1x3ILT5ynH6HvKgqdiXoTxAF4HQcQ= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1/go.mod h1:FbtygfRFze9usAadmnGJNc8KsP346kEe+y2/oyhGAGc= -github.com/aws/aws-sdk-go-v2/service/dynamodb v1.38.1 h1:AnSNs7Ogi0LXHPMDBx4RE7imU4/JmzWFziqkMKJA2AY= -github.com/aws/aws-sdk-go-v2/service/dynamodb v1.38.1/go.mod h1:J8xqRbx7HIc8ids2P8JbrKx9irONPEYq7Z1FpLDpi3I= -github.com/aws/aws-sdk-go-v2/service/dynamodbstreams v1.24.10 h1:aWEbNPNdGiTGSR6/Yy9S0Ad07sMVaT/CFaVq7GuDGx4= -github.com/aws/aws-sdk-go-v2/service/dynamodbstreams v1.24.10/go.mod h1:HywkMgYwY0uaybPvvctx6fkm3L1ssRKeGv7TPZ6OQ/M= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 h1:iXtILhvDxB6kPvEXgsDhGaZCSC6LQET5ZHSdJozeI0Y= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1/go.mod h1:9nu0fVANtYiAePIBh2/pFUSwtJ402hLnp854CNoDOeE= -github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.10.7 h1:EqGlayejoCRXmnVC6lXl6phCm9R2+k35e0gWsO9G5DI= -github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.10.7/go.mod h1:BTw+t+/E5F3ZnDai/wSOYM54WUVjSdewE7Jvwtb7o+w= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7 h1:8eUsivBQzZHqe/3FE+cqwfH+0p5Jo8PFM/QYQSmeZ+M= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.7/go.mod h1:kLPQvGUmxn/fqiCrDeohwG33bq2pQpGeY62yRO6Nrh0= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.8 h1:CvuUmnXI7ebaUAhbJcDy9YQx8wHR69eZ9I7q5hszt/g= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.8/go.mod h1:XDeGv1opzwm8ubxddF0cgqkZWsyOtw4lr6dxwmb6YQg= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7 h1:F2rBfNAL5UyswqoeWv9zs74N/NanhK16ydHW1pahX6E= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.7/go.mod h1:JfyQ0g2JG8+Krq0EuZNnRwX0mU0HrwY/tG6JNfcqh4k= -github.com/aws/aws-sdk-go-v2/service/sts v1.33.3 h1:Xgv/hyNgvLda/M9l9qxXc4UFSgppnRczLxlMs5Ae/QY= -github.com/aws/aws-sdk-go-v2/service/sts v1.33.3/go.mod h1:5Gn+d+VaaRgsjewpMvGazt0WfcFO+Md4wLOuBfGR9Bc= -github.com/aws/smithy-go v1.22.1 h1:/HPHZQ0g7f4eUeK6HKglFz8uwVfZKgoI25rb/J+dnro= -github.com/aws/smithy-go v1.22.1/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sst/sst/v3 v3.4.27 h1:LRPqw1HRhLZQ8EoL8rXacOkavZlf1k/Am8CZ0uEdMXg= -github.com/sst/sst/v3 v3.4.27/go.mod h1:rxQ4Pi7xaYAbyfLt0rFREzQDLE72clWKxudGKG9Xpt4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/examples/aws-go-lambda-dynamo/src/handlers/handlers.go b/examples/aws-go-lambda-dynamo/src/handlers/handlers.go deleted file mode 100644 index 9a5f742d8d..0000000000 --- a/examples/aws-go-lambda-dynamo/src/handlers/handlers.go +++ /dev/null @@ -1,118 +0,0 @@ -package handlers - -import ( - "context" - "encoding/json" - "net/http" - "sst-go-lambda-dynamo/models" - "sst-go-lambda-dynamo/repository" - - "github.com/aws/aws-lambda-go/events" -) - -type Handlers struct { - userRepo repository.UserRepository -} - -func NewHandlers(userRepo repository.UserRepository) *Handlers { - return &Handlers{userRepo: userRepo} -} - -func (h *Handlers) GetUser(ctx context.Context, r events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error) { - - queryString := r.QueryStringParameters - if queryString == nil { - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusBadRequest, - Body: `{"message": "Missing query string"}`, - }, nil - } - - id := queryString["id"] - - user, err := h.userRepo.GetUser(ctx, id) - if err != nil { - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusNotFound, - Body: `{"message": "User not found"}`, - }, nil - } - - userJSON, err := json.Marshal(user) - if err != nil { - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusInternalServerError, - Body: `{"message": "Failed to marshal user"}`, - }, err - } - - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusOK, - Body: string(userJSON), - }, nil -} - -type PostUserRequestData struct { - Name string `json:"name"` - Email string `json:"email"` -} - -func (h *Handlers) CreateUser(ctx context.Context, r events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error) { - - var data PostUserRequestData - if err := json.Unmarshal([]byte(r.Body), &data); err != nil { - return events.LambdaFunctionURLResponse{ - StatusCode: 400, - Body: `{"message": "Invalid request body"}`, - }, err - } - - user, err := h.userRepo.CreateUser(ctx, models.UserCreate{ - Name: data.Name, - Email: data.Email, - }) - if err != nil { - return events.LambdaFunctionURLResponse{ - StatusCode: 500, - Body: `{"message": "Failed to create user"}`, - }, err - } - - userJSON, err := json.Marshal(user) - if err != nil { - return events.LambdaFunctionURLResponse{ - StatusCode: 500, - Body: `{"message": "Failed to marshal user"}`, - }, err - } - - return events.LambdaFunctionURLResponse{ - StatusCode: 201, - Body: string(userJSON), - }, nil -} - -func (h *Handlers) DeleteUser(ctx context.Context, r events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error) { - - queryString := r.QueryStringParameters - if queryString == nil { - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusBadRequest, - Body: `{"message": "Missing query string"}`, - }, nil - } - - id := queryString["id"] - - if err := h.userRepo.DeleteUser(ctx, id); err != nil { - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusInternalServerError, - Body: `{"message": "Failed to delete user"}`, - }, err - } - - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusOK, - Body: `{"message": "User deleted"}`, - }, nil -} diff --git a/examples/aws-go-lambda-dynamo/src/main.go b/examples/aws-go-lambda-dynamo/src/main.go deleted file mode 100644 index 59d8e6270d..0000000000 --- a/examples/aws-go-lambda-dynamo/src/main.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "context" - "net/http" - "os" - "sst-go-lambda-dynamo/handlers" - "sst-go-lambda-dynamo/repository" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/dynamodb" - "github.com/sst/sst/v3/sdk/golang/resource" -) - -type App struct { - handlers *handlers.Handlers -} - -func NewApp() *App { - cfg, err := config.LoadDefaultConfig(context.Background(), func(opts *config.LoadOptions) error { - // example of setting region from environment variable - opts.Region = os.Getenv("AWS_REGION") - return nil - }) - if err != nil { - panic(err) - } - client := dynamodb.NewFromConfig(cfg) - - tableName, err := resource.Get("Table", "name") - if err != nil { - panic(err) - } - - userRepo := repository.NewDynamoDBRepository(client, tableName.(string)) - handlers := handlers.NewHandlers(userRepo) - - return &App{handlers: handlers} -} - -func (app *App) handler(ctx context.Context, r events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error) { - switch r.RequestContext.HTTP.Method { - case http.MethodGet: - return app.handlers.GetUser(ctx, r) - case http.MethodPost: - return app.handlers.CreateUser(ctx, r) - case http.MethodDelete: - return app.handlers.DeleteUser(ctx, r) - default: - return events.LambdaFunctionURLResponse{ - StatusCode: http.StatusMethodNotAllowed, - Headers: map[string]string{"Content-Type": "application/json"}, - Body: `{"message": "Method Not Allowed"}`, - }, nil - } -} - -func main() { - app := NewApp() - lambda.Start(app.handler) -} diff --git a/examples/aws-go-lambda-dynamo/src/models/user.go b/examples/aws-go-lambda-dynamo/src/models/user.go deleted file mode 100644 index addac21e76..0000000000 --- a/examples/aws-go-lambda-dynamo/src/models/user.go +++ /dev/null @@ -1,18 +0,0 @@ -package models - -import ( - "time" -) - -type User struct { - ID string `json:"id" dynamodbav:"id"` - Name string `json:"name" dynamodbav:"name"` - Email string `json:"email" dynamodbav:"email"` - CreatedAt time.Time `json:"created_at" dynamodbav:"created_at"` - UpdatedAt time.Time `json:"updated_at" dynamodbav:"updated_at"` -} - -type UserCreate struct { - Name string - Email string -} diff --git a/examples/aws-go-lambda-dynamo/src/repository/dynamodb.go b/examples/aws-go-lambda-dynamo/src/repository/dynamodb.go deleted file mode 100644 index 062b0b7135..0000000000 --- a/examples/aws-go-lambda-dynamo/src/repository/dynamodb.go +++ /dev/null @@ -1,126 +0,0 @@ -package repository - -import ( - "context" - "fmt" - "sst-go-lambda-dynamo/models" - "time" - - "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" - "github.com/aws/aws-sdk-go-v2/service/dynamodb" - "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" - "github.com/google/uuid" -) - -type DynamoUser struct { - models.User - PK string `dynamodbav:"PK"` - SK string `dynamodbav:"SK"` - TYPE string `dynamodbav:"TYPE"` -} - -func getKey(id string) (map[string]types.AttributeValue, error) { - return attributevalue.MarshalMap(map[string]string{ - "PK": "USER#" + id, - "SK": "USER#" + id, - }) -} - -func formatTo(u models.User) DynamoUser { - return DynamoUser{ - User: u, - PK: "USER#" + u.ID, - SK: "USER#" + u.ID, - TYPE: "USER", - } -} - -func formatFrom(item map[string]types.AttributeValue) (models.User, error) { - var user models.User - err := attributevalue.UnmarshalMap(item, &user) - return user, err -} - -type DynamoDBRepository struct { - client *dynamodb.Client - tableName string -} - -func NewDynamoDBRepository(client *dynamodb.Client, tableName string) UserRepository { - return &DynamoDBRepository{ - client: client, - tableName: tableName, - } -} - -func (r *DynamoDBRepository) GetUser(ctx context.Context, id string) (*models.User, error) { - key, err := getKey(id) - if err != nil { - return nil, fmt.Errorf("failed to get key: %w", err) - } - output, err := r.client.GetItem(ctx, &dynamodb.GetItemInput{ - TableName: &r.tableName, - Key: key, - }) - if err != nil { - return nil, fmt.Errorf("failed to get user: %w", err) - } - - if output.Item == nil { - return nil, fmt.Errorf("user not found") - } - - user, err := formatFrom(output.Item) - if err != nil { - return nil, fmt.Errorf("failed to format user: %w", err) - } - - return &user, nil -} - -func (r *DynamoDBRepository) CreateUser(ctx context.Context, user models.UserCreate) (*models.User, error) { - - id, err := uuid.NewV7() - if err != nil { - return nil, fmt.Errorf("failed to generate id: %w", err) - } - now := time.Now() - newUser := models.User{ - ID: id.String(), - Name: user.Name, - Email: user.Email, - CreatedAt: now, - UpdatedAt: now, - } - - dynamoUser := formatTo(newUser) - item, err := attributevalue.MarshalMap(dynamoUser) - if err != nil { - return nil, fmt.Errorf("failed to marshal user: %w", err) - } - _, err = r.client.PutItem(ctx, &dynamodb.PutItemInput{ - TableName: &r.tableName, - Item: item, - }) - if err != nil { - return nil, fmt.Errorf("failed to put user: %w", err) - } - - return &newUser, nil -} - -func (r *DynamoDBRepository) DeleteUser(ctx context.Context, id string) error { - key, err := getKey(id) - if err != nil { - return fmt.Errorf("failed to get key: %w", err) - } - - _, err = r.client.DeleteItem(ctx, &dynamodb.DeleteItemInput{ - TableName: &r.tableName, - Key: key, - }) - if err != nil { - return fmt.Errorf("failed to delete user: %w", err) - } - return nil -} diff --git a/examples/aws-go-lambda-dynamo/src/repository/repository.go b/examples/aws-go-lambda-dynamo/src/repository/repository.go deleted file mode 100644 index 5c6ee70503..0000000000 --- a/examples/aws-go-lambda-dynamo/src/repository/repository.go +++ /dev/null @@ -1,12 +0,0 @@ -package repository - -import ( - "context" - "sst-go-lambda-dynamo/models" -) - -type UserRepository interface { - GetUser(ctx context.Context, id string) (*models.User, error) - CreateUser(ctx context.Context, user models.UserCreate) (*models.User, error) - DeleteUser(ctx context.Context, id string) error -} diff --git a/examples/aws-go-lambda-dynamo/sst.config.ts b/examples/aws-go-lambda-dynamo/sst.config.ts deleted file mode 100644 index d1c97887bc..0000000000 --- a/examples/aws-go-lambda-dynamo/sst.config.ts +++ /dev/null @@ -1,69 +0,0 @@ -/// - -/** - * ## AWS Lambda Go DynamoDB - * - * An example on how to use a Go runtime Lambda with DynamoDB. - * - * You configure the DynamoDB client. - * - * ```go title="src/main.go" - * import ( - * "github.com/sst/sst/v3/sdk/golang/resource" - * ) - * - * func main() { - * cfg, err := config.LoadDefaultConfig(context.Background()) - * if err != nil { - * panic(err) - * } - * client := dynamodb.NewFromConfig(cfg) - * - * - * tableName, err := resource.Get("Table", "name") - * if err != nil { - * panic(err) - * } - * } - * ``` - * - * And make a request to DynamoDB. - * - * ```go title="src/main.go" - * _, err = r.client.PutItem(ctx, &dynamodb.PutItemInput{ - * TableName: tableName.(string), - * Item: item, - * }) - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-go-lambda-dynamo", - removal: "remove", - home: "aws", - providers: { - aws: { - region: "us-east-2", - }, - }, - }; - }, - async run() { - const table = new sst.aws.Dynamo("Table", { - fields: { - PK: "string", - SK: "string", - }, - primaryIndex: { hashKey: "PK", rangeKey: "SK" }, - }); - - new sst.aws.Function("GoFunction", { - url: true, - runtime: "go", - handler: "./src", - link: [table], - }); - }, -}); diff --git a/examples/aws-go-lambda-dynamo/tsconfig.json b/examples/aws-go-lambda-dynamo/tsconfig.json deleted file mode 100644 index fdc4236bd1..0000000000 --- a/examples/aws-go-lambda-dynamo/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "compilerOptions": { - //Enable latest features - "lib": ["ESNext"], - "target": "ESNext", - "module": "ESNext", - "moduleDetection": "force", - "jsx": "react-jsx", - "allowJs": true, - - // Bundler mode - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "noEmit": true, - - // Best practices - "strict": true, - "skipLibCheck": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedIndexedAccess": true, - "noImplicitOverride": true, - - // Some stricter flags (disabled by default) - "noUnusedLocals": false, - "noUnusedParameters": false, - "noPropertyAccessFromIndexSignature": false - } -} diff --git a/examples/aws-hono-container/.dockerignore b/examples/aws-hono-container/.dockerignore deleted file mode 100644 index 5eae331bf4..0000000000 --- a/examples/aws-hono-container/.dockerignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -.git - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-hono-container/.gitignore b/examples/aws-hono-container/.gitignore deleted file mode 100644 index 349b782160..0000000000 --- a/examples/aws-hono-container/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -# dev -.yarn/ -!.yarn/releases -.vscode/* -!.vscode/launch.json -!.vscode/*.code-snippets -.idea/workspace.xml -.idea/usage.statistics.xml -.idea/shelf - -# deps -node_modules/ - -# env -.env -.env.production - -# logs -logs/ -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -# misc -.DS_Store - -# sst -.sst diff --git a/examples/aws-hono-container/Dockerfile b/examples/aws-hono-container/Dockerfile deleted file mode 100644 index 84684fd82a..0000000000 --- a/examples/aws-hono-container/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM node:lts-alpine AS base - -FROM base AS builder -RUN apk add --no-cache gcompat -WORKDIR /app -COPY package*json tsconfig.json src ./ -# Copy over generated types -COPY sst-env.d.ts* ./ -RUN npm ci && \ - npm run build && \ - npm prune --production - -FROM base AS runner -WORKDIR /app -RUN addgroup --system --gid 1001 nodejs -RUN adduser --system --uid 1001 hono -COPY --from=builder --chown=hono:nodejs /app/node_modules /app/node_modules -COPY --from=builder --chown=hono:nodejs /app/dist /app/dist -COPY --from=builder --chown=hono:nodejs /app/package.json /app/package.json - -USER hono -EXPOSE 3000 -CMD ["node", "/app/dist/index.js"] diff --git a/examples/aws-hono-container/package.json b/examples/aws-hono-container/package.json deleted file mode 100644 index 565f26f302..0000000000 --- a/examples/aws-hono-container/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-hono-container", - "type": "module", - "scripts": { - "dev": "tsx watch src/index.ts", - "build": "tsc" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/lib-storage": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "@hono/node-server": "^1.13.7", - "hono": "^4.6.12", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.146", - "@types/node": "^20.11.17", - "tsx": "^4.7.1", - "typescript": "^5.7.2" - } -} diff --git a/examples/aws-hono-container/src/index.ts b/examples/aws-hono-container/src/index.ts deleted file mode 100644 index 30af78b446..0000000000 --- a/examples/aws-hono-container/src/index.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { serve } from '@hono/node-server' -import { Hono } from 'hono' -import { Resource } from 'sst' -import { - S3Client, - GetObjectCommand, - ListObjectsV2Command, -} from '@aws-sdk/client-s3' -import { Upload } from '@aws-sdk/lib-storage' -import { getSignedUrl } from '@aws-sdk/s3-request-presigner' - -const s3 = new S3Client(); - -const app = new Hono() - -app.get('/', (c) => { - return c.text('Hello Hono!') -}) - -app.post('/', async (c) => { - const body = await c.req.parseBody(); - const file = body['file'] as File; - - const params = { - Bucket: Resource.MyBucket.name, - ContentType: file.type, - Key: file.name, - Body: file, - }; - const upload = new Upload({ - params, - client: s3, - }); - await upload.done(); - - return c.text('File uploaded successfully.'); -}); - -app.get('/latest', async (c) => { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0), - )[0]; - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - return c.redirect(await getSignedUrl(s3, command)); -}); - -const port = 3000 -console.log(`Server is running on http://localhost:${port}`) - -serve({ - fetch: app.fetch, - port -}) diff --git a/examples/aws-hono-container/sst.config.ts b/examples/aws-hono-container/sst.config.ts deleted file mode 100644 index 67b166954e..0000000000 --- a/examples/aws-hono-container/sst.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-hono-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-hono-container/tsconfig.json b/examples/aws-hono-container/tsconfig.json deleted file mode 100644 index b55223e0d5..0000000000 --- a/examples/aws-hono-container/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "NodeNext", - "strict": true, - "verbatimModuleSyntax": true, - "skipLibCheck": true, - "types": [ - "node" - ], - "jsx": "react-jsx", - "jsxImportSource": "hono/jsx", - "outDir": "./dist" - }, - "exclude": ["node_modules"] -} diff --git a/examples/aws-hono-redis/.dockerignore b/examples/aws-hono-redis/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-hono-redis/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-hono-redis/.gitignore b/examples/aws-hono-redis/.gitignore deleted file mode 100644 index 349b782160..0000000000 --- a/examples/aws-hono-redis/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -# dev -.yarn/ -!.yarn/releases -.vscode/* -!.vscode/launch.json -!.vscode/*.code-snippets -.idea/workspace.xml -.idea/usage.statistics.xml -.idea/shelf - -# deps -node_modules/ - -# env -.env -.env.production - -# logs -logs/ -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -# misc -.DS_Store - -# sst -.sst diff --git a/examples/aws-hono-redis/Dockerfile b/examples/aws-hono-redis/Dockerfile deleted file mode 100644 index e63bc0b843..0000000000 --- a/examples/aws-hono-redis/Dockerfile +++ /dev/null @@ -1,30 +0,0 @@ -FROM node:20-alpine AS base - -FROM base AS builder - -RUN apk add --no-cache gcompat -WORKDIR /app - -COPY package*json tsconfig.json src ./ - -# Copy over generated types -COPY sst-env.d.ts* ./ - -RUN npm ci && \ - npm run build && \ - npm prune --production - -FROM base AS runner -WORKDIR /app - -RUN addgroup --system --gid 1001 nodejs -RUN adduser --system --uid 1001 hono - -COPY --from=builder --chown=hono:nodejs /app/node_modules /app/node_modules -COPY --from=builder --chown=hono:nodejs /app/dist /app/dist -COPY --from=builder --chown=hono:nodejs /app/package.json /app/package.json - -USER hono -EXPOSE 3000 - -CMD ["node", "/app/dist/index.js"] diff --git a/examples/aws-hono-redis/package.json b/examples/aws-hono-redis/package.json deleted file mode 100644 index 7048149d5a..0000000000 --- a/examples/aws-hono-redis/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-hono-redis", - "type": "module", - "scripts": { - "build": "tsc", - "dev": "tsx watch src/index.ts" - }, - "dependencies": { - "@hono/node-server": "^1.13.2", - "hono": "^4.6.5", - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "@types/node": "^20.11.17", - "tsx": "^4.7.1", - "typescript": "^5.6.3" - } -} diff --git a/examples/aws-hono-redis/src/index.ts b/examples/aws-hono-redis/src/index.ts deleted file mode 100644 index eb89ae5adc..0000000000 --- a/examples/aws-hono-redis/src/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Hono } from "hono"; -import { Resource } from "sst"; -import { Cluster } from "ioredis"; -import { serve } from "@hono/node-server"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - }, -); - -const app = new Hono(); - -app.get("/", async (c) => { - const counter = await redis.incr("counter"); - return c.text(`Hit counter: ${counter}`); -}); - -const port = 3000; -console.log(`Server is running on port ${port}`); - -serve({ - fetch: app.fetch, - port, -}); diff --git a/examples/aws-hono-redis/sst.config.ts b/examples/aws-hono-redis/sst.config.ts deleted file mode 100644 index d39e5dcf86..0000000000 --- a/examples/aws-hono-redis/sst.config.ts +++ /dev/null @@ -1,97 +0,0 @@ -/// - -/** - * ## AWS Hono container with Redis - * - * Creates a hit counter app with Hono and Redis. - * - * This deploys Hono API as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {2} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "npm run dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:3000` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it by: - - * 1. Using the `Dockerfile` that's included in this example. - * - * 2. This compiles our TypeScript file, so we'll need add the following to the `tsconfig.json`. - * - * ```diff lang="json" title="tsconfig.json" {4,6} - * { - * "compilerOptions": { - * // ... - * + "outDir": "./dist" - * }, - * + "exclude": ["node_modules"] - * } - * ``` - * - * 3. Install TypeScript. - * - * ```bash - * npm install typescript --save-dev - * ``` - * - * 3. And add a `build` script to our `package.json`. - * - * ```diff lang="json" title="package.json" - * "scripts": { - * // ... - * + "build": "tsc" - * } - * ``` - * And finally, running `npx sst deploy --stage production`. - */ -export default $config({ - app(input) { - return { - name: "aws-hono-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-hono-redis/tsconfig.json b/examples/aws-hono-redis/tsconfig.json deleted file mode 100644 index 25d91658cc..0000000000 --- a/examples/aws-hono-redis/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "NodeNext", - "strict": true, - "outDir": "./dist", - "verbatimModuleSyntax": true, - "skipLibCheck": true, - "types": [ - "node" - ], - "jsx": "react-jsx", - "jsxImportSource": "hono/jsx", - }, - "exclude": ["node_modules"] -} diff --git a/examples/aws-hono-stream/.gitignore b/examples/aws-hono-stream/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-hono-stream/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-hono-stream/index.ts b/examples/aws-hono-stream/index.ts deleted file mode 100644 index 5a9239a382..0000000000 --- a/examples/aws-hono-stream/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Hono } from "hono"; -import { streamText } from "hono/streaming"; -import { streamHandle } from "hono/aws-lambda"; - -const app = new Hono() - .get("/", (c) => { - return streamText(c, async (stream) => { - await stream.writeln("Hello"); - await stream.sleep(3000); - await stream.writeln("World"); - }) - }); - -export const handler = streamHandle(app); diff --git a/examples/aws-hono-stream/package.json b/examples/aws-hono-stream/package.json deleted file mode 100644 index 51c7dd4fe7..0000000000 --- a/examples/aws-hono-stream/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-hono-stream", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "hono": "^4.6.2", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-hono-stream/sst.config.ts b/examples/aws-hono-stream/sst.config.ts deleted file mode 100644 index 005d16ee1a..0000000000 --- a/examples/aws-hono-stream/sst.config.ts +++ /dev/null @@ -1,46 +0,0 @@ -/// - -/** - * ## AWS Hono streaming - * - * An example on how to enable streaming for Lambda functions using Hono. - * - * ```ts title="sst.config.ts" - * { - * streaming: true - * } - * ``` - * - * ```ts title="index.ts" - * export const handler = streamHandle(app); - * ``` - * - * To test this in your terminal, use the `curl` command with the `--no-buffer` option. - * - * ```bash "--no-buffer" - * curl --no-buffer https://u3dyblk457ghskwbmzrbylpxoi0ayrbb.lambda-url.us-east-1.on.aws - * ``` - * - * Streaming is also supported through API Gateway REST API. - * - */ -export default $config({ - app(input) { - return { - name: "aws-hono-stream", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const hono = new sst.aws.Function("Hono", { - url: true, - streaming: true, - timeout: "15 minutes", - handler: "index.handler", - }); - return { - api: hono.url, - }; - }, -}); diff --git a/examples/aws-hono-stream/tsconfig.json b/examples/aws-hono-stream/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-hono-stream/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-hono/.gitignore b/examples/aws-hono/.gitignore deleted file mode 100644 index c84fd38455..0000000000 --- a/examples/aws-hono/.gitignore +++ /dev/null @@ -1,35 +0,0 @@ -# prod -dist/ -lambda.zip - -# dev -.yarn/ -!.yarn/releases -.vscode/* -!.vscode/launch.json -!.vscode/*.code-snippets -.idea/workspace.xml -.idea/usage.statistics.xml -.idea/shelf - -# deps -node_modules/ - -# env -.env -.env.production - -# logs -logs/ -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -# misc -.DS_Store - -# sst -.sst diff --git a/examples/aws-hono/package.json b/examples/aws-hono/package.json deleted file mode 100644 index 6ed2c8e0c7..0000000000 --- a/examples/aws-hono/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-hono", - "type": "module", - "scripts": { - "build": "esbuild --bundle --outfile=./dist/index.js --platform=node --target=node20 ./src/index.ts", - "deploy": "run-s build zip update", - "update": "aws lambda update-function-code --zip-file fileb://lambda.zip --function-name hello", - "zip": "zip -j lambda.zip dist/index.js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.146", - "esbuild": "^0.21.4", - "npm-run-all2": "^6.2.0" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "hono": "^4.6.12", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-hono/src/index.ts b/examples/aws-hono/src/index.ts deleted file mode 100644 index cb7ac2f0ae..0000000000 --- a/examples/aws-hono/src/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Hono } from "hono"; -import { handle } from "hono/aws-lambda"; -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { - S3Client, - GetObjectCommand, - PutObjectCommand, - ListObjectsV2Command, -} from "@aws-sdk/client-s3"; - -const s3 = new S3Client(); - -const app = new Hono(); - -app.get("/", async (c) => { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - - return c.text(await getSignedUrl(s3, command)); -}); - -app.get("/latest", async (c) => { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - - const latestFile = objects.Contents!.sort( - (a, b) => - (b.LastModified?.getTime() ?? 0) - (a.LastModified?.getTime() ?? 0), - )[0]; - - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - - return c.redirect(await getSignedUrl(s3, command)); -}); - -export const handler = handle(app); diff --git a/examples/aws-hono/sst.config.ts b/examples/aws-hono/sst.config.ts deleted file mode 100644 index 2c9f1db7b1..0000000000 --- a/examples/aws-hono/sst.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-hono", - removal: input?.stage === "production" ? "retain" : "remove", - protect: input?.stage === "production", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket"); - new sst.aws.Function("Hono", { - url: true, - link: [bucket], - handler: "src/index.handler", - }); - }, -}); diff --git a/examples/aws-hono/tsconfig.json b/examples/aws-hono/tsconfig.json deleted file mode 100644 index 667b7e7e6d..0000000000 --- a/examples/aws-hono/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "Bundler", - "strict": true, - "skipLibCheck": true, - "types": [ - "node" - ], - "jsx": "react-jsx", - "jsxImportSource": "hono/jsx", - } -} \ No newline at end of file diff --git a/examples/aws-iam-permission-boundary/index.ts b/examples/aws-iam-permission-boundary/index.ts deleted file mode 100644 index 09995bf3ca..0000000000 --- a/examples/aws-iam-permission-boundary/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3"; -import { SQSClient, ListQueuesCommand } from "@aws-sdk/client-sqs"; -const s3 = new S3Client(); -const sqs = new SQSClient(); - -export const handler = async () => { - const response = []; - - // List buckets - try { - await s3.send(new ListBucketsCommand()); - response.push("s3:ListBuckets - success"); - } catch (e: any) { - response.push(`s3:ListBuckets - failed (${e.message})`); - } - - // List queues - try { - await sqs.send(new ListQueuesCommand()); - response.push("sqs:ListQueues - success"); - } catch (e: any) { - response.push(`sqs:ListQueues - failed (${e.message})`); - } - - return { - statusCode: 200, - body: `
${JSON.stringify(response, null, 2)}
`, - }; -}; diff --git a/examples/aws-iam-permission-boundary/package.json b/examples/aws-iam-permission-boundary/package.json deleted file mode 100644 index 347231b033..0000000000 --- a/examples/aws-iam-permission-boundary/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-iam-permission-boundary", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-s3": "^3.564.0", - "@aws-sdk/client-sqs": "^3.564.0" - } -} diff --git a/examples/aws-iam-permission-boundary/sst.config.ts b/examples/aws-iam-permission-boundary/sst.config.ts deleted file mode 100644 index 953b39ad0a..0000000000 --- a/examples/aws-iam-permission-boundary/sst.config.ts +++ /dev/null @@ -1,61 +0,0 @@ -/// - -/** - * ## IAM permissions boundaries - * - * Use permissions boundaries to set the maximum permissions for all IAM roles that'll be - * created in your app. - * - * In this example, the Function has the `s3:ListAllMyBuckets` and `sqs:ListQueues` - * permissions. However, we create a permissions boundary that only allows `s3:ListAllMyBuckets`. - * And we apply it to all Roles in the app using the global - * [`$transform`](/docs/reference/global/#transform). - * - * As a result, the Function is only allowed to list S3 buckets. If you open the deployed URL, - * you'll see that the SQS list call fails. - * - * Learn more about [AWS IAM permissions boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html). - */ -export default $config({ - app(input) { - return { - name: "aws-iam-permission-boundary", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - // Create a permission boundary - const permissionsBoundary = new aws.iam.Policy("MyPermissionsBoundary", { - policy: aws.iam.getPolicyDocumentOutput({ - statements: [ - { - actions: ["s3:ListAllMyBuckets"], - resources: ["*"], - }, - ], - }).json, - }); - - // Apply the boundary to all roles - $transform(aws.iam.Role, (args) => { - args.permissionsBoundary = permissionsBoundary; - }); - - // The boundary automatically applies to this Function's role - const app = new sst.aws.Function("MyApp", { - handler: "index.handler", - permissions: [ - { - actions: ["s3:ListAllMyBuckets", "sqs:ListQueues"], - resources: ["*"], - }, - ], - url: true, - }); - - return { - app: app.url, - }; - }, -}); diff --git a/examples/aws-import/.gitignore b/examples/aws-import/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-import/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-import/package.json b/examples/aws-import/package.json deleted file mode 100644 index 62f02b1660..0000000000 --- a/examples/aws-import/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-import", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-import/sst.config.ts b/examples/aws-import/sst.config.ts deleted file mode 100644 index c8d3b84e1e..0000000000 --- a/examples/aws-import/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -/** - * ## Import existing resource - * - * Import an existing AWS resource using the `transform` option with `opts.import`. - */ -export default $config({ - app(input) { - return { - name: "aws-import", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Bucket("MyBucket", { - transform: { - bucket(args, opts) { - opts.import = "aws-import-my-bucket"; - args.bucket = "aws-import-my-bucket"; - args.forceDestroy = undefined; - }, - }, - }); - }, -}); diff --git a/examples/aws-import/tsconfig.json b/examples/aws-import/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-import/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-info/package.json b/examples/aws-info/package.json deleted file mode 100644 index 9802a5872a..0000000000 --- a/examples/aws-info/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-info", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-info/sst.config.ts b/examples/aws-info/sst.config.ts deleted file mode 100644 index 3c09c1ee88..0000000000 --- a/examples/aws-info/sst.config.ts +++ /dev/null @@ -1,25 +0,0 @@ -/// - -/** - * ## Current AWS account - * - * You can use the `aws.getXXXXOutput()` provider functions to get info about the current - * AWS account. - * Learn more about [provider functions](/docs/providers/#functions). - */ -export default $config({ - app(input) { - return { - name: "aws-info", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - return { - region: aws.getRegionOutput().region, - account: aws.getCallerIdentityOutput({}).accountId, - }; - }, -}); - diff --git a/examples/aws-jsx-email/.gitignore b/examples/aws-jsx-email/.gitignore deleted file mode 100644 index fccbe3fea3..0000000000 --- a/examples/aws-jsx-email/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -node_modules - -# env -.env - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* -.pnpm-debug.log* - -# sst -.sst diff --git a/examples/aws-jsx-email/index.ts b/examples/aws-jsx-email/index.ts deleted file mode 100644 index 907afeca8b..0000000000 --- a/examples/aws-jsx-email/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Resource } from "sst"; -import { render } from "jsx-email"; -import { Template } from "./templates/email"; -import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2"; - -const client = new SESv2Client(); - -export const handler = async () => { - await client.send( - new SendEmailCommand({ - FromEmailAddress: Resource.MyEmail.sender, - Destination: { - ToAddresses: [Resource.MyEmail.sender], - }, - Content: { - Simple: { - Subject: { - Data: "Hello World!", - }, - Body: { - Html: { - Data: await render(Template({ - email: "spongebob@example.com", - name: "Spongebob Squarepants" - })), - }, - }, - }, - }, - }) - ); - - return { - statusCode: 200, - body: "Sent!" - }; -}; diff --git a/examples/aws-jsx-email/package.json b/examples/aws-jsx-email/package.json deleted file mode 100644 index 25b27b978c..0000000000 --- a/examples/aws-jsx-email/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-jsx-email", - "version": "0.0.0", - "private": true, - "description": "A simple starter for jsx-email", - "scripts": { - "build": "email build ./templates", - "create": "email create", - "dev": "email preview ./templates" - }, - "dependencies": { - "@aws-sdk/client-sesv2": "^3.651.1", - "jsx-email": "^1.10.11", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "@types/react": "^18.2.0", - "react": "^18.2.0", - "typescript": "^5.2.2" - } -} diff --git a/examples/aws-jsx-email/sst.config.ts b/examples/aws-jsx-email/sst.config.ts deleted file mode 100644 index a17fd32f97..0000000000 --- a/examples/aws-jsx-email/sst.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// - -/** - * ## AWS JSX Email - * - * Uses [JSX Email](https://jsx.email) and the `Email` component to design and send emails. - * - * To test this example, change the `sst.config.ts` to use your own email address. - * - * ```ts title="sst.config.ts" - * sender: "email@example.com" - * ``` - * - * Then run. - * - * ```bash - * npm install - * npx sst dev - * ``` - * - * You'll get an email from AWS asking you to confirm your email address. Click the link to - * verify it. - * - * Next, go to the URL in the `sst dev` CLI output. You should now receive an email rendered - * using JSX Email. - * - * ```ts title="index.ts" - * import { Template } from "./templates/email"; - * - * await render(Template({ - * email: "spongebob@example.com", - * name: "Spongebob Squarepants" - * })) - * ``` - * - * Once you are ready to go to production, you can: - * - * - [Request production access](https://docs.aws.amazon.com/ses/latest/dg/request-production-access.html) for SES - * - And [use your domain](/docs/component/aws/email/) to send emails - */ -export default $config({ - app(input) { - return { - name: "aws-jsx-email", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const email = new sst.aws.Email("MyEmail", { - sender: "email@example.com", - }); - const api = new sst.aws.Function("MyApi", { - handler: "index.handler", - link: [email], - url: true, - }); - - return { - api: api.url, - }; - }, -}); diff --git a/examples/aws-jsx-email/templates/email.tsx b/examples/aws-jsx-email/templates/email.tsx deleted file mode 100644 index 4c4591a9e9..0000000000 --- a/examples/aws-jsx-email/templates/email.tsx +++ /dev/null @@ -1,96 +0,0 @@ -import { - Body, - Button, - Container, - Head, - Hr, - Html, - Link, - Preview, - Section, - Text -} from 'jsx-email'; - - -export type TemplateProps = { - email: string; - name: string; -} - -const main = { - backgroundColor: '#f6f9fc', - fontFamily: - '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Ubuntu,sans-serif' -}; - -const container = { - backgroundColor: '#ffffff', - margin: '0 auto', - marginBottom: '64px', - padding: '20px 0 48px' -}; - -const box = { - padding: '0 48px' -}; - -const hr = { - borderColor: '#e6ebf1', - margin: '20px 0' -}; - -const paragraph = { - color: '#777', - fontSize: '16px', - lineHeight: '24px', - textAlign: 'left' as const -}; - -const anchor = { - color: '#777' -}; - -const button = { - backgroundColor: 'coral', - borderRadius: '5px', - color: '#fff', - display: 'block', - fontSize: '16px', - fontWeight: 'bold', - textAlign: 'center' as const, - textDecoration: 'none', - width: '100%', - padding: '10px' -}; - -export const defaultProps = { - email: 'batman@example.com', - name: 'Bruce Wayne' -} as TemplateProps; - -export const templateName = 'aws-jsx-email'; - -export const Template = ({ email, name }: TemplateProps) => ( - - - This is our email preview text for {name} <{email}> - - -
- This is our email body text - -
- - This is text content with a{' '} - - link - - . - -
-
- - -); diff --git a/examples/aws-jsx-email/tsconfig.json b/examples/aws-jsx-email/tsconfig.json deleted file mode 100644 index b49214f869..0000000000 --- a/examples/aws-jsx-email/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "declaration": true, - "declarationMap": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "lib": ["ES2023"], - "module": "ESNext", - "moduleResolution": "node", - "noEmitOnError": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "preserveSymlinks": true, - "preserveWatchOutput": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "strict": true, - "strictNullChecks": true, - "target": "ESNext" - }, - "exclude": ["**/dist", "**/node_modules", "sst.config.ts"], - "include": ["templates", "index.ts", "sst-env.d.ts"] -} diff --git a/examples/aws-kinesis-stream/package.json b/examples/aws-kinesis-stream/package.json deleted file mode 100644 index 5cf5cc605b..0000000000 --- a/examples/aws-kinesis-stream/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-kinesis-stream", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "sst": "file:../../sdk/js" - }, - "dependencies": { - "@aws-sdk/client-kinesis": "^3.598.0" - } -} diff --git a/examples/aws-kinesis-stream/publisher.ts b/examples/aws-kinesis-stream/publisher.ts deleted file mode 100644 index 1ef13cba14..0000000000 --- a/examples/aws-kinesis-stream/publisher.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { KinesisClient, PutRecordsCommand } from "@aws-sdk/client-kinesis"; -import { Resource } from "sst"; - -export const handler = async (event) => { - const client = new KinesisClient(); - - await client.send( - new PutRecordsCommand({ - Records: [ - { - Data: JSON.stringify({ type: "foo" }), - PartitionKey: "1", - }, - { - Data: JSON.stringify({ type: "bar" }), - PartitionKey: "1", - }, - ], - StreamName: Resource.MyStream.name, - }) - ); - - return { - statusCode: 200, - body: JSON.stringify({ status: "sent" }, null, 2), - }; -}; diff --git a/examples/aws-kinesis-stream/sst.config.ts b/examples/aws-kinesis-stream/sst.config.ts deleted file mode 100644 index 4e116e92d4..0000000000 --- a/examples/aws-kinesis-stream/sst.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -/** - * ## Kinesis streams - * - * Create a Kinesis stream, and subscribe to it with a function. - */ -export default $config({ - app(input) { - return { - name: "aws-kinesis-stream", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const stream = new sst.aws.KinesisStream("MyStream"); - - // Create a function subscribing to all events - stream.subscribe("AllSub", "subscriber.all"); - - // Create a function subscribing to events of `bar` type - stream.subscribe("FilteredSub", "subscriber.filtered", { - filters: [ - { - data: { - type: ["bar"], - }, - }, - ], - }); - - const app = new sst.aws.Function("MyApp", { - handler: "publisher.handler", - link: [stream], - url: true, - }); - - return { - app: app.url, - stream: stream.name, - }; - }, -}); diff --git a/examples/aws-kinesis-stream/subscriber.ts b/examples/aws-kinesis-stream/subscriber.ts deleted file mode 100644 index 8042f2aafc..0000000000 --- a/examples/aws-kinesis-stream/subscriber.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { KinesisStreamHandler } from "aws-lambda"; - -export const all: KinesisStreamHandler = async (event) => { - for (const record of event.Records) { - const data = Buffer.from(record.kinesis.data, "base64").toString(); - console.log(`"All" subscriber received:`, data); - } -}; - -export const filtered: KinesisStreamHandler = async (event) => { - for (const record of event.Records) { - const data = Buffer.from(record.kinesis.data, "base64").toString(); - console.log(`"Filtered" subscriber received:`, data); - } -}; diff --git a/examples/aws-lambda-ai-stream/index.ts b/examples/aws-lambda-ai-stream/index.ts deleted file mode 100644 index 07cbaf48d0..0000000000 --- a/examples/aws-lambda-ai-stream/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { streamText } from 'ai'; - -export const handler = awslambda.streamifyResponse(async (_event, responseStream) => { - const result = streamText({ - model: 'amazon/nova-micro', - prompt: 'Write a poem about clouds that is twenty paragraphs long.', - }); - - responseStream.setContentType('text/plain'); - for await (const chunk of result.textStream) { - responseStream.write(chunk); - process.stdout.write(chunk); - } - responseStream.end(); -}); diff --git a/examples/aws-lambda-ai-stream/package.json b/examples/aws-lambda-ai-stream/package.json deleted file mode 100644 index dbb40556da..0000000000 --- a/examples/aws-lambda-ai-stream/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "aws-lambda-ai-stream", - "type": "module", - "dependencies": { - "ai": "^6.0.116", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-lambda-ai-stream/sst.config.ts b/examples/aws-lambda-ai-stream/sst.config.ts deleted file mode 100644 index 97e6c3feb7..0000000000 --- a/examples/aws-lambda-ai-stream/sst.config.ts +++ /dev/null @@ -1,79 +0,0 @@ -/// - -/** - * ## AWS Lambda AI streaming - * - * An example on how to stream AI responses from a Lambda function using the - * [AI SDK](https://ai-sdk.dev). - * - * Uses `streamText` from the AI SDK to stream a response - * through a Lambda function URL. - * - * ```ts title="sst.config.ts" - * { - * streaming: true - * } - * ``` - * - * The handler uses `awslambda.streamifyResponse` to stream the AI response - * back to the client as it's generated. - * - * ```ts title="index.ts" - * export const handler = awslambda.streamifyResponse( - * async (_event, responseStream) => { - * const result = streamText({ - * model: "amazon/nova-micro", - * prompt: "Write a poem about clouds that is twenty paragraphs long.", - * }); - * - * responseStream.setContentType("text/plain"); - * for await (const chunk of result.textStream) { - * responseStream.write(chunk); - * } - * responseStream.end(); - * }, - * ); - * ``` - * - * Set the API key for the AI gateway. - * - * ```bash - * sst secret set AiGatewayApiKey your-api-key-here - * ``` - * - * Use the "Run Client" dev command in the multiplexer to invoke the server and see - * the streamed response. - * - */ -export default $config({ - app(input) { - return { - name: "aws-lambda-ai-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const server = new sst.aws.Function("Server", { - url: true, - streaming: true, - timeout: "15 minutes", - handler: "index.handler", - environment: { - AI_GATEWAY_API_KEY: new sst.Secret("AiGatewayApiKey").value, - }, - }); - - new sst.x.DevCommand("Client", { - dev: { - autostart: false, - command: $interpolate`curl --no-buffer ${server.url}`, - title: "Run Client", - }, - }); - - return { - url: server.url, - }; - }, -}); diff --git a/examples/aws-lambda-cron/cron.ts b/examples/aws-lambda-cron/cron.ts deleted file mode 100644 index 8fabb78be5..0000000000 --- a/examples/aws-lambda-cron/cron.ts +++ /dev/null @@ -1,4 +0,0 @@ -export async function handler(event: any) { - console.log("Cron triggered", JSON.stringify(event)); - return { statusCode: 200 }; -} diff --git a/examples/aws-lambda-cron/package.json b/examples/aws-lambda-cron/package.json deleted file mode 100644 index 1725914407..0000000000 --- a/examples/aws-lambda-cron/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-cron-lambda", - "private": true, - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-lambda-cron/sst.config.ts b/examples/aws-lambda-cron/sst.config.ts deleted file mode 100644 index f3fc0b6ccc..0000000000 --- a/examples/aws-lambda-cron/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-lambda-cron", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const queue = new sst.aws.Queue("MyDLQ"); - - const cron = new sst.aws.CronV2("MyCron", { - schedule: "rate(1 minute)", - function: "cron.handler", - timezone: "America/New_York", - retries: 3, - dlq: queue.arn, - }); - - return { - function: cron.nodes.function.name, - dlq: queue.arn, - }; - }, -}); diff --git a/examples/aws-lambda-cron/tsconfig.json b/examples/aws-lambda-cron/tsconfig.json deleted file mode 100644 index 6ec1c39406..0000000000 --- a/examples/aws-lambda-cron/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "bundler", - "strict": true, - "esModuleInterop": true - } -} diff --git a/examples/aws-lambda-golang/src/go.mod b/examples/aws-lambda-golang/src/go.mod deleted file mode 100644 index a7eafea675..0000000000 --- a/examples/aws-lambda-golang/src/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module aws-lambda - -go 1.23.4 - -require ( - github.com/aws/aws-lambda-go v1.47.0 - github.com/sst/sst/v3 v3.4.24-0.20241218234311-d6f5cc752318 -) diff --git a/examples/aws-lambda-golang/src/go.sum b/examples/aws-lambda-golang/src/go.sum deleted file mode 100644 index f3a3bcaf9f..0000000000 --- a/examples/aws-lambda-golang/src/go.sum +++ /dev/null @@ -1,12 +0,0 @@ -github.com/aws/aws-lambda-go v1.47.0 h1:0H8s0vumYx/YKs4sE7YM0ktwL2eWse+kfopsRI1sXVI= -github.com/aws/aws-lambda-go v1.47.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sst/sst/v3 v3.4.24-0.20241218234311-d6f5cc752318 h1:9qjY8XcNVRM6/Hbx+z3GdhkPgFImgUDJy1uWObko2h4= -github.com/sst/sst/v3 v3.4.24-0.20241218234311-d6f5cc752318/go.mod h1:rxQ4Pi7xaYAbyfLt0rFREzQDLE72clWKxudGKG9Xpt4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/examples/aws-lambda-golang/src/main.go b/examples/aws-lambda-golang/src/main.go deleted file mode 100644 index f19721e58c..0000000000 --- a/examples/aws-lambda-golang/src/main.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/aws/aws-lambda-go/lambda" - "github.com/sst/sst/v3/sdk/golang/resource" -) - -func handler() (string, error) { - bucket, err := resource.Get("MyBucket", "name") - if err != nil { - return "", err - } - return bucket.(string), nil -} - -func main() { - lambda.Start(handler) -} diff --git a/examples/aws-lambda-golang/sst.config.ts b/examples/aws-lambda-golang/sst.config.ts deleted file mode 100644 index 19d2c1301e..0000000000 --- a/examples/aws-lambda-golang/sst.config.ts +++ /dev/null @@ -1,60 +0,0 @@ -/// - -/** - * ## AWS Lambda Go - * - * This example shows how to use the [`go`](https://golang.org/) runtime in your Lambda - * functions. - * - * Our Go function is in the `src` directory and we point to it in our function. - * - * ```ts title="sst.config.ts" {5} - * new sst.aws.Function("MyFunction", { - * url: true, - * runtime: "go", - * link: [bucket], - * handler: "./src", - * }); - * ``` - * - * We are also linking it to an S3 bucket. We can reference the bucket in our function. - * - * ```go title="src/main.go" {2} - * func handler() (string, error) { - * bucket, err := resource.Get("MyBucket", "name") - * if err != nil { - * return "", err - * } - * return bucket.(string), nil - * } - * ``` - * - * The `resource.Get` function is from the SST Go SDK. - * - * ```go title="src/main.go" {2} - * import ( - * "github.com/sst/sst/v3/sdk/golang/resource" - * ) - * ``` - * - * The `sst dev` CLI also supports running your Go function [_Live_](/docs/live). - */ -export default $config({ - app(input) { - return { - name: "aws-lambda-golang", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket"); - - new sst.aws.Function("MyFunction", { - url: true, - runtime: "go", - link: [bucket], - handler: "./src", - }); - }, -}); diff --git a/examples/aws-lambda-hook/.gitignore b/examples/aws-lambda-hook/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-lambda-hook/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-lambda-hook/index.js b/examples/aws-lambda-hook/index.js deleted file mode 100644 index e65fb38036..0000000000 --- a/examples/aws-lambda-hook/index.js +++ /dev/null @@ -1,7 +0,0 @@ -export async function handler(event,) { - console.log(event); - return { - statusCode: 200, - body: 'Hello World', - }; -} diff --git a/examples/aws-lambda-hook/package.json b/examples/aws-lambda-hook/package.json deleted file mode 100644 index 90bae21e53..0000000000 --- a/examples/aws-lambda-hook/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-lambda-hook", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "type": "commonjs", - "dependencies": { - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.149" - } -} diff --git a/examples/aws-lambda-hook/sst.config.ts b/examples/aws-lambda-hook/sst.config.ts deleted file mode 100644 index 3935f30d6a..0000000000 --- a/examples/aws-lambda-hook/sst.config.ts +++ /dev/null @@ -1,33 +0,0 @@ -/// - -/** - * ## AWS Lambda build hook - * - * In this example we hook into the Lambda function build process with - * `hook.postbuild`. - * - * This is useful for modifying the generated Lambda function code before it's - * uploaded to AWS. It can also be used for uploading the generated sourcemaps - * to a service like Sentry. - */ -export default $config({ - app(input) { - return { - name: "aws-lambda-hook", - removal: input?.stage === "production" ? "retain" : "remove", - protect: ["production"].includes(input?.stage), - home: "aws", - }; - }, - async run() { - new sst.aws.Function("MyFunction", { - url: true, - handler: "index.handler", - hook: { - async postbuild(dir) { - console.log(`postbuild ------- ${dir}`); - }, - }, - }); - }, -}); diff --git a/examples/aws-lambda-hook/tsconfig.json b/examples/aws-lambda-hook/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-lambda-hook/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-lambda-retry-with-queues/package.json b/examples/aws-lambda-retry-with-queues/package.json deleted file mode 100644 index 64cfdc9882..0000000000 --- a/examples/aws-lambda-retry-with-queues/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-lambda-retry-with-queues", - "version": "1.0.0", - "description": "", - "type": "module", - "devDependencies": { - "@types/aws-lambda": "8.10.146" - }, - "dependencies": { - "sst": "file:../../sdk/js", - "@aws-sdk/client-lambda": "^3.714.0", - "@aws-sdk/client-sqs": "^3.714.0", - "zod": "^3.24.1" - } -} diff --git a/examples/aws-lambda-retry-with-queues/src/bus-subscriber.ts b/examples/aws-lambda-retry-with-queues/src/bus-subscriber.ts deleted file mode 100644 index fe11df3db3..0000000000 --- a/examples/aws-lambda-retry-with-queues/src/bus-subscriber.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { bus } from "sst/aws/bus"; -import { testEvent } from "./event"; - -export const handler = bus.subscriber([testEvent], async (evt, raw) => { - console.log("event", evt, raw, process.env); - const message = evt.properties.message; - - if (message !== "hello") { - throw new Error("🚨 bus subscriber failed"); - } -}); diff --git a/examples/aws-lambda-retry-with-queues/src/event.ts b/examples/aws-lambda-retry-with-queues/src/event.ts deleted file mode 100644 index 5cf54e780b..0000000000 --- a/examples/aws-lambda-retry-with-queues/src/event.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { event } from "sst/event"; -import crypto from "node:crypto"; -import { z } from "zod"; - -export const defineEvent = event.builder({ - validator: (schema) => { - return (input) => { - return schema.parse(input); - }; - }, - metadata: () => { - return { - idempotencyKey: crypto.randomUUID(), - timestamp: new Date().toISOString(), - }; - }, -}); - -export const testEvent = defineEvent( - "test", - z.object({ - message: z.string(), - }) -); diff --git a/examples/aws-lambda-retry-with-queues/src/publisher.ts b/examples/aws-lambda-retry-with-queues/src/publisher.ts deleted file mode 100644 index de80c2f044..0000000000 --- a/examples/aws-lambda-retry-with-queues/src/publisher.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { LambdaFunctionURLHandler } from "aws-lambda"; -import { bus } from "sst/aws/bus"; -import { Resource } from "sst"; -import { testEvent } from "./event"; - -// This function sends a message to the bus. This could be any other service which pugliches message to the bus. -export const handler: LambdaFunctionURLHandler = async (evt) => { - if (!evt.body) { - return { - statusCode: 400, - body: JSON.stringify({ message: "missing body" }), - }; - } - - try { - const body = JSON.parse(evt.body); - const message = body.message; - if (typeof message !== "string") { - return { - statusCode: 400, - body: JSON.stringify({ message: "message must be a string" }), - }; - } - bus.publish(Resource.bus.name, testEvent, { message }); - } catch (e) { - console.error(e); - return { - statusCode: 500, - body: JSON.stringify({ message: "error" }), - }; - } - - return { - statusCode: 200, - }; -}; diff --git a/examples/aws-lambda-retry-with-queues/src/retry.ts b/examples/aws-lambda-retry-with-queues/src/retry.ts deleted file mode 100644 index 93685227c5..0000000000 --- a/examples/aws-lambda-retry-with-queues/src/retry.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { - LambdaClient, - InvokeCommand, - GetFunctionCommand, - ResourceNotFoundException, -} from "@aws-sdk/client-lambda"; -import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs"; -import type { SQSHandler } from "aws-lambda"; -import { Resource } from "sst"; - -const lambda = new LambdaClient({}); -lambda.middlewareStack.remove("recursionDetectionMiddleware"); -const sqs = new SQSClient({}); -sqs.middlewareStack.remove("recursionDetectionMiddleware"); - -export const handler: SQSHandler = async (evt) => { - for (const record of evt.Records) { - const parsed = JSON.parse(record.body); - console.log("body", parsed); - const functionName = parsed.requestContext.functionArn - .replace(":$LATEST", "") - .split(":") - .pop(); - if (parsed.responsePayload) { - const attempt = (parsed.requestPayload.attempts || 0) + 1; - - const info = await lambda.send( - new GetFunctionCommand({ - FunctionName: functionName, - }), - ); - const max = - Number.parseInt( - info.Configuration?.Environment?.Variables?.RETRIES || "", - ) || 0; - console.log("max retries", max); - if (attempt > max) { - console.log(`giving up after ${attempt} retries`); - // send to dlq - await sqs.send( - new SendMessageCommand({ - QueueUrl: Resource.dlq.url, - MessageBody: JSON.stringify({ - requestPayload: parsed.requestPayload, - requestContext: parsed.requestContext, - responsePayload: parsed.responsePayload, - }), - }), - ); - return; - } - const seconds = Math.min(Math.pow(2, attempt), 900); - console.log( - "delaying retry by ", - seconds, - "seconds for attempt", - attempt, - ); - parsed.requestPayload.attempts = attempt; - await sqs.send( - new SendMessageCommand({ - QueueUrl: Resource.retryQueue.url, - DelaySeconds: seconds, - MessageBody: JSON.stringify({ - requestPayload: parsed.requestPayload, - requestContext: parsed.requestContext, - }), - }), - ); - } - - if (!parsed.responsePayload) { - console.log("triggering function"); - try { - await lambda.send( - new InvokeCommand({ - InvocationType: "Event", - Payload: Buffer.from(JSON.stringify(parsed.requestPayload)), - FunctionName: functionName, - }), - ); - } catch (e) { - if (e instanceof ResourceNotFoundException) { - return; - } - throw e; - } - } - } -}; diff --git a/examples/aws-lambda-retry-with-queues/sst.config.ts b/examples/aws-lambda-retry-with-queues/sst.config.ts deleted file mode 100644 index 2f912c2147..0000000000 --- a/examples/aws-lambda-retry-with-queues/sst.config.ts +++ /dev/null @@ -1,223 +0,0 @@ -/// - -/** - * ## AWS Lambda retry with queues - * - * An example on how to retry Lambda invocations using SQS queues. - * - * Create a SQS retry queue which will be set as the destination for the Lambda function. - * - * ```ts title="src/retry.ts" - * const retryQueue = new sst.aws.Queue("retryQueue"); - * - * const bus = new sst.aws.Bus("bus"); - * - * const busSubscriber = bus.subscribe("busSubscriber", { - * handler: "src/bus-subscriber.handler", - * environment: { - * RETRIES: "2", // set the number of retries - * }, - * link: [retryQueue], // so the function can send messages to the retry queue - * }); - * - * new aws.lambda.FunctionEventInvokeConfig("eventConfig", { - * functionName: $resolve([busSubscriber.nodes.function.name]).apply( - * ([name]) => name, - * ), - * maximumRetryAttempts: 2, // default is 2, must be between 0 and 2 - * destinationConfig: { - * onFailure: { - * destination: retryQueue.arn, - * }, - * }, - * }); - * ``` - * - * Create a bus subscriber which will publish messages to the bus. Include a DLQ for messages that continue to fail. - * - * ```ts title="sst.config.ts" - * - * const dlq = new sst.aws.Queue("dlq"); - * - * retryQueue.subscribe({ - * handler: "src/retry.handler", - * link: [busSubscriber.nodes.function, retryQueue, dlq], - * timeout: "30 seconds", - * environment: { - * RETRIER_QUEUE_URL: retryQueue.url, - * }, - * permissions: [ - * { - * actions: ["lambda:GetFunction", "lambda:InvokeFunction"], - * resources: [ - * $interpolate`arn:aws:lambda:${aws.getRegionOutput().region}:${ - * aws.getCallerIdentityOutput().accountId - * }:function:*`, - * ], - * }, - * ], - * transform: { - * function: { - * deadLetterConfig: { - * targetArn: dlq.arn, - * }, - * }, - * }, - * }); - * ``` - * - * - * The Retry function will read mesaages and send back to the queue to be retried with a backoff. - * - * ```ts title="src/retry.ts" - * export const handler: SQSHandler = async (evt) => { - * for (const record of evt.Records) { - * const parsed = JSON.parse(record.body); - * console.log("body", parsed); - * const functionName = parsed.requestContext.functionArn - * .replace(":$LATEST", "") - * .split(":") - * .pop(); - * if (parsed.responsePayload) { - * const attempt = (parsed.requestPayload.attempts || 0) + 1; - * - * const info = await lambda.send( - * new GetFunctionCommand({ - * FunctionName: functionName, - * }), - * ); - * const max = - * Number.parseInt( - * info.Configuration?.Environment?.Variables?.RETRIES || "", - * ) || 0; - * console.log("max retries", max); - * if (attempt > max) { - * console.log(`giving up after ${attempt} retries`); - * // send to dlq - * await sqs.send( - * new SendMessageCommand({ - * QueueUrl: Resource.dlq.url, - * MessageBody: JSON.stringify({ - * requestPayload: parsed.requestPayload, - * requestContext: parsed.requestContext, - * responsePayload: parsed.responsePayload, - * }), - * }), - * ); - * return; - * } - * const seconds = Math.min(Math.pow(2, attempt), 900); - * console.log( - * "delaying retry by ", - * seconds, - * "seconds for attempt", - * attempt, - * ); - * parsed.requestPayload.attempts = attempt; - * await sqs.send( - * new SendMessageCommand({ - * QueueUrl: Resource.retryQueue.url, - * DelaySeconds: seconds, - * MessageBody: JSON.stringify({ - * requestPayload: parsed.requestPayload, - * requestContext: parsed.requestContext, - * }), - * }), - * ); - * } - * - * if (!parsed.responsePayload) { - * console.log("triggering function"); - * try { - * await lambda.send( - * new InvokeCommand({ - * InvocationType: "Event", - * Payload: Buffer.from(JSON.stringify(parsed.requestPayload)), - * FunctionName: functionName, - * }), - * ); - * } catch (e) { - * if (e instanceof ResourceNotFoundException) { - * return; - * } - * throw e; - * } - * } - * } - * }; - * ``` - */ -export default $config({ - app(input) { - return { - name: "aws-lambda-retry-with-queues", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const dlq = new sst.aws.Queue("dlq"); - - const retryQueue = new sst.aws.Queue("retryQueue"); - - const bus = new sst.aws.Bus("bus"); - - const busSubscriber = bus.subscribe("busSubscriber", { - handler: "src/bus-subscriber.handler", - environment: { - RETRIES: "2", - }, - link: [retryQueue], // so the function can send messages to the queue - }); - - const publisher = new sst.aws.Function("publisher", { - handler: "src/publisher.handler", - link: [bus], - url: true, - }); - - new aws.lambda.FunctionEventInvokeConfig("eventConfig", { - functionName: $resolve([busSubscriber.nodes.function.name]).apply( - ([name]) => name, - ), - maximumRetryAttempts: 1, - destinationConfig: { - onFailure: { - destination: retryQueue.arn, - }, - }, - }); - - retryQueue.subscribe({ - handler: "src/retry.handler", - link: [busSubscriber.nodes.function, retryQueue, dlq], - timeout: "30 seconds", - environment: { - RETRIER_QUEUE_URL: retryQueue.url, - }, - permissions: [ - { - actions: ["lambda:GetFunction", "lambda:InvokeFunction"], - resources: [ - $interpolate`arn:aws:lambda:${aws.getRegionOutput().region}:${ - aws.getCallerIdentityOutput().accountId - }:function:*`, - ], - }, - ], - transform: { - function: { - deadLetterConfig: { - targetArn: dlq.arn, - }, - }, - }, - }); - - return { - publisher: publisher.url, - dlq: dlq.url, - retryQueue: retryQueue.url, - }; - }, -}); diff --git a/examples/aws-lambda-retry-with-queues/tsconfig.json b/examples/aws-lambda-retry-with-queues/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-lambda-retry-with-queues/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-lambda-rust-multiple-binaries/.gitignore b/examples/aws-lambda-rust-multiple-binaries/.gitignore deleted file mode 100644 index 2a7be17e50..0000000000 --- a/examples/aws-lambda-rust-multiple-binaries/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target - -# sst -.sst diff --git a/examples/aws-lambda-rust-multiple-binaries/Cargo.toml b/examples/aws-lambda-rust-multiple-binaries/Cargo.toml deleted file mode 100644 index 0c41f4ac1e..0000000000 --- a/examples/aws-lambda-rust-multiple-binaries/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "aws-lambda-rust-multi-bin" -version = "0.1.0" -edition = "2021" - -[dependencies] -aws-config = { version = "1.5.16", features = ["behavior-version-latest"] } -aws-sdk-s3 = "1.73.0" -lambda_runtime = "0.13.0" -serde = { version = "1.0.217", features = ["derive"] } -serde_json = "1.0.138" -# this will break when not in this repo. -sst_sdk = { version = "0.1.0", path = "../../sdk/rust" } -# sst_sdk = "0.1.0" -tokio = { version = "1", features = ["macros"] } -uuid = { version = "1.13.1", features = ["v4"] } - -[[bin]] -name = "push" -path = "src/push.rs" - -[[bin]] -name = "pop" -path = "src/pop.rs" diff --git a/examples/aws-lambda-rust-multiple-binaries/src/pop.rs b/examples/aws-lambda-rust-multiple-binaries/src/pop.rs deleted file mode 100644 index 9106c96e6c..0000000000 --- a/examples/aws-lambda-rust-multiple-binaries/src/pop.rs +++ /dev/null @@ -1,48 +0,0 @@ -use std::time::Duration; - -use aws_sdk_s3::presigning::PresigningConfig; -use lambda_runtime::{service_fn, Error, LambdaEvent}; -use serde::Deserialize; -use serde_json::Value; -use sst_sdk::Resource; - -#[derive(Deserialize, Debug)] -struct Bucket { - name: String, -} - -async fn latest(_event: LambdaEvent) -> Result { - let config = aws_config::load_from_env().await; - let client = aws_sdk_s3::Client::new(&config); - let resource = Resource::init().unwrap(); - let Bucket { name } = resource.get("Bucket").unwrap(); - - let objects = client.list_objects().bucket(&name).send().await.unwrap(); - let latest = objects - .contents() - .into_iter() - .min_by_key(|o| o.last_modified().unwrap()) - .unwrap(); - - let url = client - .get_object() - .bucket(name) - .key(latest.key().unwrap()) - .presigned( - PresigningConfig::builder() - .expires_in(Duration::from_secs(60 * 10)) - .build() - .unwrap(), - ) - .await - .unwrap(); - - Ok(url.uri().to_string()) -} - -#[tokio::main] -async fn main() -> Result<(), Error> { - let func = service_fn(latest); - lambda_runtime::run(func).await?; - Ok(()) -} diff --git a/examples/aws-lambda-rust-multiple-binaries/src/push.rs b/examples/aws-lambda-rust-multiple-binaries/src/push.rs deleted file mode 100644 index 7ee767072c..0000000000 --- a/examples/aws-lambda-rust-multiple-binaries/src/push.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::time::Duration; - -use aws_sdk_s3::presigning::PresigningConfig; -use lambda_runtime::{service_fn, Error, LambdaEvent}; -use serde::Deserialize; -use serde_json::Value; -use sst_sdk::Resource; - -#[derive(Deserialize, Debug)] -struct Bucket { - name: String, -} - -async fn presigned_url(_event: LambdaEvent) -> Result { - let config = aws_config::load_from_env().await; - let client = aws_sdk_s3::Client::new(&config); - let resource = Resource::init().unwrap(); - let Bucket { name } = resource.get("Bucket").unwrap(); - - let url = client - .put_object() - .bucket(name) - .key(uuid::Uuid::new_v4()) - .presigned( - PresigningConfig::builder() - .expires_in(Duration::from_secs(60 * 10)) - .build() - .unwrap(), - ) - .await - .unwrap(); - - Ok(url.uri().to_string()) -} - -#[tokio::main] -async fn main() -> Result<(), Error> { - let func = service_fn(presigned_url); - lambda_runtime::run(func).await?; - Ok(()) -} diff --git a/examples/aws-lambda-rust-multiple-binaries/sst.config.ts b/examples/aws-lambda-rust-multiple-binaries/sst.config.ts deleted file mode 100644 index f229ab5948..0000000000 --- a/examples/aws-lambda-rust-multiple-binaries/sst.config.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// - -/** - * ## AWS Lamda Rust multiple-binaries - * - * This example shows how to deploy multiple binary rust project to AWS Lambda. - * - * SST relies on the work of [cargo lambda](https://cargo-lambda) to build and deploy Rust Lambda functions. - * - * What is special about the following file is that we are defining multiple binaries using the `[[bin]]` section in the `Cargo.toml` file. - * - * ```toml title="Cargo.toml" {13,14,15,17,18,19} - * [package] - * name = "aws-lambda-rust-multi-bin" - * version = "0.1.0" - * edition = "2021" - * - * [dependencies] - * lambda_runtime = "0.13.0" - * serde = { version = "1.0.217", features = ["derive"] } - * serde_json = "1.0.138" - * tokio = { version = "1", features = ["macros"] } - * # -- please note ommited dependencies -- - * - * [[bin]] - * name = "push" - * path = "src/push.rs" - * - * [[bin]] - * name = "pop" - * path = "src/pop.rs" - * ``` - * - * We then utilise the . syntax to specify the handler binary - * - * ```ts title="sst.config.ts" {5,11} - * new sst.aws.Function("push", { - * url: true, - * runtime: "rust", - * link: [bucket], - * handler: "./.push", - * }); - * new sst.aws.Function("pop", { - * url: true, - * runtime: "rust", - * link: [bucket], - * handler: "./.pop", - * }); - * ``` - */ - -export default $config({ - app(input) { - return { - name: "aws-lambda-rust-multiple-binaries", - removal: input?.stage === "production" ? "retain" : "remove", - protect: ["production"].includes(input?.stage), - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("Bucket"); - const push = new sst.aws.Function("push", { - runtime: "rust", - handler: "./.push", - url: true, - architecture: "arm64", - link: [bucket], - }); - const pop = new sst.aws.Function("pop", { - runtime: "rust", - handler: "./.pop", - url: true, - architecture: "arm64", - link: [bucket], - }); - - return { push_url: push.url, pop_url: pop.url }; - }, -}); diff --git a/examples/aws-lambda-stream/.gitignore b/examples/aws-lambda-stream/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-lambda-stream/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-lambda-stream/index.ts b/examples/aws-lambda-stream/index.ts deleted file mode 100644 index fb8e0b89d2..0000000000 --- a/examples/aws-lambda-stream/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export const handler = awslambda.streamifyResponse( - async (event, stream) => { - stream = awslambda.HttpResponseStream.from(stream, { - statusCode: 200, - headers: { - "Content-Type": "text/plain; charset=UTF-8", - "X-Content-Type-Options": "nosniff", - }, - }); - - stream.write("Hello "); - await new Promise((resolve) => setTimeout(resolve, 3000)); - stream.write("World"); - - stream.end(); - }, -); diff --git a/examples/aws-lambda-stream/package.json b/examples/aws-lambda-stream/package.json deleted file mode 100644 index bda03c194b..0000000000 --- a/examples/aws-lambda-stream/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "aws-lambda-stream", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.161" - } -} diff --git a/examples/aws-lambda-stream/sst.config.ts b/examples/aws-lambda-stream/sst.config.ts deleted file mode 100644 index 8bea35f559..0000000000 --- a/examples/aws-lambda-stream/sst.config.ts +++ /dev/null @@ -1,60 +0,0 @@ -/// - -/** - * ## AWS Lambda streaming - * - * An example on how to enable streaming for Lambda functions. - * - * ```ts title="sst.config.ts" - * { - * streaming: true - * } - * ``` - * - * Use the `awslambda.streamifyResponse` function to wrap your handler. The `awslambda` - * global is provided by the Lambda execution environment at runtime, and SST provides it - * automatically during `sst dev` as well. For TypeScript types, importing from - * `@types/aws-lambda` will augment the global namespace. - * - * ```ts title="index.ts" - * export const handler = awslambda.streamifyResponse( - * async (event, stream) => { - * stream = awslambda.HttpResponseStream.from(stream, { - * statusCode: 200, - * headers: { - * "Content-Type": "text/plain; charset=UTF-8", - * "X-Content-Type-Options": "nosniff", - * }, - * }); - * - * stream.write("Hello "); - * await new Promise((resolve) => setTimeout(resolve, 3000)); - * stream.write("World"); - * - * stream.end(); - * }, - * ); - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-lambda-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const fn = new sst.aws.Function("MyFunction", { - url: true, - streaming: true, - timeout: "15 minutes", - handler: "index.handler", - }); - - return { - url: fn.url, - }; - }, -}); diff --git a/examples/aws-lambda-stream/tsconfig.json b/examples/aws-lambda-stream/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-lambda-stream/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-lambda-trpc-stream/package.json b/examples/aws-lambda-trpc-stream/package.json deleted file mode 100644 index 94bc5f1505..0000000000 --- a/examples/aws-lambda-trpc-stream/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "aws-lambda-trpc-stream", - "type": "module", - "dependencies": { - "@trpc/client": "^11.11.0", - "@trpc/server": "^11.11.0", - "sst": "file:../../sdk/js", - "zod": "^4.3.6" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-lambda-trpc-stream/sst.config.ts b/examples/aws-lambda-trpc-stream/sst.config.ts deleted file mode 100644 index 0d59f8a635..0000000000 --- a/examples/aws-lambda-trpc-stream/sst.config.ts +++ /dev/null @@ -1,48 +0,0 @@ -/// - -/** - * ## AWS Lambda tRPC streaming - * - * An example on how to use tRPC with Lambda streaming. - * - * Uses `@trpc/server`'s `awsLambdaStreamingRequestHandler` adapter to handle - * streaming responses through Lambda function URLs. - * - * The `trpc-server` function defines a tRPC router and streams responses. - * The `trpc-client` function invokes the server using `httpBatchStreamLink`. - * - * Streaming is supported in both `sst dev` and `sst deploy`. - * - */ -export default $config({ - app(input) { - return { - name: 'aws-lambda-trpc-stream', - removal: input?.stage === 'production' ? 'retain' : 'remove', - home: 'aws', - }; - }, - async run() { - const trpcServer = new sst.aws.Function('TrpcServer', { - handler: 'trpc-server.handler', - streaming: true, - url: true, - runtime: 'nodejs24.x', - }); - - new sst.x.DevCommand('Client', { - dev: { - autostart: false, - command: $interpolate`npx tsx trpc-client.ts`, - title: 'Run Client', - }, - environment: { - TRPC_SERVER_URL: trpcServer.url, - }, - }); - - return { - serverUrl: trpcServer.url, - }; - }, -}); diff --git a/examples/aws-lambda-trpc-stream/trpc-client.ts b/examples/aws-lambda-trpc-stream/trpc-client.ts deleted file mode 100644 index aec7000b10..0000000000 --- a/examples/aws-lambda-trpc-stream/trpc-client.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - createTRPCClient, - httpBatchStreamLink, - TRPCClientError, -} from "@trpc/client"; -import { ApiRouter } from "./trpc-server"; - -const client = createTRPCClient({ - links: [ - httpBatchStreamLink({ - url: process.env.TRPC_SERVER_URL, - methodOverride: "POST", - }), - ], -}); - -export const main = async () => { - await Promise.all( - Array.from({ length: 10 }, async (_, idx) => { - const delay = Math.random() * 8_000; - console.log("sending request", idx); - try { - const res = await client.getById.query({ delay, idx }); - console.log("got response", res.idx); - } catch (err) { - if (isTrpcError(err)) { - console.error("received error", idx, err.shape.message); - } else { - console.error("received unexpecte error", idx); - } - } - }), - ); -}; - -const isTrpcError = (err: unknown): err is TRPCClientError => { - return !!err && err instanceof TRPCClientError; -}; - -main().catch(console.error); diff --git a/examples/aws-lambda-trpc-stream/trpc-server.ts b/examples/aws-lambda-trpc-stream/trpc-server.ts deleted file mode 100644 index 6fb341e390..0000000000 --- a/examples/aws-lambda-trpc-stream/trpc-server.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { initTRPC, TRPCError } from '@trpc/server'; -import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda'; -import z from 'zod'; - -const { router, procedure } = initTRPC.create(); - -const apiRouter = router({ - getById: procedure - .input( - z.object({ - delay: z.number(), - idx: z.number(), - }), - ) - .query(async ({ input }) => { - await new Promise((r) => setTimeout(r, input.delay)); - if (Math.random() < 0.5) { - console.log('sending response', input.delay); - return { id: Math.random(), idx: input.idx }; - } - console.log('sending error', input.idx); - throw new TRPCError({ - code: 'BAD_REQUEST', - message: 'Random failure', - }); - }), -}); - -export type ApiRouter = typeof apiRouter; - -export const handler = awslambda.streamifyResponse( - awsLambdaStreamingRequestHandler({ - router: apiRouter, - allowMethodOverride: true, - }), -); diff --git a/examples/aws-lambda-vpc/.gitignore b/examples/aws-lambda-vpc/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-lambda-vpc/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-lambda-vpc/index.ts b/examples/aws-lambda-vpc/index.ts deleted file mode 100644 index 4cb5e4819a..0000000000 --- a/examples/aws-lambda-vpc/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -export const handler = async () => { - const counter = await redis.incr("counter"); - return { - statusCode: 200, - body: `Hit counter: ${counter}` - }; -}; diff --git a/examples/aws-lambda-vpc/package.json b/examples/aws-lambda-vpc/package.json deleted file mode 100644 index 38b2e18d93..0000000000 --- a/examples/aws-lambda-vpc/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-lambda-vpc", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-lambda-vpc/sst.config.ts b/examples/aws-lambda-vpc/sst.config.ts deleted file mode 100644 index 6fef731bf9..0000000000 --- a/examples/aws-lambda-vpc/sst.config.ts +++ /dev/null @@ -1,66 +0,0 @@ -/// - -/** - * ## AWS Lambda in a VPC - * - * You can use SST to locally work on Lambda functions that are in a VPC. To do so, you'll - * need to enable `bastion` and `nat` on the `Vpc` component. - * - * ```ts title="sst.config.ts" - * new sst.aws.Vpc("MyVpc", { bastion: true, nat: "managed" }); - * ``` - * - * The NAT gateway is necessary to allow your Lambda function to connect to the internet. While, - * the bastion host is necessary for your local machine to be able to tunnel to the VPC. - * - * You'll need to install the tunnel, if you haven't done this before. - * - * ```bash "sudo" - * sudo sst tunnel install - * ``` - * - * This needs _sudo_ to create the network interface on your machine. You'll only need to do - * this once. - * - * Now you can run `sst dev`, your function can access resources in the VPC. For example, here - * we are connecting to a Redis cluster. - * - * ```ts title="index.ts" - * const redis = new Cluster( - * [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - * { - * dnsLookup: (address, callback) => callback(null, address), - * redisOptions: { - * tls: {}, - * username: Resource.MyRedis.username, - * password: Resource.MyRedis.password, - * }, - * } - * ); - * ``` - * - * The Redis cluster is in the same VPC as the function. - */ -export default $config({ - app(input) { - return { - name: "aws-lambda-vpc", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true, nat: "managed" }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const api = new sst.aws.Function("MyFunction", { - vpc, - url: true, - link: [redis], - handler: "index.handler" - }); - - return { - url: api.url, - }; - }, -}); diff --git a/examples/aws-lambda-vpc/tsconfig.json b/examples/aws-lambda-vpc/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-lambda-vpc/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-linkable-env/.gitignore b/examples/aws-linkable-env/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-linkable-env/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-linkable-env/package.json b/examples/aws-linkable-env/package.json deleted file mode 100644 index 9febdd34d5..0000000000 --- a/examples/aws-linkable-env/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-linkable-env", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-linkable-env/sst.config.ts b/examples/aws-linkable-env/sst.config.ts deleted file mode 100644 index 20acdfcd00..0000000000 --- a/examples/aws-linkable-env/sst.config.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// - -/** - * ## Linkable env vars - * - * Pass SST link env vars to a native `aws.ecs.TaskDefinition` container using - * `sst.Linkable.env()`. This lets `Resource.MyResource` work at runtime - * in compute not managed by SST. - * - */ -export default $config({ - app(input) { - return { - name: "aws-linkable-env", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // Create an SST bucket - const bucket = new sst.aws.Bucket("MyBucket"); - - // Create a custom linkable - const linkable = new sst.Linkable("MyLinkable", { - properties: { - foo: "bar", - }, - }); - - // Create VPC and ECS cluster using native AWS resources - const vpc = new aws.ec2.Vpc("Vpc", { cidrBlock: "10.0.0.0/16" }); - const subnet = new aws.ec2.Subnet("Subnet", { - vpcId: vpc.id, - cidrBlock: "10.0.0.0/24", - }); - const cluster = new aws.ecs.Cluster("Cluster"); - - // Linkable.env() returns a Record, but ECS expects - // environment as an array of { name, value } objects - const environment = sst.Linkable.env([bucket, linkable]).apply((env) => - Object.entries(env).map(([name, value]) => ({ name, value })), - ); - - const taskDefinition = new aws.ecs.TaskDefinition("TaskDefinition", { - family: $interpolate`${$app.name}-${$app.stage}`, - cpu: "256", - memory: "512", - networkMode: "awsvpc", - requiresCompatibilities: ["FARGATE"], - containerDefinitions: $jsonStringify([ - { - name: "app", - image: "public.ecr.aws/docker/library/node:20-slim", - essential: true, - environment, - }, - ]), - }); - - new aws.ecs.Service("Service", { - cluster: cluster.arn, - taskDefinition: taskDefinition.arn, - desiredCount: 0, - launchType: "FARGATE", - networkConfiguration: { - subnets: [subnet.id], - }, - }); - }, -}); diff --git a/examples/aws-linkable-env/tsconfig.json b/examples/aws-linkable-env/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-linkable-env/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-linkable/.gitignore b/examples/aws-linkable/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-linkable/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-linkable/index.ts b/examples/aws-linkable/index.ts deleted file mode 100644 index 1498966a26..0000000000 --- a/examples/aws-linkable/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Resource } from "sst"; - -export async function handler() { - console.log("Hello World!"); - console.log("topic", Resource.Topic.arn); - console.log( - "existingResources", - Resource.ExistingResources.queueName, - Resource.ExistingResources.bucketName, - ); -} diff --git a/examples/aws-linkable/package.json b/examples/aws-linkable/package.json deleted file mode 100644 index ccedf4fe7b..0000000000 --- a/examples/aws-linkable/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-linkable", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-linkable/sst.config.ts b/examples/aws-linkable/sst.config.ts deleted file mode 100644 index 3a27854d1c..0000000000 --- a/examples/aws-linkable/sst.config.ts +++ /dev/null @@ -1,46 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-linkable", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // make a native resource linkable - sst.Linkable.wrap(aws.sns.Topic, (resource) => ({ - // these properties will be available when linked - properties: { - arn: resource.arn, - name: resource.name, - }, - })); - const topic = new aws.sns.Topic("Topic"); - - // create something that can be linked - const existingResources = new sst.Linkable("ExistingResources", { - properties: { - bucketName: "existing-bucket", - queueName: "existing-queue", - }, - include: [ - sst.aws.permission({ - actions: ["s3:GetObject", "sns:Publish"], - resources: ["*"], - }), - ], - }); - - const fn = new sst.aws.Function("Function", { - handler: "index.handler", - link: [topic, existingResources], - url: true, - }); - - return { - url: fn.url, - }; - }, -}); diff --git a/examples/aws-linkable/tsconfig.json b/examples/aws-linkable/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-linkable/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-load-balancer-waf/package.json b/examples/aws-load-balancer-waf/package.json deleted file mode 100644 index 668890f41c..0000000000 --- a/examples/aws-load-balancer-waf/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-load-balancer-waf", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-load-balancer-waf/sst.config.ts b/examples/aws-load-balancer-waf/sst.config.ts deleted file mode 100644 index 1a5fecc363..0000000000 --- a/examples/aws-load-balancer-waf/sst.config.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// - -/** - * ## AWS Load Balancer Web Application Firewall (WAF) - * - * Enable WAF for an AWS Load Balancer. - * - * The WAF is configured to enable a rate limit and enables AWS managed rules. - * - */ -export default $config({ - app(input) { - return { - name: "aws-load-balancer-waf", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - const service = cluster.addService("MyAppService", { - image: { - context: "./", - dockerfile: "packages/server/Dockerfile", - }, - }); - - const rateLimitRule = { - name: "RateLimitRule", - statement: { - rateBasedStatement: { - limit: 200, - aggregateKeyType: "IP", - }, - }, - priority: 1, - action: { block: {} }, - visibilityConfig: { - cloudwatchMetricsEnabled: true, - sampledRequestsEnabled: true, - metricName: "MyAppRateLimitRule", - }, - }; - - const awsManagedRules = { - name: "AWSManagedRules", - statement: { - managedRuleGroupStatement: { - name: "AWSManagedRulesCommonRuleSet", - vendorName: "AWS", - }, - }, - priority: 2, - overrideAction: { - none: {}, - }, - visibilityConfig: { - cloudwatchMetricsEnabled: true, - sampledRequestsEnabled: true, - metricName: "MyAppAWSManagedRules", - }, - }; - - const webAcl = new aws.wafv2.WebAcl("AppAlbWebAcl", { - defaultAction: { allow: {} }, - scope: "REGIONAL", - visibilityConfig: { - cloudwatchMetricsEnabled: true, - sampledRequestsEnabled: true, - metricName: "AppAlbWebAcl", - }, - rules: [rateLimitRule, awsManagedRules], - }); - - service.nodes.loadBalancer.arn.apply((arn) => { - new aws.wafv2.WebAclAssociation("MyAppAlbWebAclAssociation", { - resourceArn: arn, - webAclArn: webAcl.arn, - }); - }); - - return {}; - }, -}); diff --git a/examples/aws-monorepo/.gitignore b/examples/aws-monorepo/.gitignore deleted file mode 100644 index c4a0d6f07c..0000000000 --- a/examples/aws-monorepo/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -node_modules - -# sst -.sst - -# temporary files -.#* diff --git a/examples/aws-monorepo/infra/api.ts b/examples/aws-monorepo/infra/api.ts deleted file mode 100644 index 2d09eeae8b..0000000000 --- a/examples/aws-monorepo/infra/api.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { database } from "./database"; - -export const api = new sst.aws.Function("Api", { - url: true, - link: [database], - handler: "./packages/functions/src/api.handler", - environment: { - foo: "9", - }, -}); diff --git a/examples/aws-monorepo/infra/astro.ts b/examples/aws-monorepo/infra/astro.ts deleted file mode 100644 index 1b7671fa07..0000000000 --- a/examples/aws-monorepo/infra/astro.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { api } from "./api"; - -const bucket = new sst.aws.Bucket("MyBucket"); -export const astro = new sst.aws.Astro("Astro", { - path: "packages/astro", - link: [bucket], - environment: { - VITE_API_URL: api.url, - }, -}); diff --git a/examples/aws-monorepo/infra/database.ts b/examples/aws-monorepo/infra/database.ts deleted file mode 100644 index 420a14a240..0000000000 --- a/examples/aws-monorepo/infra/database.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const database = new sst.aws.Dynamo("Database", { - fields: { - PK: "string", - SK: "string", - }, - primaryIndex: { - hashKey: "PK", - rangeKey: "SK", - }, -}); diff --git a/examples/aws-monorepo/infra/frontend.ts b/examples/aws-monorepo/infra/frontend.ts deleted file mode 100644 index c32a095522..0000000000 --- a/examples/aws-monorepo/infra/frontend.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { api } from "./api"; - -export const web = new sst.aws.StaticSite("StaticSite", { - path: "packages/frontend", - build: { - output: "dist", - command: "npm run build", - }, - environment: { - VITE_API_URL: api.url, - }, -}); diff --git a/examples/aws-monorepo/infra/index.ts b/examples/aws-monorepo/infra/index.ts deleted file mode 100644 index f29a75d8b1..0000000000 --- a/examples/aws-monorepo/infra/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./api"; -export * from "./database"; -export * from "./frontend"; -export * from "./astro"; diff --git a/examples/aws-monorepo/package.json b/examples/aws-monorepo/package.json deleted file mode 100644 index 9f1076e6a4..0000000000 --- a/examples/aws-monorepo/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "aws-monorepo", - "version": "0.0.0", - "workspaces": [ - "packages/*" - ], - "scripts": { - "dev": "sst dev" - }, - "devDependencies": { - "@tsconfig/node20": "^20.1.4", - "typescript": "5.3.3" - }, - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-monorepo/packages/astro/.gitignore b/examples/aws-monorepo/packages/astro/.gitignore deleted file mode 100644 index 9a746a2f70..0000000000 --- a/examples/aws-monorepo/packages/astro/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# build output -dist/ - -# generated types -.astro/ - -# dependencies -node_modules/ - -# logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - -# environment variables -.env -.env.production - -# macOS-specific files -.DS_Store - -# sst -.sst diff --git a/examples/aws-monorepo/packages/astro/.vscode/extensions.json b/examples/aws-monorepo/packages/astro/.vscode/extensions.json deleted file mode 100644 index 22a15055d6..0000000000 --- a/examples/aws-monorepo/packages/astro/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "recommendations": ["astro-build.astro-vscode"], - "unwantedRecommendations": [] -} diff --git a/examples/aws-monorepo/packages/astro/.vscode/launch.json b/examples/aws-monorepo/packages/astro/.vscode/launch.json deleted file mode 100644 index d642209762..0000000000 --- a/examples/aws-monorepo/packages/astro/.vscode/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "command": "./node_modules/.bin/astro dev", - "name": "Development server", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/examples/aws-monorepo/packages/astro/astro.config.mjs b/examples/aws-monorepo/packages/astro/astro.config.mjs deleted file mode 100644 index b4f287b9a8..0000000000 --- a/examples/aws-monorepo/packages/astro/astro.config.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from "astro/config"; -import aws from "astro-sst"; - -export default defineConfig({ - output: "server", - adapter: aws(), -}); diff --git a/examples/aws-monorepo/packages/astro/package.json b/examples/aws-monorepo/packages/astro/package.json deleted file mode 100644 index 677f362509..0000000000 --- a/examples/aws-monorepo/packages/astro/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-astro", - "type": "module", - "version": "0.0.1", - "scripts": { - "dev": "astro dev", - "start": "astro dev", - "build": "astro build", - "preview": "astro preview", - "astro": "astro" - }, - "dependencies": { - "@astrojs/check": "^0.5.10", - "@aws-sdk/client-s3": "^3.540.0", - "@aws-sdk/s3-request-presigner": "^3.540.0", - "astro": "^4.5.9", - "astro-sst": "^2.41.2", - "sst": "file:../../../../sdk/js", - "typescript": "^5.4.3" - } -} diff --git a/examples/aws-monorepo/packages/astro/public/favicon.svg b/examples/aws-monorepo/packages/astro/public/favicon.svg deleted file mode 100644 index f157bd1c5e..0000000000 --- a/examples/aws-monorepo/packages/astro/public/favicon.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/examples/aws-monorepo/packages/astro/src/components/Card.astro b/examples/aws-monorepo/packages/astro/src/components/Card.astro deleted file mode 100644 index bd6d5971eb..0000000000 --- a/examples/aws-monorepo/packages/astro/src/components/Card.astro +++ /dev/null @@ -1,61 +0,0 @@ ---- -interface Props { - title: string; - body: string; - href: string; -} - -const { href, title, body } = Astro.props; ---- - - - diff --git a/examples/aws-monorepo/packages/astro/src/env.d.ts b/examples/aws-monorepo/packages/astro/src/env.d.ts deleted file mode 100644 index acef35f175..0000000000 --- a/examples/aws-monorepo/packages/astro/src/env.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/// -/// diff --git a/examples/aws-monorepo/packages/astro/src/layouts/Layout.astro b/examples/aws-monorepo/packages/astro/src/layouts/Layout.astro deleted file mode 100644 index 7b552be19b..0000000000 --- a/examples/aws-monorepo/packages/astro/src/layouts/Layout.astro +++ /dev/null @@ -1,51 +0,0 @@ ---- -interface Props { - title: string; -} - -const { title } = Astro.props; ---- - - - - - - - - - - {title} - - - - - - diff --git a/examples/aws-monorepo/packages/astro/src/pages/index.astro b/examples/aws-monorepo/packages/astro/src/pages/index.astro deleted file mode 100644 index bd93563ed4..0000000000 --- a/examples/aws-monorepo/packages/astro/src/pages/index.astro +++ /dev/null @@ -1,75 +0,0 @@ ---- -import { Resource } from "sst"; -import Layout from '../layouts/Layout.astro'; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, -}); -const url = await getSignedUrl(new S3Client({}), command); ---- - - -
-
- - -
- -
-
- - diff --git a/examples/aws-monorepo/packages/astro/tsconfig.json b/examples/aws-monorepo/packages/astro/tsconfig.json deleted file mode 100644 index 77da9dd009..0000000000 --- a/examples/aws-monorepo/packages/astro/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "astro/tsconfigs/strict" -} \ No newline at end of file diff --git a/examples/aws-monorepo/packages/core/package.json b/examples/aws-monorepo/packages/core/package.json deleted file mode 100644 index bfd1c917de..0000000000 --- a/examples/aws-monorepo/packages/core/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@aws-monorepo/core", - "version": "0.0.0", - "exports": { - "./*": [ - "./src/*/index.ts", - "./src/*.ts" - ] - }, - "devDependencies": { - "sst": "file:../../../../sdk/js" - } -} diff --git a/examples/aws-monorepo/packages/core/src/example/index.ts b/examples/aws-monorepo/packages/core/src/example/index.ts deleted file mode 100644 index 9cb1c03477..0000000000 --- a/examples/aws-monorepo/packages/core/src/example/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export namespace Example { - export function hello() { - return "Hello, world!"; - } -} diff --git a/examples/aws-monorepo/packages/core/tsconfig.json b/examples/aws-monorepo/packages/core/tsconfig.json deleted file mode 100644 index ea59875db2..0000000000 --- a/examples/aws-monorepo/packages/core/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@tsconfig/node20/tsconfig.json", - "compilerOptions": { - "module": "NodeNext", - "moduleResolution": "Bundler", - }, -} diff --git a/examples/aws-monorepo/packages/frontend/index.html b/examples/aws-monorepo/packages/frontend/index.html deleted file mode 100644 index 800ee5dbc2..0000000000 --- a/examples/aws-monorepo/packages/frontend/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - Vite App - - -

Vite is running in %MODE%

-

api: %VITE_API_URL%

- - - diff --git a/examples/aws-monorepo/packages/frontend/package.json b/examples/aws-monorepo/packages/frontend/package.json deleted file mode 100644 index 6a6424629f..0000000000 --- a/examples/aws-monorepo/packages/frontend/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@aws-monorepo/frontend", - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build" - }, - "devDependencies": { - "vite": "^5.2.8", - "sst": "file:../../../../sdk/js" - } -} diff --git a/examples/aws-monorepo/packages/frontend/vite.config.ts b/examples/aws-monorepo/packages/frontend/vite.config.ts deleted file mode 100644 index 0c4b848dbd..0000000000 --- a/examples/aws-monorepo/packages/frontend/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from "vite"; - -export default defineConfig({ - server: { - host: "0.0.0.0", - }, -}); diff --git a/examples/aws-monorepo/packages/functions/package.json b/examples/aws-monorepo/packages/functions/package.json deleted file mode 100644 index 9fd4eb3af9..0000000000 --- a/examples/aws-monorepo/packages/functions/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@aws-monorepo/functions", - "version": "0.0.0", - "dependencies": { - "@aws-monorepo/core": "*", - "sst": "file:../../../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.137", - "sst": "file:../../../../sdk/js" - } -} diff --git a/examples/aws-monorepo/packages/functions/src/api.ts b/examples/aws-monorepo/packages/functions/src/api.ts deleted file mode 100644 index 4b1bf2a200..0000000000 --- a/examples/aws-monorepo/packages/functions/src/api.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Resource } from "sst"; -import { Handler } from "aws-lambda"; -import { Example } from "@aws-monorepo/core/example"; - -export const handler: Handler = async (event) => { - console.log( - "this is a long time as a test for the long and to see if it wraps and here cool wow", - ); - return { - statusCode: 200, - body: `${Example.hello()} Linked to ${Resource.Database.name}.`, - }; -}; diff --git a/examples/aws-monorepo/packages/functions/tsconfig.json b/examples/aws-monorepo/packages/functions/tsconfig.json deleted file mode 100644 index ea59875db2..0000000000 --- a/examples/aws-monorepo/packages/functions/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@tsconfig/node20/tsconfig.json", - "compilerOptions": { - "module": "NodeNext", - "moduleResolution": "Bundler", - }, -} diff --git a/examples/aws-monorepo/packages/scripts/package.json b/examples/aws-monorepo/packages/scripts/package.json deleted file mode 100644 index c8b78ff82a..0000000000 --- a/examples/aws-monorepo/packages/scripts/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@aws-monorepo/scripts", - "version": "0.0.0", - "dependencies": { - "@aws-monorepo/core": "*", - "sst": "file:../../../../sdk/js" - }, - "scripts": { - "shell": "sst shell tsx" - }, - "devDependencies": { - "tsx": "^4.7.2" - } -} diff --git a/examples/aws-monorepo/packages/scripts/src/example.ts b/examples/aws-monorepo/packages/scripts/src/example.ts deleted file mode 100644 index 1e9ac7bb9a..0000000000 --- a/examples/aws-monorepo/packages/scripts/src/example.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { Resource } from "sst"; -import { Example } from "@aws-monorepo/core/example"; - -console.log(`${Example.hello()} Linked to ${Resource.Database.name}.`); diff --git a/examples/aws-monorepo/packages/scripts/tsconfig.json b/examples/aws-monorepo/packages/scripts/tsconfig.json deleted file mode 100644 index ea59875db2..0000000000 --- a/examples/aws-monorepo/packages/scripts/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@tsconfig/node20/tsconfig.json", - "compilerOptions": { - "module": "NodeNext", - "moduleResolution": "Bundler", - }, -} diff --git a/examples/aws-monorepo/sst.config.ts b/examples/aws-monorepo/sst.config.ts deleted file mode 100644 index 724d416c16..0000000000 --- a/examples/aws-monorepo/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-monorepo", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const infra = await import("./infra"); - - return { - api: infra.api.url, - astro: infra.astro.url, - }; - }, -}); diff --git a/examples/aws-monorepo/tsconfig.json b/examples/aws-monorepo/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-monorepo/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-multi-region/index.ts b/examples/aws-multi-region/index.ts deleted file mode 100644 index 0f59768d5e..0000000000 --- a/examples/aws-multi-region/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export async function handler() { - return { - statusCode: 200, - body: `Hello from ${process.env.AWS_REGION}`, - }; -} diff --git a/examples/aws-multi-region/package.json b/examples/aws-multi-region/package.json deleted file mode 100644 index b2370c5519..0000000000 --- a/examples/aws-multi-region/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-multi-region", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.145", - "@types/node": "^22.5.4" - } -} diff --git a/examples/aws-multi-region/sst.config.ts b/examples/aws-multi-region/sst.config.ts deleted file mode 100644 index a11d183110..0000000000 --- a/examples/aws-multi-region/sst.config.ts +++ /dev/null @@ -1,51 +0,0 @@ -/// - -/** - * ## AWS multi-region - * - * To deploy resources to multiple AWS regions, you can create a new provider for the region - * you want to deploy to. - * - * ```ts title="sst.config.ts" - * const provider = new aws.Provider("MyProvider", { region: "us-west-2" }); - * ``` - * - * And then pass that in to the resource. - * - * ```ts title="sst.config.ts" - * new sst.aws.Function("MyFunction", { handler: "index.handler" }, { provider }); - * ``` - * - * If no provider is passed in, the default provider will be used. And if no region is - * specified, the default region from your credentials will be used. - */ -export default $config({ - app(input) { - return { - name: "aws-multi-region", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const east = new sst.aws.Function("MyEastFunction", { - url: true, - handler: "index.handler", - }); - - const provider = new aws.Provider("MyWestProvider", { region: "us-west-2" }); - const west = new sst.aws.Function( - "MyWestFunction", - { - url: true, - handler: "index.handler", - }, - { provider } - ); - - return { - east: east.url, - west: west.url, - }; - }, -}); diff --git a/examples/aws-mysql-local/.gitignore b/examples/aws-mysql-local/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-mysql-local/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-mysql-local/index.ts b/examples/aws-mysql-local/index.ts deleted file mode 100644 index 7d1712321c..0000000000 --- a/examples/aws-mysql-local/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -import mysql from "mysql2/promise"; -import { Resource } from "sst"; - -const connection = await mysql.createConnection({ - host: Resource.MyDatabase.host, - port: Resource.MyDatabase.port, - user: Resource.MyDatabase.username, - password: Resource.MyDatabase.password, - database: Resource.MyDatabase.database, -}); - -export async function handler() { - const [rows] = await connection.query("SELECT NOW()"); - return { - statusCode: 200, - body: `Querying ${Resource.MyDatabase.host}\n\n` + rows[0].now, - }; -} diff --git a/examples/aws-mysql-local/package.json b/examples/aws-mysql-local/package.json deleted file mode 100644 index 10eb83dc38..0000000000 --- a/examples/aws-mysql-local/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-mysql-local", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "mysql2": "3.14.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-mysql-local/sst.config.ts b/examples/aws-mysql-local/sst.config.ts deleted file mode 100644 index 374825c605..0000000000 --- a/examples/aws-mysql-local/sst.config.ts +++ /dev/null @@ -1,86 +0,0 @@ -/// - -/** - * ## AWS MySQL local - * - * In this example, we connect to a locally running MySQL instance for dev. While - * on deploy, we use RDS. - * - * We use the [`docker run`](https://docs.docker.com/reference/cli/docker/container/run/) CLI - * to start a local container with MySQL. You don't have to use Docker, you can use - * any other way to run MySQL locally. - * - * ```bash - * docker run \ - * --rm \ - * -p 3306:3306 \ - * -v $(pwd)/.sst/storage/mysql:/var/lib/mysql/data \ - * -e MYSQL_ROOT_PASSWORD=password \ - * -e MYSQL_DATABASE=local \ - * mysql:8.0 - * ``` - * - * The data is saved to the `.sst/storage` directory. So if you restart the dev server, the - * data will still be there. - * - * We then configure the `dev` property of the `Mysql` component with the settings for the - * local MySQL instance. - * - * ```ts title="sst.config.ts" - * dev: { - * username: "root", - * password: "password", - * database: "local", - * host: "localhost", - * port: 3306, - * } - * ``` - * - * By providing the `dev` prop for Mysql, SST will use the local MySQL instance and - * not deploy a new RDS database when running `sst dev`. - * - * It also allows us to access the database through a Resource `link` without having to - * conditionally check if we are running locally. - * - * ```ts title="index.ts" - * const pool = new Pool({ - * host: Resource.MyDatabase.host, - * port: Resource.MyDatabase.port, - * user: Resource.MyDatabase.username, - * password: Resource.MyDatabase.password, - * database: Resource.MyDatabase.database, - * }); - * ``` - * - * The above will work in both `sst dev` and `sst deploy`. - */ -export default $config({ - app(input) { - return { - name: "aws-mysql-local", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "ec2" }); - - const mysql = new sst.aws.Mysql("MyDatabase", { - dev: { - username: "root", - password: "password", - database: "local", - host: "localhost", - port: 3306, - }, - vpc, - }); - - new sst.aws.Function("MyFunction", { - vpc, - url: true, - link: [mysql], - handler: "index.handler", - }); - }, -}); diff --git a/examples/aws-mysql-local/tsconfig.json b/examples/aws-mysql-local/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-mysql-local/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-mysql/index.ts b/examples/aws-mysql/index.ts deleted file mode 100644 index e589834de9..0000000000 --- a/examples/aws-mysql/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -import mysql from "mysql2/promise"; -import { Resource } from "sst"; - -const connection = await mysql.createConnection({ - host: Resource.MyDatabase.host, - port: Resource.MyDatabase.port, - user: Resource.MyDatabase.username, - password: Resource.MyDatabase.password, - database: Resource.MyDatabase.database, -}); - -export async function handler() { - const [rows] = await connection.execute("SELECT NOW()"); - return { - statusCode: 200, - body: `Querying ${Resource.MyDatabase.host}\n\n` + rows[0]['NOW()'], - }; -} diff --git a/examples/aws-mysql/package.json b/examples/aws-mysql/package.json deleted file mode 100644 index cdf175cd3c..0000000000 --- a/examples/aws-mysql/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-mysql", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "mysql2": "3.14.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-mysql/sst.config.ts b/examples/aws-mysql/sst.config.ts deleted file mode 100644 index f5baedce72..0000000000 --- a/examples/aws-mysql/sst.config.ts +++ /dev/null @@ -1,79 +0,0 @@ -/// - -/** - * ## AWS MySQL - * - * In this example, we deploy an RDS MySQL database. - * - * ```ts title="sst.config.ts" - * const mysql = new sst.aws.Mysql("MyDatabase", { - * vpc, - * }); - * ``` - * - * And link it to a Lambda function. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Function("MyApp", { - * handler: "index.handler", - * link: [mysql], - * url: true, - * vpc, - * }); - * ``` - * - * Now in the function we can access the database. - * - * ```ts title="index.ts" - * const connection = await mysql.createConnection({ - * database: Resource.MyDatabase.database, - * host: Resource.MyDatabase.host, - * port: Resource.MyDatabase.port, - * user: Resource.MyDatabase.username, - * password: Resource.MyDatabase.password, - * }); - * ``` - * - * We also enable the `bastion` option for the VPC. This allows us to connect to - * the database from our local machine with the `sst tunnel` CLI. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only - * need to do this once on your machine. - * - * Now you can run `npx sst dev` and you can connect to the database from your local machine. - * - */ -export default $config({ - app(input) { - return { - name: "aws-mysql", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "ec2", bastion: true }); - const mysql = new sst.aws.Mysql("MyDatabase", { - vpc, - }); - const app = new sst.aws.Function("MyApp", { - handler: "index.handler", - link: [mysql], - url: true, - vpc, - }); - - return { - app: app.url, - host: mysql.host, - port: mysql.port, - username: mysql.username, - password: mysql.password, - database: mysql.database, - }; - }, -}); diff --git a/examples/aws-nestjs-container/.dockerignore b/examples/aws-nestjs-container/.dockerignore deleted file mode 100644 index 3b5d5cb550..0000000000 --- a/examples/aws-nestjs-container/.dockerignore +++ /dev/null @@ -1,6 +0,0 @@ -dist -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-nestjs-container/.eslintrc.js b/examples/aws-nestjs-container/.eslintrc.js deleted file mode 100644 index 259de13c73..0000000000 --- a/examples/aws-nestjs-container/.eslintrc.js +++ /dev/null @@ -1,25 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', - parserOptions: { - project: 'tsconfig.json', - tsconfigRootDir: __dirname, - sourceType: 'module', - }, - plugins: ['@typescript-eslint/eslint-plugin'], - extends: [ - 'plugin:@typescript-eslint/recommended', - 'plugin:prettier/recommended', - ], - root: true, - env: { - node: true, - jest: true, - }, - ignorePatterns: ['.eslintrc.js'], - rules: { - '@typescript-eslint/interface-name-prefix': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/explicit-module-boundary-types': 'off', - '@typescript-eslint/no-explicit-any': 'off', - }, -}; diff --git a/examples/aws-nestjs-container/.gitignore b/examples/aws-nestjs-container/.gitignore deleted file mode 100644 index 8e0d8ec3b0..0000000000 --- a/examples/aws-nestjs-container/.gitignore +++ /dev/null @@ -1,59 +0,0 @@ -# compiled output -/dist -/node_modules -/build - -# Logs -logs -*.log -npm-debug.log* -pnpm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* - -# OS -.DS_Store - -# Tests -/coverage -/.nyc_output - -# IDEs and editors -/.idea -.project -.classpath -.c9/ -*.launch -.settings/ -*.sublime-workspace - -# IDE - VSCode -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -# dotenv environment variable files -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# temp directory -.temp -.tmp - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json - -# sst -.sst diff --git a/examples/aws-nestjs-container/.prettierrc b/examples/aws-nestjs-container/.prettierrc deleted file mode 100644 index dcb72794f5..0000000000 --- a/examples/aws-nestjs-container/.prettierrc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all" -} \ No newline at end of file diff --git a/examples/aws-nestjs-container/Dockerfile b/examples/aws-nestjs-container/Dockerfile deleted file mode 100644 index 143907a2df..0000000000 --- a/examples/aws-nestjs-container/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:22 - -WORKDIR /usr/src/app -COPY package*.json ./ -RUN npm install -COPY . . -RUN npm run build - -EXPOSE 3000 -CMD ["node", "dist/main"] diff --git a/examples/aws-nestjs-container/nest-cli.json b/examples/aws-nestjs-container/nest-cli.json deleted file mode 100644 index f9aa683b1a..0000000000 --- a/examples/aws-nestjs-container/nest-cli.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/nest-cli", - "collection": "@nestjs/schematics", - "sourceRoot": "src", - "compilerOptions": { - "deleteOutDir": true - } -} diff --git a/examples/aws-nestjs-container/package.json b/examples/aws-nestjs-container/package.json deleted file mode 100644 index 0beae8372e..0000000000 --- a/examples/aws-nestjs-container/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "aws-nestjs-container", - "version": "0.0.1", - "description": "", - "author": "", - "private": true, - "license": "UNLICENSED", - "scripts": { - "build": "nest build", - "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", - "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", - "start": "nest start", - "start:debug": "nest start --debug --watch", - "start:dev": "nest start --watch", - "start:prod": "node dist/main", - "test": "jest", - "test:cov": "jest --coverage", - "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", - "test:e2e": "jest --config ./test/jest-e2e.json", - "test:watch": "jest --watch" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.717.0", - "@aws-sdk/lib-storage": "^3.717.0", - "@aws-sdk/s3-request-presigner": "^3.717.0", - "@nestjs/common": "^10.0.0", - "@nestjs/core": "^10.0.0", - "@nestjs/platform-express": "^10.0.0", - "reflect-metadata": "^0.2.0", - "rxjs": "^7.8.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@nestjs/cli": "^10.0.0", - "@nestjs/schematics": "^10.0.0", - "@nestjs/testing": "^10.0.0", - "@types/aws-lambda": "8.10.146", - "@types/express": "^5.0.0", - "@types/jest": "^29.5.2", - "@types/multer": "^1.4.12", - "@types/node": "^20.3.1", - "@types/supertest": "^6.0.0", - "@typescript-eslint/eslint-plugin": "^8.0.0", - "@typescript-eslint/parser": "^8.0.0", - "eslint": "^8.0.0", - "eslint-config-prettier": "^9.0.0", - "eslint-plugin-prettier": "^5.0.0", - "jest": "^29.5.0", - "prettier": "^3.0.0", - "source-map-support": "^0.5.21", - "supertest": "^7.0.0", - "ts-jest": "^29.1.0", - "ts-loader": "^9.4.3", - "ts-node": "^10.9.1", - "tsconfig-paths": "^4.2.0", - "typescript": "^5.1.3" - }, - "jest": { - "collectCoverageFrom": [ - "**/*.(t|j)s" - ], - "coverageDirectory": "../coverage", - "moduleFileExtensions": [ - "js", - "json", - "ts" - ], - "rootDir": "src", - "testEnvironment": "node", - "testRegex": ".*\\.spec\\.ts$", - "transform": { - "^.+\\.(t|j)s$": "ts-jest" - } - } -} diff --git a/examples/aws-nestjs-container/src/app.controller.spec.ts b/examples/aws-nestjs-container/src/app.controller.spec.ts deleted file mode 100644 index d22f3890a3..0000000000 --- a/examples/aws-nestjs-container/src/app.controller.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { AppController } from './app.controller'; -import { AppService } from './app.service'; - -describe('AppController', () => { - let appController: AppController; - - beforeEach(async () => { - const app: TestingModule = await Test.createTestingModule({ - controllers: [AppController], - providers: [AppService], - }).compile(); - - appController = app.get(AppController); - }); - - describe('root', () => { - it('should return "Hello World!"', () => { - expect(appController.getHello()).toBe('Hello World!'); - }); - }); -}); diff --git a/examples/aws-nestjs-container/src/app.controller.ts b/examples/aws-nestjs-container/src/app.controller.ts deleted file mode 100644 index 1c84dea417..0000000000 --- a/examples/aws-nestjs-container/src/app.controller.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { - S3Client, - GetObjectCommand, - ListObjectsV2Command, -} from '@aws-sdk/client-s3'; -import { Resource } from 'sst'; -import { Express } from 'express'; -import { Upload } from '@aws-sdk/lib-storage'; -import { FileInterceptor } from '@nestjs/platform-express'; -import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; -import { Controller, Get, Post, Redirect, UploadedFile, UseInterceptors } from '@nestjs/common'; -import { AppService } from './app.service'; - -const s3 = new S3Client({}); - -@Controller() -export class AppController { - constructor(private readonly appService: AppService) { } - - @Get() - getHello(): string { - return this.appService.getHello(); - } - - @Post() - @UseInterceptors(FileInterceptor('file')) - async uploadFile(@UploadedFile() file: Express.Multer.File): Promise { - const params = { - Bucket: Resource.MyBucket.name, - ContentType: file.mimetype, - Key: file.originalname, - Body: file.buffer, - }; - - const upload = new Upload({ - params, - client: s3, - }); - - await upload.done(); - - return 'File uploaded successfully.'; - } - - @Get('latest') - @Redirect('/', 302) - async getLatestFile() { - const objects = await s3.send( - new ListObjectsV2Command({ - Bucket: Resource.MyBucket.name, - }), - ); - - const latestFile = objects.Contents.sort( - (a, b) => b.LastModified.getTime() - a.LastModified.getTime(), - )[0]; - - const command = new GetObjectCommand({ - Key: latestFile.Key, - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(s3, command); - - return { url }; - } -} diff --git a/examples/aws-nestjs-container/src/app.module.ts b/examples/aws-nestjs-container/src/app.module.ts deleted file mode 100644 index 86628031ca..0000000000 --- a/examples/aws-nestjs-container/src/app.module.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Module } from '@nestjs/common'; -import { AppController } from './app.controller'; -import { AppService } from './app.service'; - -@Module({ - imports: [], - controllers: [AppController], - providers: [AppService], -}) -export class AppModule {} diff --git a/examples/aws-nestjs-container/src/app.service.ts b/examples/aws-nestjs-container/src/app.service.ts deleted file mode 100644 index 927d7cca0b..0000000000 --- a/examples/aws-nestjs-container/src/app.service.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Injectable } from '@nestjs/common'; - -@Injectable() -export class AppService { - getHello(): string { - return 'Hello World!'; - } -} diff --git a/examples/aws-nestjs-container/src/main.ts b/examples/aws-nestjs-container/src/main.ts deleted file mode 100644 index f76bc8d977..0000000000 --- a/examples/aws-nestjs-container/src/main.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { NestFactory } from '@nestjs/core'; -import { AppModule } from './app.module'; - -async function bootstrap() { - const app = await NestFactory.create(AppModule); - await app.listen(process.env.PORT ?? 3000); -} -bootstrap(); diff --git a/examples/aws-nestjs-container/sst.config.ts b/examples/aws-nestjs-container/sst.config.ts deleted file mode 100644 index a5f5a85951..0000000000 --- a/examples/aws-nestjs-container/sst.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: 'aws-nestjs-container', - removal: input?.stage === 'production' ? 'retain' : 'remove', - protect: ['production'].includes(input?.stage), - home: 'aws', - }; - }, - async run() { - const vpc = new sst.aws.Vpc('MyVpc'); - const bucket = new sst.aws.Bucket('MyBucket'); - - const cluster = new sst.aws.Cluster('MyCluster', { vpc }); - - new sst.aws.Service('MyService', { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: '80/http', forward: '3000/http' }], - }, - dev: { - command: 'npm run start:dev', - }, - }); - }, -}); diff --git a/examples/aws-nestjs-container/test/app.e2e-spec.ts b/examples/aws-nestjs-container/test/app.e2e-spec.ts deleted file mode 100644 index 50cda62332..0000000000 --- a/examples/aws-nestjs-container/test/app.e2e-spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { INestApplication } from '@nestjs/common'; -import * as request from 'supertest'; -import { AppModule } from './../src/app.module'; - -describe('AppController (e2e)', () => { - let app: INestApplication; - - beforeEach(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [AppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - it('/ (GET)', () => { - return request(app.getHttpServer()) - .get('/') - .expect(200) - .expect('Hello World!'); - }); -}); diff --git a/examples/aws-nestjs-container/test/jest-e2e.json b/examples/aws-nestjs-container/test/jest-e2e.json deleted file mode 100644 index e9d912f3e3..0000000000 --- a/examples/aws-nestjs-container/test/jest-e2e.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "moduleFileExtensions": ["js", "json", "ts"], - "rootDir": ".", - "testEnvironment": "node", - "testRegex": ".e2e-spec.ts$", - "transform": { - "^.+\\.(t|j)s$": "ts-jest" - } -} diff --git a/examples/aws-nestjs-container/tsconfig.build.json b/examples/aws-nestjs-container/tsconfig.build.json deleted file mode 100644 index 64f86c6bd2..0000000000 --- a/examples/aws-nestjs-container/tsconfig.build.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "./tsconfig.json", - "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] -} diff --git a/examples/aws-nestjs-container/tsconfig.json b/examples/aws-nestjs-container/tsconfig.json deleted file mode 100644 index 162793367a..0000000000 --- a/examples/aws-nestjs-container/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "declaration": true, - "removeComments": true, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "allowSyntheticDefaultImports": true, - "target": "ES2021", - "sourceMap": true, - "outDir": "./dist", - "baseUrl": "./", - "incremental": true, - "skipLibCheck": true, - "strictNullChecks": false, - "noImplicitAny": false, - "strictBindCallApply": false, - "forceConsistentCasingInFileNames": false, - "noFallthroughCasesInSwitch": false - }, - "include": ["src/**/*", "test/**/*", "sst-env.d.ts"] -} diff --git a/examples/aws-nestjs-redis/.dockerignore b/examples/aws-nestjs-redis/.dockerignore deleted file mode 100644 index 533d93408b..0000000000 --- a/examples/aws-nestjs-redis/.dockerignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -dist - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-nestjs-redis/.eslintrc.js b/examples/aws-nestjs-redis/.eslintrc.js deleted file mode 100644 index 259de13c73..0000000000 --- a/examples/aws-nestjs-redis/.eslintrc.js +++ /dev/null @@ -1,25 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', - parserOptions: { - project: 'tsconfig.json', - tsconfigRootDir: __dirname, - sourceType: 'module', - }, - plugins: ['@typescript-eslint/eslint-plugin'], - extends: [ - 'plugin:@typescript-eslint/recommended', - 'plugin:prettier/recommended', - ], - root: true, - env: { - node: true, - jest: true, - }, - ignorePatterns: ['.eslintrc.js'], - rules: { - '@typescript-eslint/interface-name-prefix': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/explicit-module-boundary-types': 'off', - '@typescript-eslint/no-explicit-any': 'off', - }, -}; diff --git a/examples/aws-nestjs-redis/.gitignore b/examples/aws-nestjs-redis/.gitignore deleted file mode 100644 index 8e0d8ec3b0..0000000000 --- a/examples/aws-nestjs-redis/.gitignore +++ /dev/null @@ -1,59 +0,0 @@ -# compiled output -/dist -/node_modules -/build - -# Logs -logs -*.log -npm-debug.log* -pnpm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* - -# OS -.DS_Store - -# Tests -/coverage -/.nyc_output - -# IDEs and editors -/.idea -.project -.classpath -.c9/ -*.launch -.settings/ -*.sublime-workspace - -# IDE - VSCode -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -# dotenv environment variable files -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# temp directory -.temp -.tmp - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json - -# sst -.sst diff --git a/examples/aws-nestjs-redis/.prettierrc b/examples/aws-nestjs-redis/.prettierrc deleted file mode 100644 index dcb72794f5..0000000000 --- a/examples/aws-nestjs-redis/.prettierrc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all" -} \ No newline at end of file diff --git a/examples/aws-nestjs-redis/Dockerfile b/examples/aws-nestjs-redis/Dockerfile deleted file mode 100644 index 143907a2df..0000000000 --- a/examples/aws-nestjs-redis/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:22 - -WORKDIR /usr/src/app -COPY package*.json ./ -RUN npm install -COPY . . -RUN npm run build - -EXPOSE 3000 -CMD ["node", "dist/main"] diff --git a/examples/aws-nestjs-redis/nest-cli.json b/examples/aws-nestjs-redis/nest-cli.json deleted file mode 100644 index f9aa683b1a..0000000000 --- a/examples/aws-nestjs-redis/nest-cli.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/nest-cli", - "collection": "@nestjs/schematics", - "sourceRoot": "src", - "compilerOptions": { - "deleteOutDir": true - } -} diff --git a/examples/aws-nestjs-redis/package.json b/examples/aws-nestjs-redis/package.json deleted file mode 100644 index 83fae61d50..0000000000 --- a/examples/aws-nestjs-redis/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "name": "aws-nestjs-redis", - "version": "0.0.1", - "description": "", - "author": "", - "private": true, - "license": "UNLICENSED", - "scripts": { - "build": "nest build", - "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", - "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", - "start": "nest start", - "start:debug": "nest start --debug --watch", - "start:dev": "nest start --watch", - "start:prod": "node dist/main", - "test": "jest", - "test:cov": "jest --coverage", - "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", - "test:e2e": "jest --config ./test/jest-e2e.json", - "test:watch": "jest --watch" - }, - "dependencies": { - "@nestjs/common": "^10.0.0", - "@nestjs/core": "^10.0.0", - "@nestjs/platform-express": "^10.0.0", - "ioredis": "^5.4.1", - "reflect-metadata": "^0.2.0", - "rxjs": "^7.8.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@nestjs/cli": "^10.0.0", - "@nestjs/schematics": "^10.0.0", - "@nestjs/testing": "^10.0.0", - "@types/aws-lambda": "8.10.145", - "@types/express": "^4.17.17", - "@types/jest": "^29.5.2", - "@types/node": "^20.3.1", - "@types/supertest": "^6.0.0", - "@typescript-eslint/eslint-plugin": "^8.0.0", - "@typescript-eslint/parser": "^8.0.0", - "eslint": "^8.42.0", - "eslint-config-prettier": "^9.0.0", - "eslint-plugin-prettier": "^5.0.0", - "jest": "^29.5.0", - "prettier": "^3.0.0", - "source-map-support": "^0.5.21", - "supertest": "^7.0.0", - "ts-jest": "^29.1.0", - "ts-loader": "^9.4.3", - "ts-node": "^10.9.1", - "tsconfig-paths": "^4.2.0", - "typescript": "^5.1.3" - }, - "jest": { - "collectCoverageFrom": [ - "**/*.(t|j)s" - ], - "coverageDirectory": "../coverage", - "moduleFileExtensions": [ - "js", - "json", - "ts" - ], - "rootDir": "src", - "testEnvironment": "node", - "testRegex": ".*\\.spec\\.ts$", - "transform": { - "^.+\\.(t|j)s$": "ts-jest" - } - } -} diff --git a/examples/aws-nestjs-redis/src/app.controller.spec.ts b/examples/aws-nestjs-redis/src/app.controller.spec.ts deleted file mode 100644 index d22f3890a3..0000000000 --- a/examples/aws-nestjs-redis/src/app.controller.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { AppController } from './app.controller'; -import { AppService } from './app.service'; - -describe('AppController', () => { - let appController: AppController; - - beforeEach(async () => { - const app: TestingModule = await Test.createTestingModule({ - controllers: [AppController], - providers: [AppService], - }).compile(); - - appController = app.get(AppController); - }); - - describe('root', () => { - it('should return "Hello World!"', () => { - expect(appController.getHello()).toBe('Hello World!'); - }); - }); -}); diff --git a/examples/aws-nestjs-redis/src/app.controller.ts b/examples/aws-nestjs-redis/src/app.controller.ts deleted file mode 100644 index e821e40746..0000000000 --- a/examples/aws-nestjs-redis/src/app.controller.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Controller, Get } from '@nestjs/common'; -import { AppService } from './app.service'; - -@Controller() -export class AppController { - constructor(private readonly appService: AppService) { } - - @Get() - async getCounter(): Promise { - return (await this.appService.getCounter()).toString(); - } -} diff --git a/examples/aws-nestjs-redis/src/app.module.ts b/examples/aws-nestjs-redis/src/app.module.ts deleted file mode 100644 index 86628031ca..0000000000 --- a/examples/aws-nestjs-redis/src/app.module.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Module } from '@nestjs/common'; -import { AppController } from './app.controller'; -import { AppService } from './app.service'; - -@Module({ - imports: [], - controllers: [AppController], - providers: [AppService], -}) -export class AppModule {} diff --git a/examples/aws-nestjs-redis/src/app.service.ts b/examples/aws-nestjs-redis/src/app.service.ts deleted file mode 100644 index 25a01b7010..0000000000 --- a/examples/aws-nestjs-redis/src/app.service.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Injectable } from '@nestjs/common'; -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -@Injectable() -export class AppService { - getHello(): string { - return 'Hello World!'; - } - - async getCounter(): Promise { - return await redis.incr("counter"); - } -} diff --git a/examples/aws-nestjs-redis/src/main.ts b/examples/aws-nestjs-redis/src/main.ts deleted file mode 100644 index 13cad38cff..0000000000 --- a/examples/aws-nestjs-redis/src/main.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { NestFactory } from '@nestjs/core'; -import { AppModule } from './app.module'; - -async function bootstrap() { - const app = await NestFactory.create(AppModule); - await app.listen(3000); -} -bootstrap(); diff --git a/examples/aws-nestjs-redis/sst.config.ts b/examples/aws-nestjs-redis/sst.config.ts deleted file mode 100644 index dcc3f4aa0f..0000000000 --- a/examples/aws-nestjs-redis/sst.config.ts +++ /dev/null @@ -1,75 +0,0 @@ -/// - -/** - * ## AWS NestJS with Redis - * - * Creates a hit counter app with NestJS and Redis. - * - * :::note - * You need Node 22.12 or higher for this example to work. - * ::: - * - * Also make sure you have Node 22.12. Or set the `--experimental-require-module` flag. - * This'll allow NestJS to import the SST SDK. - * - * This deploys NestJS as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "npm run start:dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:3000` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it using `npx sst deploy --stage production` using a `Dockerfile` - * that's included in the example. - */ -export default $config({ - app(input) { - return { - name: 'aws-nestjs-redis', - removal: input?.stage === 'production' ? 'retain' : 'remove', - home: 'aws', - }; - }, - async run() { - const vpc = new sst.aws.Vpc('MyVpc', { bastion: true }); - const redis = new sst.aws.Redis('MyRedis', { vpc }); - const cluster = new sst.aws.Cluster('MyCluster', { vpc }); - - new sst.aws.Service('MyService', { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: '80/http', forward: '3000/http' }], - }, - dev: { - command: 'npm run start:dev', - }, - }); - }, -}); diff --git a/examples/aws-nestjs-redis/test/app.e2e-spec.ts b/examples/aws-nestjs-redis/test/app.e2e-spec.ts deleted file mode 100644 index 50cda62332..0000000000 --- a/examples/aws-nestjs-redis/test/app.e2e-spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { INestApplication } from '@nestjs/common'; -import * as request from 'supertest'; -import { AppModule } from './../src/app.module'; - -describe('AppController (e2e)', () => { - let app: INestApplication; - - beforeEach(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [AppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - it('/ (GET)', () => { - return request(app.getHttpServer()) - .get('/') - .expect(200) - .expect('Hello World!'); - }); -}); diff --git a/examples/aws-nestjs-redis/test/jest-e2e.json b/examples/aws-nestjs-redis/test/jest-e2e.json deleted file mode 100644 index e9d912f3e3..0000000000 --- a/examples/aws-nestjs-redis/test/jest-e2e.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "moduleFileExtensions": ["js", "json", "ts"], - "rootDir": ".", - "testEnvironment": "node", - "testRegex": ".e2e-spec.ts$", - "transform": { - "^.+\\.(t|j)s$": "ts-jest" - } -} diff --git a/examples/aws-nestjs-redis/tsconfig.build.json b/examples/aws-nestjs-redis/tsconfig.build.json deleted file mode 100644 index 64f86c6bd2..0000000000 --- a/examples/aws-nestjs-redis/tsconfig.build.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "./tsconfig.json", - "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] -} diff --git a/examples/aws-nestjs-redis/tsconfig.json b/examples/aws-nestjs-redis/tsconfig.json deleted file mode 100644 index bf0b1c3ad8..0000000000 --- a/examples/aws-nestjs-redis/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "declaration": true, - "removeComments": true, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "allowSyntheticDefaultImports": true, - "target": "ES2021", - "sourceMap": true, - "outDir": "./dist", - "baseUrl": "./", - "incremental": true, - "skipLibCheck": true, - "strictNullChecks": false, - "noImplicitAny": false, - "strictBindCallApply": false, - "forceConsistentCasingInFileNames": false, - "noFallthroughCasesInSwitch": false - }, - "include": ["src/**/*", "test/**/*", "sst-env.d.ts"], -} diff --git a/examples/aws-nextjs-add-behavior/.gitignore b/examples/aws-nextjs-add-behavior/.gitignore deleted file mode 100644 index 3ecba30f1c..0000000000 --- a/examples/aws-nextjs-add-behavior/.gitignore +++ /dev/null @@ -1,46 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/versions - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# env files (can opt-in for commiting if needed) -.env* - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-nextjs-add-behavior/app/favicon.ico b/examples/aws-nextjs-add-behavior/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-nextjs-add-behavior/app/favicon.ico and /dev/null differ diff --git a/examples/aws-nextjs-add-behavior/app/fonts/GeistMonoVF.woff b/examples/aws-nextjs-add-behavior/app/fonts/GeistMonoVF.woff deleted file mode 100644 index f2ae185cbf..0000000000 Binary files a/examples/aws-nextjs-add-behavior/app/fonts/GeistMonoVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-add-behavior/app/fonts/GeistVF.woff b/examples/aws-nextjs-add-behavior/app/fonts/GeistVF.woff deleted file mode 100644 index 1b62daacff..0000000000 Binary files a/examples/aws-nextjs-add-behavior/app/fonts/GeistVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-add-behavior/app/globals.css b/examples/aws-nextjs-add-behavior/app/globals.css deleted file mode 100644 index e3734be15e..0000000000 --- a/examples/aws-nextjs-add-behavior/app/globals.css +++ /dev/null @@ -1,42 +0,0 @@ -:root { - --background: #ffffff; - --foreground: #171717; -} - -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: var(--foreground); - background: var(--background); - font-family: Arial, Helvetica, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-nextjs-add-behavior/app/layout.tsx b/examples/aws-nextjs-add-behavior/app/layout.tsx deleted file mode 100644 index dca06aee77..0000000000 --- a/examples/aws-nextjs-add-behavior/app/layout.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type { Metadata } from "next"; -import localFont from "next/font/local"; -import "./globals.css"; - -const geistSans = localFont({ - src: "./fonts/GeistVF.woff", - variable: "--font-geist-sans", - weight: "100 900", -}); -const geistMono = localFont({ - src: "./fonts/GeistMonoVF.woff", - variable: "--font-geist-mono", - weight: "100 900", -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-nextjs-add-behavior/app/page.module.css b/examples/aws-nextjs-add-behavior/app/page.module.css deleted file mode 100644 index ee9b8e6339..0000000000 --- a/examples/aws-nextjs-add-behavior/app/page.module.css +++ /dev/null @@ -1,168 +0,0 @@ -.page { - --gray-rgb: 0, 0, 0; - --gray-alpha-200: rgba(var(--gray-rgb), 0.08); - --gray-alpha-100: rgba(var(--gray-rgb), 0.05); - - --button-primary-hover: #383838; - --button-secondary-hover: #f2f2f2; - - display: grid; - grid-template-rows: 20px 1fr 20px; - align-items: center; - justify-items: center; - min-height: 100svh; - padding: 80px; - gap: 64px; - font-family: var(--font-geist-sans); -} - -@media (prefers-color-scheme: dark) { - .page { - --gray-rgb: 255, 255, 255; - --gray-alpha-200: rgba(var(--gray-rgb), 0.145); - --gray-alpha-100: rgba(var(--gray-rgb), 0.06); - - --button-primary-hover: #ccc; - --button-secondary-hover: #1a1a1a; - } -} - -.main { - display: flex; - flex-direction: column; - gap: 32px; - grid-row-start: 2; -} - -.main ol { - font-family: var(--font-geist-mono); - padding-left: 0; - margin: 0; - font-size: 14px; - line-height: 24px; - letter-spacing: -0.01em; - list-style-position: inside; -} - -.main li:not(:last-of-type) { - margin-bottom: 8px; -} - -.main code { - font-family: inherit; - background: var(--gray-alpha-100); - padding: 2px 4px; - border-radius: 4px; - font-weight: 600; -} - -.ctas { - display: flex; - gap: 16px; -} - -.ctas a { - appearance: none; - border-radius: 128px; - height: 48px; - padding: 0 20px; - border: none; - border: 1px solid transparent; - transition: - background 0.2s, - color 0.2s, - border-color 0.2s; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - font-size: 16px; - line-height: 20px; - font-weight: 500; -} - -a.primary { - background: var(--foreground); - color: var(--background); - gap: 8px; -} - -a.secondary { - border-color: var(--gray-alpha-200); - min-width: 180px; -} - -.footer { - grid-row-start: 3; - display: flex; - gap: 24px; -} - -.footer a { - display: flex; - align-items: center; - gap: 8px; -} - -.footer img { - flex-shrink: 0; -} - -/* Enable hover only on non-touch devices */ -@media (hover: hover) and (pointer: fine) { - a.primary:hover { - background: var(--button-primary-hover); - border-color: transparent; - } - - a.secondary:hover { - background: var(--button-secondary-hover); - border-color: transparent; - } - - .footer a:hover { - text-decoration: underline; - text-underline-offset: 4px; - } -} - -@media (max-width: 600px) { - .page { - padding: 32px; - padding-bottom: 80px; - } - - .main { - align-items: center; - } - - .main ol { - text-align: center; - } - - .ctas { - flex-direction: column; - } - - .ctas a { - font-size: 14px; - height: 40px; - padding: 0 16px; - } - - a.secondary { - min-width: auto; - } - - .footer { - flex-wrap: wrap; - align-items: center; - justify-content: center; - } -} - -@media (prefers-color-scheme: dark) { - .logo { - filter: invert(); - } -} diff --git a/examples/aws-nextjs-add-behavior/app/page.tsx b/examples/aws-nextjs-add-behavior/app/page.tsx deleted file mode 100644 index 52bd15ee7f..0000000000 --- a/examples/aws-nextjs-add-behavior/app/page.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import Image from "next/image"; -import styles from "./page.module.css"; - -export default function Home() { - return ( -
-
- Next.js logo -
    -
  1. - Get started by editing app/page.tsx. -
  2. -
  3. Save and see your changes instantly.
  4. -
- - -
- -
- ); -} diff --git a/examples/aws-nextjs-add-behavior/next.config.ts b/examples/aws-nextjs-add-behavior/next.config.ts deleted file mode 100644 index e9ffa3083a..0000000000 --- a/examples/aws-nextjs-add-behavior/next.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { NextConfig } from "next"; - -const nextConfig: NextConfig = { - /* config options here */ -}; - -export default nextConfig; diff --git a/examples/aws-nextjs-add-behavior/package.json b/examples/aws-nextjs-add-behavior/package.json deleted file mode 100644 index aae5dbed9e..0000000000 --- a/examples/aws-nextjs-add-behavior/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "aws-nextjs-add-behavior", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "next": "15.0.1", - "react": "19.0.0-rc-69d4b800-20241021", - "react-dom": "19.0.0-rc-69d4b800-20241021", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "typescript": "^5" - } -} diff --git a/examples/aws-nextjs-add-behavior/public/file.svg b/examples/aws-nextjs-add-behavior/public/file.svg deleted file mode 100644 index 004145cddf..0000000000 --- a/examples/aws-nextjs-add-behavior/public/file.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-add-behavior/public/globe.svg b/examples/aws-nextjs-add-behavior/public/globe.svg deleted file mode 100644 index 567f17b0d7..0000000000 --- a/examples/aws-nextjs-add-behavior/public/globe.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-add-behavior/public/next.svg b/examples/aws-nextjs-add-behavior/public/next.svg deleted file mode 100644 index 5174b28c56..0000000000 --- a/examples/aws-nextjs-add-behavior/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-add-behavior/public/vercel.svg b/examples/aws-nextjs-add-behavior/public/vercel.svg deleted file mode 100644 index 7705396033..0000000000 --- a/examples/aws-nextjs-add-behavior/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-add-behavior/public/window.svg b/examples/aws-nextjs-add-behavior/public/window.svg deleted file mode 100644 index b2b2a44f6e..0000000000 --- a/examples/aws-nextjs-add-behavior/public/window.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-add-behavior/sst.config.ts b/examples/aws-nextjs-add-behavior/sst.config.ts deleted file mode 100644 index c50649d7d4..0000000000 --- a/examples/aws-nextjs-add-behavior/sst.config.ts +++ /dev/null @@ -1,73 +0,0 @@ -/// - -/** - * ## AWS Next.js add behavior - * - * Here's how to add additional routes or cache behaviors to the CDN of a Next.js app deployed - * with OpenNext to AWS. - * - * Specify the path pattern that you want to forward to your new origin. For example, to forward - * all requests to the `/blog` path to a different origin. - * - * ```ts title="sst.config.ts" - * pathPattern: "/blog/*" - * ``` - * - * And then specify the domain of the new origin. - * - * ```ts title="sst.config.ts" - * domainName: "blog.example.com" - * ``` - * - * We use this to `transform` our site's CDN and add the additional behaviors. - */ -export default $config({ - app(input) { - return { - name: "aws-nextjs-add-behavior", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const blogOrigin = { - // The domain of the new origin - domainName: "blog.example.com", - originId: "blogCustomOrigin", - customOriginConfig: { - httpPort: 80, - httpsPort: 443, - originSslProtocols: ["TLSv1.2"], - // If HTTPS is supported - originProtocolPolicy: "https-only", - }, - }; - - const cacheBehavior = { - // The path to forward to the new origin - pathPattern: "/blog/*", - targetOriginId: blogOrigin.originId, - viewerProtocolPolicy: "redirect-to-https", - allowedMethods: ["GET", "HEAD", "OPTIONS"], - cachedMethods: ["GET", "HEAD"], - forwardedValues: { - queryString: true, - cookies: { - forward: "all", - }, - }, - }; - - new sst.aws.Nextjs("MyWeb", { - transform: { - cdn: (options: sst.aws.CdnArgs) => { - options.origins = $resolve(options.origins).apply(val => [...val, blogOrigin]); - - options.orderedCacheBehaviors = $resolve( - options.orderedCacheBehaviors || [] - ).apply(val => [...val, cacheBehavior]); - }, - }, - }); - }, -}); diff --git a/examples/aws-nextjs-add-behavior/tsconfig.json b/examples/aws-nextjs-add-behavior/tsconfig.json deleted file mode 100644 index 3577577791..0000000000 --- a/examples/aws-nextjs-add-behavior/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2017", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-nextjs-basic-auth/.eslintrc.json b/examples/aws-nextjs-basic-auth/.eslintrc.json deleted file mode 100644 index 3722418549..0000000000 --- a/examples/aws-nextjs-basic-auth/.eslintrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["next/core-web-vitals", "next/typescript"] -} diff --git a/examples/aws-nextjs-basic-auth/.gitignore b/examples/aws-nextjs-basic-auth/.gitignore deleted file mode 100644 index 69d7f97469..0000000000 --- a/examples/aws-nextjs-basic-auth/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-nextjs-basic-auth/app/favicon.ico b/examples/aws-nextjs-basic-auth/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-nextjs-basic-auth/app/favicon.ico and /dev/null differ diff --git a/examples/aws-nextjs-basic-auth/app/fonts/GeistMonoVF.woff b/examples/aws-nextjs-basic-auth/app/fonts/GeistMonoVF.woff deleted file mode 100644 index f2ae185cbf..0000000000 Binary files a/examples/aws-nextjs-basic-auth/app/fonts/GeistMonoVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-basic-auth/app/fonts/GeistVF.woff b/examples/aws-nextjs-basic-auth/app/fonts/GeistVF.woff deleted file mode 100644 index 1b62daacff..0000000000 Binary files a/examples/aws-nextjs-basic-auth/app/fonts/GeistVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-basic-auth/app/globals.css b/examples/aws-nextjs-basic-auth/app/globals.css deleted file mode 100644 index e3734be15e..0000000000 --- a/examples/aws-nextjs-basic-auth/app/globals.css +++ /dev/null @@ -1,42 +0,0 @@ -:root { - --background: #ffffff; - --foreground: #171717; -} - -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: var(--foreground); - background: var(--background); - font-family: Arial, Helvetica, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-nextjs-basic-auth/app/layout.tsx b/examples/aws-nextjs-basic-auth/app/layout.tsx deleted file mode 100644 index dca06aee77..0000000000 --- a/examples/aws-nextjs-basic-auth/app/layout.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type { Metadata } from "next"; -import localFont from "next/font/local"; -import "./globals.css"; - -const geistSans = localFont({ - src: "./fonts/GeistVF.woff", - variable: "--font-geist-sans", - weight: "100 900", -}); -const geistMono = localFont({ - src: "./fonts/GeistMonoVF.woff", - variable: "--font-geist-mono", - weight: "100 900", -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-nextjs-basic-auth/app/page.module.css b/examples/aws-nextjs-basic-auth/app/page.module.css deleted file mode 100644 index 8a460419f9..0000000000 --- a/examples/aws-nextjs-basic-auth/app/page.module.css +++ /dev/null @@ -1,165 +0,0 @@ -.page { - --gray-rgb: 0, 0, 0; - --gray-alpha-200: rgba(var(--gray-rgb), 0.08); - --gray-alpha-100: rgba(var(--gray-rgb), 0.05); - - --button-primary-hover: #383838; - --button-secondary-hover: #f2f2f2; - - display: grid; - grid-template-rows: 20px 1fr 20px; - align-items: center; - justify-items: center; - min-height: 100svh; - padding: 80px; - gap: 64px; - font-family: var(--font-geist-sans); -} - -@media (prefers-color-scheme: dark) { - .page { - --gray-rgb: 255, 255, 255; - --gray-alpha-200: rgba(var(--gray-rgb), 0.145); - --gray-alpha-100: rgba(var(--gray-rgb), 0.06); - - --button-primary-hover: #ccc; - --button-secondary-hover: #1a1a1a; - } -} - -.main { - display: flex; - flex-direction: column; - gap: 32px; - grid-row-start: 2; -} - -.main ol { - font-family: var(--font-geist-mono); - padding-left: 0; - margin: 0; - font-size: 14px; - line-height: 24px; - letter-spacing: -0.01em; - list-style-position: inside; -} - -.main li:not(:last-of-type) { - margin-bottom: 8px; -} - -.main code { - font-family: inherit; - background: var(--gray-alpha-100); - padding: 2px 4px; - border-radius: 4px; - font-weight: 600; -} - -.ctas { - display: flex; - gap: 16px; -} - -.ctas a { - appearance: none; - border-radius: 128px; - height: 48px; - padding: 0 20px; - border: none; - border: 1px solid transparent; - transition: background 0.2s, color 0.2s, border-color 0.2s; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - font-size: 16px; - line-height: 20px; - font-weight: 500; -} - -a.primary { - background: var(--foreground); - color: var(--background); - gap: 8px; -} - -a.secondary { - border-color: var(--gray-alpha-200); - min-width: 180px; -} - -.footer { - grid-row-start: 3; - display: flex; - gap: 24px; -} - -.footer a { - display: flex; - align-items: center; - gap: 8px; -} - -.footer img { - flex-shrink: 0; -} - -/* Enable hover only on non-touch devices */ -@media (hover: hover) and (pointer: fine) { - a.primary:hover { - background: var(--button-primary-hover); - border-color: transparent; - } - - a.secondary:hover { - background: var(--button-secondary-hover); - border-color: transparent; - } - - .footer a:hover { - text-decoration: underline; - text-underline-offset: 4px; - } -} - -@media (max-width: 600px) { - .page { - padding: 32px; - padding-bottom: 80px; - } - - .main { - align-items: center; - } - - .main ol { - text-align: center; - } - - .ctas { - flex-direction: column; - } - - .ctas a { - font-size: 14px; - height: 40px; - padding: 0 16px; - } - - a.secondary { - min-width: auto; - } - - .footer { - flex-wrap: wrap; - align-items: center; - justify-content: center; - } -} - -@media (prefers-color-scheme: dark) { - .logo { - filter: invert(); - } -} diff --git a/examples/aws-nextjs-basic-auth/app/page.tsx b/examples/aws-nextjs-basic-auth/app/page.tsx deleted file mode 100644 index df5d042428..0000000000 --- a/examples/aws-nextjs-basic-auth/app/page.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import Image from "next/image"; -import styles from "./page.module.css"; - -export default function Home() { - return ( -
-
- Next.js logo -
    -
  1. - Get started by editing app/page.tsx. -
  2. -
  3. Save and see your changes instantly.
  4. -
- - -
- -
- ); -} diff --git a/examples/aws-nextjs-basic-auth/next.config.mjs b/examples/aws-nextjs-basic-auth/next.config.mjs deleted file mode 100644 index 4678774e6d..0000000000 --- a/examples/aws-nextjs-basic-auth/next.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = {}; - -export default nextConfig; diff --git a/examples/aws-nextjs-basic-auth/package.json b/examples/aws-nextjs-basic-auth/package.json deleted file mode 100644 index f9239740de..0000000000 --- a/examples/aws-nextjs-basic-auth/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "aws-nextjs-basic-auth", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "next": "14.2.9", - "react": "^18", - "react-dom": "^18", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "eslint": "^8", - "eslint-config-next": "14.2.9", - "typescript": "^5" - } -} diff --git a/examples/aws-nextjs-basic-auth/sst.config.ts b/examples/aws-nextjs-basic-auth/sst.config.ts deleted file mode 100644 index 775cdb274d..0000000000 --- a/examples/aws-nextjs-basic-auth/sst.config.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// - -/** - * ## AWS Next.js basic auth - * - * Deploys a simple Next.js app and adds basic auth to it. - * - * This is useful for dev environments where you want to share your app your team but ensure - * that it's not publicly accessible. - * - * :::tip - * You can use this for all the SSR sites, like Astro, Remix, SvelteKit, etc. - * ::: - * - * This works by injecting some code into a CloudFront function that checks the basic auth - * header and matches it against the `USERNAME` and `PASSWORD` secrets. - * - * ```ts title="sst.config.ts" - * { - * injection: $interpolate` - * if ( - * !event.request.headers.authorization - * || event.request.headers.authorization.value !== "Basic ${basicAuth}" - * ) { - * return { - * statusCode: 401, - * headers: { - * "www-authenticate": { value: "Basic" } - * } - * }; - * }`, - * } - * ``` - * - * To deploy this, you need to first set the `USERNAME` and `PASSWORD` secrets. - * - * ```bash - * sst secret set USERNAME my-username - * sst secret set PASSWORD my-password - * ``` - * - * If you are deploying this to preview environments, you might want to set the secrets using - * the [`--fallback`](/docs/reference/cli#secret) flag. - */ -export default $config({ - app(input) { - return { - name: "aws-nextjs-basic-auth", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const username = new sst.Secret("USERNAME"); - const password = new sst.Secret("PASSWORD"); - const basicAuth = $resolve([username.value, password.value]).apply( - ([username, password]) => - Buffer.from(`${username}:${password}`).toString("base64") - ); - - new sst.aws.Nextjs("MyWeb", { - server: { - // Don't password protect prod - edge: $app.stage !== "production" - ? { - viewerRequest: { - injection: $interpolate` - if ( - !event.request.headers.authorization - || event.request.headers.authorization.value !== "Basic ${basicAuth}" - ) { - return { - statusCode: 401, - headers: { - "www-authenticate": { value: "Basic" } - } - }; - }`, - }, - } - : undefined, - }, - }); - }, -}); diff --git a/examples/aws-nextjs-basic-auth/tsconfig.json b/examples/aws-nextjs-basic-auth/tsconfig.json deleted file mode 100644 index 56433afeb2..0000000000 --- a/examples/aws-nextjs-basic-auth/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-nextjs-container/.dockerignore b/examples/aws-nextjs-container/.dockerignore deleted file mode 100644 index d0a41b0f28..0000000000 --- a/examples/aws-nextjs-container/.dockerignore +++ /dev/null @@ -1,7 +0,0 @@ -.git -.next -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-nextjs-container/.gitignore b/examples/aws-nextjs-container/.gitignore deleted file mode 100644 index e1f9fd2d79..0000000000 --- a/examples/aws-nextjs-container/.gitignore +++ /dev/null @@ -1,46 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/versions - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# env files (can opt-in for committing if needed) -.env* - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-nextjs-container/Dockerfile b/examples/aws-nextjs-container/Dockerfile deleted file mode 100644 index ff80689629..0000000000 --- a/examples/aws-nextjs-container/Dockerfile +++ /dev/null @@ -1,26 +0,0 @@ -# https://github.com/nextjs/deploy-sst/blob/main/Dockerfile -FROM node:lts-alpine AS base - -# Stage 1: Install dependencies -FROM base AS deps -WORKDIR /app -COPY package.json package-lock.json* ./ -COPY sst-env.d.ts* ./ -RUN npm ci - -# Stage 2: Build the application -FROM base AS builder -WORKDIR /app -COPY --from=deps /app/node_modules ./node_modules -COPY . . -RUN npm run build - -# Stage 3: Production server -FROM base AS runner -WORKDIR /app -ENV NODE_ENV=production -COPY --from=builder /app/.next/standalone ./ -COPY --from=builder /app/.next/static ./.next/static - -EXPOSE 3000 -CMD ["node", "server.js"] diff --git a/examples/aws-nextjs-container/app/favicon.ico b/examples/aws-nextjs-container/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-nextjs-container/app/favicon.ico and /dev/null differ diff --git a/examples/aws-nextjs-container/app/fonts/GeistMonoVF.woff b/examples/aws-nextjs-container/app/fonts/GeistMonoVF.woff deleted file mode 100644 index f2ae185cbf..0000000000 Binary files a/examples/aws-nextjs-container/app/fonts/GeistMonoVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-container/app/fonts/GeistVF.woff b/examples/aws-nextjs-container/app/fonts/GeistVF.woff deleted file mode 100644 index 1b62daacff..0000000000 Binary files a/examples/aws-nextjs-container/app/fonts/GeistVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-container/app/globals.css b/examples/aws-nextjs-container/app/globals.css deleted file mode 100644 index e3734be15e..0000000000 --- a/examples/aws-nextjs-container/app/globals.css +++ /dev/null @@ -1,42 +0,0 @@ -:root { - --background: #ffffff; - --foreground: #171717; -} - -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: var(--foreground); - background: var(--background); - font-family: Arial, Helvetica, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-nextjs-container/app/layout.tsx b/examples/aws-nextjs-container/app/layout.tsx deleted file mode 100644 index dca06aee77..0000000000 --- a/examples/aws-nextjs-container/app/layout.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type { Metadata } from "next"; -import localFont from "next/font/local"; -import "./globals.css"; - -const geistSans = localFont({ - src: "./fonts/GeistVF.woff", - variable: "--font-geist-sans", - weight: "100 900", -}); -const geistMono = localFont({ - src: "./fonts/GeistMonoVF.woff", - variable: "--font-geist-mono", - weight: "100 900", -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-nextjs-container/app/page.module.css b/examples/aws-nextjs-container/app/page.module.css deleted file mode 100644 index ee9b8e6339..0000000000 --- a/examples/aws-nextjs-container/app/page.module.css +++ /dev/null @@ -1,168 +0,0 @@ -.page { - --gray-rgb: 0, 0, 0; - --gray-alpha-200: rgba(var(--gray-rgb), 0.08); - --gray-alpha-100: rgba(var(--gray-rgb), 0.05); - - --button-primary-hover: #383838; - --button-secondary-hover: #f2f2f2; - - display: grid; - grid-template-rows: 20px 1fr 20px; - align-items: center; - justify-items: center; - min-height: 100svh; - padding: 80px; - gap: 64px; - font-family: var(--font-geist-sans); -} - -@media (prefers-color-scheme: dark) { - .page { - --gray-rgb: 255, 255, 255; - --gray-alpha-200: rgba(var(--gray-rgb), 0.145); - --gray-alpha-100: rgba(var(--gray-rgb), 0.06); - - --button-primary-hover: #ccc; - --button-secondary-hover: #1a1a1a; - } -} - -.main { - display: flex; - flex-direction: column; - gap: 32px; - grid-row-start: 2; -} - -.main ol { - font-family: var(--font-geist-mono); - padding-left: 0; - margin: 0; - font-size: 14px; - line-height: 24px; - letter-spacing: -0.01em; - list-style-position: inside; -} - -.main li:not(:last-of-type) { - margin-bottom: 8px; -} - -.main code { - font-family: inherit; - background: var(--gray-alpha-100); - padding: 2px 4px; - border-radius: 4px; - font-weight: 600; -} - -.ctas { - display: flex; - gap: 16px; -} - -.ctas a { - appearance: none; - border-radius: 128px; - height: 48px; - padding: 0 20px; - border: none; - border: 1px solid transparent; - transition: - background 0.2s, - color 0.2s, - border-color 0.2s; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - font-size: 16px; - line-height: 20px; - font-weight: 500; -} - -a.primary { - background: var(--foreground); - color: var(--background); - gap: 8px; -} - -a.secondary { - border-color: var(--gray-alpha-200); - min-width: 180px; -} - -.footer { - grid-row-start: 3; - display: flex; - gap: 24px; -} - -.footer a { - display: flex; - align-items: center; - gap: 8px; -} - -.footer img { - flex-shrink: 0; -} - -/* Enable hover only on non-touch devices */ -@media (hover: hover) and (pointer: fine) { - a.primary:hover { - background: var(--button-primary-hover); - border-color: transparent; - } - - a.secondary:hover { - background: var(--button-secondary-hover); - border-color: transparent; - } - - .footer a:hover { - text-decoration: underline; - text-underline-offset: 4px; - } -} - -@media (max-width: 600px) { - .page { - padding: 32px; - padding-bottom: 80px; - } - - .main { - align-items: center; - } - - .main ol { - text-align: center; - } - - .ctas { - flex-direction: column; - } - - .ctas a { - font-size: 14px; - height: 40px; - padding: 0 16px; - } - - a.secondary { - min-width: auto; - } - - .footer { - flex-wrap: wrap; - align-items: center; - justify-content: center; - } -} - -@media (prefers-color-scheme: dark) { - .logo { - filter: invert(); - } -} diff --git a/examples/aws-nextjs-container/app/page.tsx b/examples/aws-nextjs-container/app/page.tsx deleted file mode 100644 index a7ce977382..0000000000 --- a/examples/aws-nextjs-container/app/page.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Resource } from "sst"; -import Form from "@/components/form"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; -import styles from "./page.module.css"; - -export const dynamic = "force-dynamic"; - -export default async function Home() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return ( -
-
-
-
-
- ); -} diff --git a/examples/aws-nextjs-container/components/form.module.css b/examples/aws-nextjs-container/components/form.module.css deleted file mode 100644 index 6a12c9ae58..0000000000 --- a/examples/aws-nextjs-container/components/form.module.css +++ /dev/null @@ -1,24 +0,0 @@ -.form { - padding: 2rem; - border-radius: 0.5rem; - background-color: var(--gray-alpha-100); -} - -.form input { - margin-right: 1rem; -} - -.form button { - appearance: none; - padding: 0.5rem 0.75rem; - font-weight: 500; - font-size: 0.875rem; - border-radius: 0.375rem; - background-color: transparent; - font-family: var(--font-geist-sans); - border: 1px solid var(--gray-alpha-200); -} - -.form button:active:enabled { - background-color: var(--gray-alpha-200); -} diff --git a/examples/aws-nextjs-container/components/form.tsx b/examples/aws-nextjs-container/components/form.tsx deleted file mode 100644 index adaa22afdc..0000000000 --- a/examples/aws-nextjs-container/components/form.tsx +++ /dev/null @@ -1,30 +0,0 @@ -"use client"; - -import styles from "./form.module.css"; - -export default function Form({ url }: { url: string }) { - return ( - { - e.preventDefault(); - - const file = (e.target as HTMLFormElement).file.files?.[0] ?? null; - - const image = await fetch(url, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }} - > - - - - ); -} diff --git a/examples/aws-nextjs-container/next.config.ts b/examples/aws-nextjs-container/next.config.ts deleted file mode 100644 index e23d70d906..0000000000 --- a/examples/aws-nextjs-container/next.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { NextConfig } from "next"; - -const nextConfig: NextConfig = { - /* config options here */ - output: "standalone" -}; - -export default nextConfig; diff --git a/examples/aws-nextjs-container/package.json b/examples/aws-nextjs-container/package.json deleted file mode 100644 index 9e89772fb6..0000000000 --- a/examples/aws-nextjs-container/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "aws-nextjs-container", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "next": "15.0.3", - "react": "19.0.0-rc-66855b96-20241106", - "react-dom": "19.0.0-rc-66855b96-20241106", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "typescript": "^5" - } -} diff --git a/examples/aws-nextjs-container/public/file.svg b/examples/aws-nextjs-container/public/file.svg deleted file mode 100644 index 004145cddf..0000000000 --- a/examples/aws-nextjs-container/public/file.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-container/public/globe.svg b/examples/aws-nextjs-container/public/globe.svg deleted file mode 100644 index 567f17b0d7..0000000000 --- a/examples/aws-nextjs-container/public/globe.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-container/public/next.svg b/examples/aws-nextjs-container/public/next.svg deleted file mode 100644 index 5174b28c56..0000000000 --- a/examples/aws-nextjs-container/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-container/public/vercel.svg b/examples/aws-nextjs-container/public/vercel.svg deleted file mode 100644 index 7705396033..0000000000 --- a/examples/aws-nextjs-container/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-container/public/window.svg b/examples/aws-nextjs-container/public/window.svg deleted file mode 100644 index b2b2a44f6e..0000000000 --- a/examples/aws-nextjs-container/public/window.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs-container/sst.config.ts b/examples/aws-nextjs-container/sst.config.ts deleted file mode 100644 index 5550e64e57..0000000000 --- a/examples/aws-nextjs-container/sst.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-nextjs-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - link: [bucket], - }); - }, -}); diff --git a/examples/aws-nextjs-container/tsconfig.json b/examples/aws-nextjs-container/tsconfig.json deleted file mode 100644 index 3577577791..0000000000 --- a/examples/aws-nextjs-container/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2017", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-nextjs-redis/.dockerignore b/examples/aws-nextjs-redis/.dockerignore deleted file mode 100644 index ff7df5d861..0000000000 --- a/examples/aws-nextjs-redis/.dockerignore +++ /dev/null @@ -1,12 +0,0 @@ -Dockerfile -.dockerignore -node_modules -npm-debug.log -README.md -.next -docker -.git - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-nextjs-redis/.gitignore b/examples/aws-nextjs-redis/.gitignore deleted file mode 100644 index 69d7f97469..0000000000 --- a/examples/aws-nextjs-redis/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-nextjs-redis/Dockerfile b/examples/aws-nextjs-redis/Dockerfile deleted file mode 100644 index 2d16514a6d..0000000000 --- a/examples/aws-nextjs-redis/Dockerfile +++ /dev/null @@ -1,75 +0,0 @@ -# https://github.com/vercel/next.js/tree/canary/examples/with-docker - -FROM node:18-alpine AS base - -# Install dependencies only when needed -FROM base AS deps -# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed. -RUN apk add --no-cache libc6-compat -WORKDIR /app - -COPY sst-env.d.ts* ./ - -# Install dependencies based on the preferred package manager -COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./ -RUN \ - if [ -f yarn.lock ]; then yarn --frozen-lockfile; \ - elif [ -f package-lock.json ]; then npm ci; \ - elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \ - else echo "Lockfile not found." && exit 1; \ - fi - -# Rebuild the source code only when needed -FROM base AS builder - -# Add linked resources to the environment -ARG SST_RESOURCE_MyRedis - -WORKDIR /app -COPY --from=deps /app/node_modules ./node_modules -COPY . . - -# Next.js collects completely anonymous telemetry data about general usage. -# Learn more here: https://nextjs.org/telemetry -# Uncomment the following line in case you want to disable telemetry during the build. -# ENV NEXT_TELEMETRY_DISABLED=1 - -RUN \ - if [ -f yarn.lock ]; then yarn run build; \ - elif [ -f package-lock.json ]; then npm run build; \ - elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \ - else echo "Lockfile not found." && exit 1; \ - fi - -# Production image, copy all the files and run next -FROM base AS runner -WORKDIR /app - -ENV NODE_ENV=production -# Uncomment the following line in case you want to disable telemetry during runtime. -# ENV NEXT_TELEMETRY_DISABLED=1 - -RUN addgroup --system --gid 1001 nodejs -RUN adduser --system --uid 1001 nextjs - -COPY --from=builder /app/public* ./public - -# Set the correct permission for prerender cache -RUN mkdir .next -RUN chown nextjs:nodejs .next - -# Automatically leverage output traces to reduce image size -# https://nextjs.org/docs/advanced-features/output-file-tracing -COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ -COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static - -USER nextjs - -EXPOSE 3000 - -ENV PORT=3000 - -# server.js is created by next build from the standalone output -# https://nextjs.org/docs/pages/api-reference/next-config-js/output -ENV HOSTNAME="0.0.0.0" -CMD ["node", "server.js"] diff --git a/examples/aws-nextjs-redis/app/favicon.ico b/examples/aws-nextjs-redis/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-nextjs-redis/app/favicon.ico and /dev/null differ diff --git a/examples/aws-nextjs-redis/app/fonts/GeistMonoVF.woff b/examples/aws-nextjs-redis/app/fonts/GeistMonoVF.woff deleted file mode 100644 index f2ae185cbf..0000000000 Binary files a/examples/aws-nextjs-redis/app/fonts/GeistMonoVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-redis/app/fonts/GeistVF.woff b/examples/aws-nextjs-redis/app/fonts/GeistVF.woff deleted file mode 100644 index 1b62daacff..0000000000 Binary files a/examples/aws-nextjs-redis/app/fonts/GeistVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-redis/app/globals.css b/examples/aws-nextjs-redis/app/globals.css deleted file mode 100644 index e3734be15e..0000000000 --- a/examples/aws-nextjs-redis/app/globals.css +++ /dev/null @@ -1,42 +0,0 @@ -:root { - --background: #ffffff; - --foreground: #171717; -} - -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: var(--foreground); - background: var(--background); - font-family: Arial, Helvetica, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-nextjs-redis/app/layout.tsx b/examples/aws-nextjs-redis/app/layout.tsx deleted file mode 100644 index dca06aee77..0000000000 --- a/examples/aws-nextjs-redis/app/layout.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type { Metadata } from "next"; -import localFont from "next/font/local"; -import "./globals.css"; - -const geistSans = localFont({ - src: "./fonts/GeistVF.woff", - variable: "--font-geist-sans", - weight: "100 900", -}); -const geistMono = localFont({ - src: "./fonts/GeistMonoVF.woff", - variable: "--font-geist-mono", - weight: "100 900", -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-nextjs-redis/app/page.module.css b/examples/aws-nextjs-redis/app/page.module.css deleted file mode 100644 index 51ed5f08db..0000000000 --- a/examples/aws-nextjs-redis/app/page.module.css +++ /dev/null @@ -1,41 +0,0 @@ -.page { - --gray-rgb: 0, 0, 0; - --gray-alpha-200: rgba(var(--gray-rgb), 0.08); - --gray-alpha-100: rgba(var(--gray-rgb), 0.05); - - --button-primary-hover: #383838; - --button-secondary-hover: #f2f2f2; - - display: grid; - grid-template-rows: 20px 1fr 20px; - align-items: center; - justify-items: center; - min-height: 100svh; - padding: 80px; - gap: 64px; - font-family: var(--font-geist-sans); -} - -@media (prefers-color-scheme: dark) { - .page { - --gray-rgb: 255, 255, 255; - --gray-alpha-200: rgba(var(--gray-rgb), 0.145); - --gray-alpha-100: rgba(var(--gray-rgb), 0.06); - - --button-primary-hover: #ccc; - --button-secondary-hover: #1a1a1a; - } -} - -.main { - display: flex; - flex-direction: column; - gap: 32px; - grid-row-start: 2; -} - -.main p { - font-family: var(--font-geist-mono); - font-size: 14px; - letter-spacing: -0.01em; -} diff --git a/examples/aws-nextjs-redis/app/page.tsx b/examples/aws-nextjs-redis/app/page.tsx deleted file mode 100644 index 09eda0ef92..0000000000 --- a/examples/aws-nextjs-redis/app/page.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; -import styles from "./page.module.css"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -export const dynamic = "force-dynamic"; - -export default async function Home() { - const counter = await redis.incr("counter"); - - return ( -
-
-

Hit counter: {counter}

-
-
- ); -} diff --git a/examples/aws-nextjs-redis/next.config.mjs b/examples/aws-nextjs-redis/next.config.mjs deleted file mode 100644 index 68dea63186..0000000000 --- a/examples/aws-nextjs-redis/next.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = { - output: "standalone" -}; - -export default nextConfig; diff --git a/examples/aws-nextjs-redis/package.json b/examples/aws-nextjs-redis/package.json deleted file mode 100644 index cc3f62615b..0000000000 --- a/examples/aws-nextjs-redis/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "aws-nextjs-redis", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "ioredis": "^5.4.1", - "next": "14.2.14", - "react": "^18", - "react-dom": "^18", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "typescript": "^5" - } -} diff --git a/examples/aws-nextjs-redis/sst.config.ts b/examples/aws-nextjs-redis/sst.config.ts deleted file mode 100644 index edc3bb7886..0000000000 --- a/examples/aws-nextjs-redis/sst.config.ts +++ /dev/null @@ -1,71 +0,0 @@ -/// - -/** - * ## AWS Next.js container with Redis - * - * Creates a hit counter app with Next.js and Redis. - * - * This deploys Next.js as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "npm run dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:3000` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it by: - * - * 1. Setting `output: "standalone"` in your `next.config.mjs` file. - * 2. Adding a `Dockerfile` that's included in this example. - * 3. Running `npx sst deploy --stage production`. - */ -export default $config({ - app(input) { - return { - name: "aws-nextjs-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-nextjs-redis/tsconfig.json b/examples/aws-nextjs-redis/tsconfig.json deleted file mode 100644 index 56433afeb2..0000000000 --- a/examples/aws-nextjs-redis/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-nextjs-stream/.gitignore b/examples/aws-nextjs-stream/.gitignore deleted file mode 100644 index 69d7f97469..0000000000 --- a/examples/aws-nextjs-stream/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-nextjs-stream/app/favicon.ico b/examples/aws-nextjs-stream/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-nextjs-stream/app/favicon.ico and /dev/null differ diff --git a/examples/aws-nextjs-stream/app/fonts/GeistMonoVF.woff b/examples/aws-nextjs-stream/app/fonts/GeistMonoVF.woff deleted file mode 100644 index f2ae185cbf..0000000000 Binary files a/examples/aws-nextjs-stream/app/fonts/GeistMonoVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-stream/app/fonts/GeistVF.woff b/examples/aws-nextjs-stream/app/fonts/GeistVF.woff deleted file mode 100644 index 1b62daacff..0000000000 Binary files a/examples/aws-nextjs-stream/app/fonts/GeistVF.woff and /dev/null differ diff --git a/examples/aws-nextjs-stream/app/globals.css b/examples/aws-nextjs-stream/app/globals.css deleted file mode 100644 index 8f2485f332..0000000000 --- a/examples/aws-nextjs-stream/app/globals.css +++ /dev/null @@ -1,8 +0,0 @@ -body { - font-family: Arial, sans-serif; - margin: 0; - padding: 0; - background-color: #f0f8ff; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} diff --git a/examples/aws-nextjs-stream/app/layout.tsx b/examples/aws-nextjs-stream/app/layout.tsx deleted file mode 100644 index dca06aee77..0000000000 --- a/examples/aws-nextjs-stream/app/layout.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type { Metadata } from "next"; -import localFont from "next/font/local"; -import "./globals.css"; - -const geistSans = localFont({ - src: "./fonts/GeistVF.woff", - variable: "--font-geist-sans", - weight: "100 900", -}); -const geistMono = localFont({ - src: "./fonts/GeistMonoVF.woff", - variable: "--font-geist-mono", - weight: "100 900", -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-nextjs-stream/app/page.module.css b/examples/aws-nextjs-stream/app/page.module.css deleted file mode 100644 index 579a1e6288..0000000000 --- a/examples/aws-nextjs-stream/app/page.module.css +++ /dev/null @@ -1,5 +0,0 @@ -.container { - max-width: 800px; - margin: 0 auto; - padding: 20px; -} diff --git a/examples/aws-nextjs-stream/app/page.tsx b/examples/aws-nextjs-stream/app/page.tsx deleted file mode 100644 index 00597dbc40..0000000000 --- a/examples/aws-nextjs-stream/app/page.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { Suspense } from "react"; -import Bio from "@/components/bio"; -import Friends from "@/components/friends"; -import styles from "./page.module.css"; - -export const dynamic = "force-dynamic"; - -export default async function Home() { - return ( -
- - -
-

Friends from Bikini Bottom

- Loading...
}> - - - - - ); -} diff --git a/examples/aws-nextjs-stream/components/bio.module.css b/examples/aws-nextjs-stream/components/bio.module.css deleted file mode 100644 index e07167d438..0000000000 --- a/examples/aws-nextjs-stream/components/bio.module.css +++ /dev/null @@ -1,15 +0,0 @@ -.section { - background-color: #fff; - padding: 20px; - margin-bottom: 20px; - border-radius: 10px; -} -.content { - display: flex; - align-items: center; -} -.text { - flex: 1; - padding-right: 20px; -} - diff --git a/examples/aws-nextjs-stream/components/bio.tsx b/examples/aws-nextjs-stream/components/bio.tsx deleted file mode 100644 index 8c116ce0f7..0000000000 --- a/examples/aws-nextjs-stream/components/bio.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import styles from "./bio.module.css"; - -const spongebob = { - name: "SpongeBob SquarePants", - description: "SpongeBob SquarePants is the main character of the popular animated TV series. He's a cheerful sea sponge who lives in a pineapple house in the underwater city of Bikini Bottom. SpongeBob works as a fry cook at the Krusty Krab and loves jellyfishing with his best friend Patrick Star.", - image: "spongebob.png", -}; - -export default function Bio({ }) { - return ( -
-

{spongebob.name}

-
-
-

{spongebob.description}

-
- {spongebob.name} -
-
- ); -} diff --git a/examples/aws-nextjs-stream/components/friends.module.css b/examples/aws-nextjs-stream/components/friends.module.css deleted file mode 100644 index c04d006655..0000000000 --- a/examples/aws-nextjs-stream/components/friends.module.css +++ /dev/null @@ -1,16 +0,0 @@ -.grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); - gap: 20px; -} -.card { - background-color: #fff; - padding: 10px; - border-radius: 5px; - text-align: center; -} -.img { - max-width: 100%; - height: auto; - border-radius: 5px; -} diff --git a/examples/aws-nextjs-stream/components/friends.tsx b/examples/aws-nextjs-stream/components/friends.tsx deleted file mode 100644 index ee01bd962c..0000000000 --- a/examples/aws-nextjs-stream/components/friends.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import styles from "./friends.module.css"; - -interface Character { - name: string; - image: string; -} - -function friendsPromise() { - return new Promise((resolve) => { - setTimeout(() => { - resolve( - [ - { name: "Patrick Star", image: "patrick.png" }, - { name: "Sandy Cheeks", image: "sandy.png" }, - { name: "Squidward Tentacles", image: "squidward.png" }, - { name: "Mr. Krabs", image: "mr-krabs.png" }, - ] - ); - }, 3000); - }); -} - -export default async function Friends() { - const friends = await friendsPromise() as Character[]; - - return ( -
- {friends.map((friend) => ( -
- {friend.name} -

{friend.name}

-
- ))} -
- ); -} diff --git a/examples/aws-nextjs-stream/next.config.mjs b/examples/aws-nextjs-stream/next.config.mjs deleted file mode 100644 index 4678774e6d..0000000000 --- a/examples/aws-nextjs-stream/next.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = {}; - -export default nextConfig; diff --git a/examples/aws-nextjs-stream/open-next.config.ts b/examples/aws-nextjs-stream/open-next.config.ts deleted file mode 100644 index 15aa84d402..0000000000 --- a/examples/aws-nextjs-stream/open-next.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -const config = { - default: { - override: { - wrapper: "aws-lambda-streaming", - }, - }, -}; - -export default config; diff --git a/examples/aws-nextjs-stream/package.json b/examples/aws-nextjs-stream/package.json deleted file mode 100644 index 324de7960c..0000000000 --- a/examples/aws-nextjs-stream/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "aws-nextjs-stream", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "next": "14.2.12", - "react": "^18", - "react-dom": "^18", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "typescript": "^5" - } -} diff --git a/examples/aws-nextjs-stream/public/mr-krabs.png b/examples/aws-nextjs-stream/public/mr-krabs.png deleted file mode 100644 index e94ea64054..0000000000 Binary files a/examples/aws-nextjs-stream/public/mr-krabs.png and /dev/null differ diff --git a/examples/aws-nextjs-stream/public/patrick.png b/examples/aws-nextjs-stream/public/patrick.png deleted file mode 100644 index 030eaaf8a3..0000000000 Binary files a/examples/aws-nextjs-stream/public/patrick.png and /dev/null differ diff --git a/examples/aws-nextjs-stream/public/sandy.png b/examples/aws-nextjs-stream/public/sandy.png deleted file mode 100644 index eb7a9cc324..0000000000 Binary files a/examples/aws-nextjs-stream/public/sandy.png and /dev/null differ diff --git a/examples/aws-nextjs-stream/public/spongebob.png b/examples/aws-nextjs-stream/public/spongebob.png deleted file mode 100644 index 18f7df537e..0000000000 Binary files a/examples/aws-nextjs-stream/public/spongebob.png and /dev/null differ diff --git a/examples/aws-nextjs-stream/public/squidward.png b/examples/aws-nextjs-stream/public/squidward.png deleted file mode 100644 index 4af85e000b..0000000000 Binary files a/examples/aws-nextjs-stream/public/squidward.png and /dev/null differ diff --git a/examples/aws-nextjs-stream/sst.config.ts b/examples/aws-nextjs-stream/sst.config.ts deleted file mode 100644 index 866bda8298..0000000000 --- a/examples/aws-nextjs-stream/sst.config.ts +++ /dev/null @@ -1,53 +0,0 @@ -/// - -/** - * ## AWS Next.js streaming - * - * An example of how to use streaming Next.js RSC. Uses `Suspense` to stream an async component. - * - * ```tsx title="app/page.tsx" - * Loading...}> - * - * - * ``` - * - * For this demo we also need to make sure the route is not statically built. - * - * ```ts title="app/page.tsx" - * export const dynamic = "force-dynamic"; - * ``` - * - * This is deployed with OpenNext, which needs a config to enable streaming. - * - * ```ts title="open-next.config.ts" {4} - * export default { - * default: { - * override: { - * wrapper: "aws-lambda-streaming" - * } - * } - * }; - * ``` - * - * You should see the _friends_ section load after a 3 second delay. - * - * :::note - * Safari handles streaming differently than other browsers. - * ::: - * - * Safari uses a [different heuristic](https://bugs.webkit.org/show_bug.cgi?id=252413) to - * determine when to stream data. You need to render _enough_ initial HTML to trigger streaming. - * This is typically only a problem for demo apps. - */ -export default $config({ - app(input) { - return { - name: "aws-nextjs-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Nextjs("MyWeb"); - }, -}); diff --git a/examples/aws-nextjs-stream/tsconfig.json b/examples/aws-nextjs-stream/tsconfig.json deleted file mode 100644 index 56433afeb2..0000000000 --- a/examples/aws-nextjs-stream/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-nextjs/.gitignore b/examples/aws-nextjs/.gitignore deleted file mode 100644 index 69d7f97469..0000000000 --- a/examples/aws-nextjs/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-nextjs/app/favicon.ico b/examples/aws-nextjs/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-nextjs/app/favicon.ico and /dev/null differ diff --git a/examples/aws-nextjs/app/fonts/GeistMonoVF.woff b/examples/aws-nextjs/app/fonts/GeistMonoVF.woff deleted file mode 100644 index f2ae185cbf..0000000000 Binary files a/examples/aws-nextjs/app/fonts/GeistMonoVF.woff and /dev/null differ diff --git a/examples/aws-nextjs/app/fonts/GeistVF.woff b/examples/aws-nextjs/app/fonts/GeistVF.woff deleted file mode 100644 index 1b62daacff..0000000000 Binary files a/examples/aws-nextjs/app/fonts/GeistVF.woff and /dev/null differ diff --git a/examples/aws-nextjs/app/globals.css b/examples/aws-nextjs/app/globals.css deleted file mode 100644 index e3734be15e..0000000000 --- a/examples/aws-nextjs/app/globals.css +++ /dev/null @@ -1,42 +0,0 @@ -:root { - --background: #ffffff; - --foreground: #171717; -} - -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: var(--foreground); - background: var(--background); - font-family: Arial, Helvetica, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-nextjs/app/layout.tsx b/examples/aws-nextjs/app/layout.tsx deleted file mode 100644 index dca06aee77..0000000000 --- a/examples/aws-nextjs/app/layout.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import type { Metadata } from "next"; -import localFont from "next/font/local"; -import "./globals.css"; - -const geistSans = localFont({ - src: "./fonts/GeistVF.woff", - variable: "--font-geist-sans", - weight: "100 900", -}); -const geistMono = localFont({ - src: "./fonts/GeistMonoVF.woff", - variable: "--font-geist-mono", - weight: "100 900", -}); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-nextjs/app/page.module.css b/examples/aws-nextjs/app/page.module.css deleted file mode 100644 index 8a460419f9..0000000000 --- a/examples/aws-nextjs/app/page.module.css +++ /dev/null @@ -1,165 +0,0 @@ -.page { - --gray-rgb: 0, 0, 0; - --gray-alpha-200: rgba(var(--gray-rgb), 0.08); - --gray-alpha-100: rgba(var(--gray-rgb), 0.05); - - --button-primary-hover: #383838; - --button-secondary-hover: #f2f2f2; - - display: grid; - grid-template-rows: 20px 1fr 20px; - align-items: center; - justify-items: center; - min-height: 100svh; - padding: 80px; - gap: 64px; - font-family: var(--font-geist-sans); -} - -@media (prefers-color-scheme: dark) { - .page { - --gray-rgb: 255, 255, 255; - --gray-alpha-200: rgba(var(--gray-rgb), 0.145); - --gray-alpha-100: rgba(var(--gray-rgb), 0.06); - - --button-primary-hover: #ccc; - --button-secondary-hover: #1a1a1a; - } -} - -.main { - display: flex; - flex-direction: column; - gap: 32px; - grid-row-start: 2; -} - -.main ol { - font-family: var(--font-geist-mono); - padding-left: 0; - margin: 0; - font-size: 14px; - line-height: 24px; - letter-spacing: -0.01em; - list-style-position: inside; -} - -.main li:not(:last-of-type) { - margin-bottom: 8px; -} - -.main code { - font-family: inherit; - background: var(--gray-alpha-100); - padding: 2px 4px; - border-radius: 4px; - font-weight: 600; -} - -.ctas { - display: flex; - gap: 16px; -} - -.ctas a { - appearance: none; - border-radius: 128px; - height: 48px; - padding: 0 20px; - border: none; - border: 1px solid transparent; - transition: background 0.2s, color 0.2s, border-color 0.2s; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - font-size: 16px; - line-height: 20px; - font-weight: 500; -} - -a.primary { - background: var(--foreground); - color: var(--background); - gap: 8px; -} - -a.secondary { - border-color: var(--gray-alpha-200); - min-width: 180px; -} - -.footer { - grid-row-start: 3; - display: flex; - gap: 24px; -} - -.footer a { - display: flex; - align-items: center; - gap: 8px; -} - -.footer img { - flex-shrink: 0; -} - -/* Enable hover only on non-touch devices */ -@media (hover: hover) and (pointer: fine) { - a.primary:hover { - background: var(--button-primary-hover); - border-color: transparent; - } - - a.secondary:hover { - background: var(--button-secondary-hover); - border-color: transparent; - } - - .footer a:hover { - text-decoration: underline; - text-underline-offset: 4px; - } -} - -@media (max-width: 600px) { - .page { - padding: 32px; - padding-bottom: 80px; - } - - .main { - align-items: center; - } - - .main ol { - text-align: center; - } - - .ctas { - flex-direction: column; - } - - .ctas a { - font-size: 14px; - height: 40px; - padding: 0 16px; - } - - a.secondary { - min-width: auto; - } - - .footer { - flex-wrap: wrap; - align-items: center; - justify-content: center; - } -} - -@media (prefers-color-scheme: dark) { - .logo { - filter: invert(); - } -} diff --git a/examples/aws-nextjs/app/page.tsx b/examples/aws-nextjs/app/page.tsx deleted file mode 100644 index a7ce977382..0000000000 --- a/examples/aws-nextjs/app/page.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Resource } from "sst"; -import Form from "@/components/form"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; -import styles from "./page.module.css"; - -export const dynamic = "force-dynamic"; - -export default async function Home() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return ( -
-
-
-
-
- ); -} diff --git a/examples/aws-nextjs/components/form.module.css b/examples/aws-nextjs/components/form.module.css deleted file mode 100644 index 6a12c9ae58..0000000000 --- a/examples/aws-nextjs/components/form.module.css +++ /dev/null @@ -1,24 +0,0 @@ -.form { - padding: 2rem; - border-radius: 0.5rem; - background-color: var(--gray-alpha-100); -} - -.form input { - margin-right: 1rem; -} - -.form button { - appearance: none; - padding: 0.5rem 0.75rem; - font-weight: 500; - font-size: 0.875rem; - border-radius: 0.375rem; - background-color: transparent; - font-family: var(--font-geist-sans); - border: 1px solid var(--gray-alpha-200); -} - -.form button:active:enabled { - background-color: var(--gray-alpha-200); -} diff --git a/examples/aws-nextjs/components/form.tsx b/examples/aws-nextjs/components/form.tsx deleted file mode 100644 index adaa22afdc..0000000000 --- a/examples/aws-nextjs/components/form.tsx +++ /dev/null @@ -1,30 +0,0 @@ -"use client"; - -import styles from "./form.module.css"; - -export default function Form({ url }: { url: string }) { - return ( - { - e.preventDefault(); - - const file = (e.target as HTMLFormElement).file.files?.[0] ?? null; - - const image = await fetch(url, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }} - > - - - - ); -} diff --git a/examples/aws-nextjs/next.config.mjs b/examples/aws-nextjs/next.config.mjs deleted file mode 100644 index 4678774e6d..0000000000 --- a/examples/aws-nextjs/next.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = {}; - -export default nextConfig; diff --git a/examples/aws-nextjs/package.json b/examples/aws-nextjs/package.json deleted file mode 100644 index 5c3a68a25a..0000000000 --- a/examples/aws-nextjs/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "aws-nextjs", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.668.0", - "@aws-sdk/s3-request-presigner": "^3.668.0", - "next": "14.2.15", - "react": "^18", - "react-dom": "^18", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "typescript": "^5" - } -} diff --git a/examples/aws-nextjs/public/next.svg b/examples/aws-nextjs/public/next.svg deleted file mode 100644 index 5174b28c56..0000000000 --- a/examples/aws-nextjs/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs/public/vercel.svg b/examples/aws-nextjs/public/vercel.svg deleted file mode 100644 index d2f8422273..0000000000 --- a/examples/aws-nextjs/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-nextjs/sst.config.ts b/examples/aws-nextjs/sst.config.ts deleted file mode 100644 index fd9b633273..0000000000 --- a/examples/aws-nextjs/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-nextjs", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public" - }); - new sst.aws.Nextjs("MyWeb", { - link: [bucket] - }); - } -}); diff --git a/examples/aws-nextjs/tsconfig.json b/examples/aws-nextjs/tsconfig.json deleted file mode 100644 index 56433afeb2..0000000000 --- a/examples/aws-nextjs/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-nuxt-container/.dockerignore b/examples/aws-nuxt-container/.dockerignore deleted file mode 100644 index ea0aaeeec9..0000000000 --- a/examples/aws-nuxt-container/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-nuxt-container/.gitignore b/examples/aws-nuxt-container/.gitignore deleted file mode 100644 index cf7b41ed76..0000000000 --- a/examples/aws-nuxt-container/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# Nuxt dev/build outputs -.output -.data -.nuxt -.nitro -.cache -dist - -# Node dependencies -node_modules - -# Logs -logs -*.log - -# Misc -.DS_Store -.fleet -.idea - -# Local env files -.env -.env.* -!.env.example - -# sst -.sst diff --git a/examples/aws-nuxt-container/Dockerfile b/examples/aws-nuxt-container/Dockerfile deleted file mode 100644 index eb842b02d5..0000000000 --- a/examples/aws-nuxt-container/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM node:lts AS base - -WORKDIR /src - -# Build -FROM base as build - -COPY --link package.json package-lock.json ./ -RUN npm install - -COPY --link . . - -RUN npm run build - -# Run -FROM base - -ENV PORT=3000 -ENV NODE_ENV=production - -COPY --from=build /src/.output /src/.output - -CMD [ "node", ".output/server/index.mjs" ] diff --git a/examples/aws-nuxt-container/app.vue b/examples/aws-nuxt-container/app.vue deleted file mode 100644 index 66c4a4c37a..0000000000 --- a/examples/aws-nuxt-container/app.vue +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/examples/aws-nuxt-container/nuxt.config.ts b/examples/aws-nuxt-container/nuxt.config.ts deleted file mode 100644 index 6425fa7cd8..0000000000 --- a/examples/aws-nuxt-container/nuxt.config.ts +++ /dev/null @@ -1,5 +0,0 @@ -// https://nuxt.com/docs/api/configuration/nuxt-config -export default defineNuxtConfig({ - compatibilityDate: '2024-04-03', - devtools: { enabled: true } -}) diff --git a/examples/aws-nuxt-container/package.json b/examples/aws-nuxt-container/package.json deleted file mode 100644 index 962195505a..0000000000 --- a/examples/aws-nuxt-container/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-nuxt-container", - "private": true, - "type": "module", - "scripts": { - "build": "nuxt build", - "dev": "nuxt dev", - "generate": "nuxt generate", - "postinstall": "nuxt prepare", - "preview": "nuxt preview" - }, - "dependencies": { - "ioredis": "^5.4.1", - "nuxt": "^3.13.0", - "sst": "file:../../sdk/js", - "vue": "latest", - "vue-router": "latest" - }, - "overrides": { - "nitropack": "npm:nitropack-nightly@latest" - } -} diff --git a/examples/aws-nuxt-container/public/favicon.ico b/examples/aws-nuxt-container/public/favicon.ico deleted file mode 100644 index 18993ad91c..0000000000 Binary files a/examples/aws-nuxt-container/public/favicon.ico and /dev/null differ diff --git a/examples/aws-nuxt-container/public/robots.txt b/examples/aws-nuxt-container/public/robots.txt deleted file mode 100644 index 8b13789179..0000000000 --- a/examples/aws-nuxt-container/public/robots.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/aws-nuxt-container/server/api/counter.ts b/examples/aws-nuxt-container/server/api/counter.ts deleted file mode 100644 index b46ecd1276..0000000000 --- a/examples/aws-nuxt-container/server/api/counter.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -export default defineEventHandler(async () => { - return await redis.incr("counter"); -}) diff --git a/examples/aws-nuxt-container/server/tsconfig.json b/examples/aws-nuxt-container/server/tsconfig.json deleted file mode 100644 index b9ed69c19e..0000000000 --- a/examples/aws-nuxt-container/server/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../.nuxt/tsconfig.server.json" -} diff --git a/examples/aws-nuxt-container/sst.config.ts b/examples/aws-nuxt-container/sst.config.ts deleted file mode 100644 index ef36277d5d..0000000000 --- a/examples/aws-nuxt-container/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-nuxt-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-nuxt-container/tsconfig.json b/examples/aws-nuxt-container/tsconfig.json deleted file mode 100644 index a746f2a70c..0000000000 --- a/examples/aws-nuxt-container/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - // https://nuxt.com/docs/guide/concepts/typescript - "extends": "./.nuxt/tsconfig.json" -} diff --git a/examples/aws-nuxt-stream/.gitignore b/examples/aws-nuxt-stream/.gitignore deleted file mode 100644 index cf7b41ed76..0000000000 --- a/examples/aws-nuxt-stream/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# Nuxt dev/build outputs -.output -.data -.nuxt -.nitro -.cache -dist - -# Node dependencies -node_modules - -# Logs -logs -*.log - -# Misc -.DS_Store -.fleet -.idea - -# Local env files -.env -.env.* -!.env.example - -# sst -.sst diff --git a/examples/aws-nuxt-stream/app.vue b/examples/aws-nuxt-stream/app.vue deleted file mode 100644 index c7e6100872..0000000000 --- a/examples/aws-nuxt-stream/app.vue +++ /dev/null @@ -1,30 +0,0 @@ - - - diff --git a/examples/aws-nuxt-stream/nuxt.config.ts b/examples/aws-nuxt-stream/nuxt.config.ts deleted file mode 100644 index c67efbbe32..0000000000 --- a/examples/aws-nuxt-stream/nuxt.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -// https://nuxt.com/docs/api/configuration/nuxt-config -export default defineNuxtConfig({ - ignore: ['**/.sst/**'], - compatibilityDate: '2025-05-15', - nitro: { - preset: 'aws-lambda', - awsLambda: { - streaming: true - } - }, - devtools: { enabled: true } -}) diff --git a/examples/aws-nuxt-stream/package.json b/examples/aws-nuxt-stream/package.json deleted file mode 100644 index 34569ea7a4..0000000000 --- a/examples/aws-nuxt-stream/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "nuxt-app", - "private": true, - "type": "module", - "scripts": { - "build": "nuxt build", - "dev": "nuxt dev", - "generate": "nuxt generate", - "postinstall": "nuxt prepare", - "preview": "nuxt preview" - }, - "dependencies": { - "nuxt": "^3.15.5", - "sst": "file:../../sdk/js", - "vue": "latest", - "vue-router": "latest" - } -} diff --git a/examples/aws-nuxt-stream/public/favicon.ico b/examples/aws-nuxt-stream/public/favicon.ico deleted file mode 100644 index 18993ad91c..0000000000 Binary files a/examples/aws-nuxt-stream/public/favicon.ico and /dev/null differ diff --git a/examples/aws-nuxt-stream/public/robots.txt b/examples/aws-nuxt-stream/public/robots.txt deleted file mode 100644 index 8b13789179..0000000000 --- a/examples/aws-nuxt-stream/public/robots.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/aws-nuxt-stream/server/api/streaming.ts b/examples/aws-nuxt-stream/server/api/streaming.ts deleted file mode 100644 index d237103432..0000000000 --- a/examples/aws-nuxt-stream/server/api/streaming.ts +++ /dev/null @@ -1,20 +0,0 @@ -export default defineEventHandler(async (event) => { - const eventStream = createEventStream(event); - - eventStream.push("Start\n\n"); - - const interval = setInterval(async () => { - await eventStream.push(`Random: ${Math.random().toFixed(5)} `); - }, 1000); - - setTimeout(async () => { - clearInterval(interval); - await eventStream.close(); - }, 10000); - - eventStream.onClosed(() => { - clearInterval(interval); - }); - - return eventStream.send(); -}) diff --git a/examples/aws-nuxt-stream/server/tsconfig.json b/examples/aws-nuxt-stream/server/tsconfig.json deleted file mode 100644 index b9ed69c19e..0000000000 --- a/examples/aws-nuxt-stream/server/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../.nuxt/tsconfig.server.json" -} diff --git a/examples/aws-nuxt-stream/sst.config.ts b/examples/aws-nuxt-stream/sst.config.ts deleted file mode 100644 index cb1615d890..0000000000 --- a/examples/aws-nuxt-stream/sst.config.ts +++ /dev/null @@ -1,86 +0,0 @@ -/// - -/** - * ## AWS Nuxt streaming - * - * An example of how to use streaming with Nuxt.js. Uses `createEventStream` to stream data from a server API. - * - * ```ts title="server/api/streaming.ts" - * export default defineEventHandler(async (event) => { - * const eventStream = createEventStream(event); - * eventStream.push("Start\n\n"); - * - * // Send a message every second - * const interval = setInterval(async () => { - * await eventStream.push(`Random: ${Math.random().toFixed(5)} `); - * }, 1000); - * } - * ``` - * - * The client uses the Fetch API to consume the stream. - * - * ```vue title="app.vue" - * - * - * - * ``` - * - * Make sure to have your nuxt.config.ts set up to handle the streaming API correctly. - * - * ```ts title="nuxt.config.ts" {4-6} - * export default defineNuxtConfig({ - * nitro: { - * preset: 'aws-lambda', - * awsLambda: { - * streaming: true - * } - * } - * }); - * ``` - * - * You should see random numbers streamed to the page every second for 10 seconds. - * - * :::note - * Safari handles streaming differently than other browsers. - * ::: - * - * Safari uses a [different heuristic](https://bugs.webkit.org/show_bug.cgi?id=252413) to - * determine when to stream data. You need to render _enough_ initial HTML to trigger streaming. - * This is typically only a problem for demo apps. - */ -export default $config({ - app(input) { - return { - name: "aws-nuxt-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Nuxt("MyWeb"); - }, -}); diff --git a/examples/aws-nuxt-stream/tsconfig.json b/examples/aws-nuxt-stream/tsconfig.json deleted file mode 100644 index a746f2a70c..0000000000 --- a/examples/aws-nuxt-stream/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - // https://nuxt.com/docs/guide/concepts/typescript - "extends": "./.nuxt/tsconfig.json" -} diff --git a/examples/aws-nuxt/.gitignore b/examples/aws-nuxt/.gitignore deleted file mode 100644 index cf7b41ed76..0000000000 --- a/examples/aws-nuxt/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# Nuxt dev/build outputs -.output -.data -.nuxt -.nitro -.cache -dist - -# Node dependencies -node_modules - -# Logs -logs -*.log - -# Misc -.DS_Store -.fleet -.idea - -# Local env files -.env -.env.* -!.env.example - -# sst -.sst diff --git a/examples/aws-nuxt/app.vue b/examples/aws-nuxt/app.vue deleted file mode 100644 index 5947ef77d1..0000000000 --- a/examples/aws-nuxt/app.vue +++ /dev/null @@ -1,24 +0,0 @@ - - diff --git a/examples/aws-nuxt/nuxt.config.ts b/examples/aws-nuxt/nuxt.config.ts deleted file mode 100644 index f4c5faca38..0000000000 --- a/examples/aws-nuxt/nuxt.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -// https://nuxt.com/docs/api/configuration/nuxt-config -export default defineNuxtConfig({ - compatibilityDate: '2024-04-03', - nitro: { - preset: 'aws-lambda' - }, - devtools: { enabled: true } -}) diff --git a/examples/aws-nuxt/package.json b/examples/aws-nuxt/package.json deleted file mode 100644 index 2001ffcfb3..0000000000 --- a/examples/aws-nuxt/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-nuxt", - "private": true, - "type": "module", - "scripts": { - "build": "nuxt build", - "dev": "nuxt dev", - "generate": "nuxt generate", - "postinstall": "nuxt prepare", - "preview": "nuxt preview" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.651.1", - "@aws-sdk/s3-request-presigner": "^3.651.1", - "nuxt": "^3.13.0", - "sst": "file:../../sdk/js", - "vue": "latest", - "vue-router": "latest" - } -} diff --git a/examples/aws-nuxt/public/favicon.ico b/examples/aws-nuxt/public/favicon.ico deleted file mode 100644 index 18993ad91c..0000000000 Binary files a/examples/aws-nuxt/public/favicon.ico and /dev/null differ diff --git a/examples/aws-nuxt/public/robots.txt b/examples/aws-nuxt/public/robots.txt deleted file mode 100644 index 8b13789179..0000000000 --- a/examples/aws-nuxt/public/robots.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/aws-nuxt/server/api/presigned.ts b/examples/aws-nuxt/server/api/presigned.ts deleted file mode 100644 index b8c29a2e5b..0000000000 --- a/examples/aws-nuxt/server/api/presigned.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -export default defineEventHandler(async () => { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - - return await getSignedUrl(new S3Client({}), command); -}) diff --git a/examples/aws-nuxt/server/tsconfig.json b/examples/aws-nuxt/server/tsconfig.json deleted file mode 100644 index b9ed69c19e..0000000000 --- a/examples/aws-nuxt/server/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../.nuxt/tsconfig.server.json" -} diff --git a/examples/aws-nuxt/sst.config.ts b/examples/aws-nuxt/sst.config.ts deleted file mode 100644 index 462d330512..0000000000 --- a/examples/aws-nuxt/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-nuxt", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - new sst.aws.Nuxt("MyWeb", { - link: [bucket], - }); - }, -}); diff --git a/examples/aws-nuxt/tsconfig.json b/examples/aws-nuxt/tsconfig.json deleted file mode 100644 index a746f2a70c..0000000000 --- a/examples/aws-nuxt/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - // https://nuxt.com/docs/guide/concepts/typescript - "extends": "./.nuxt/tsconfig.json" -} diff --git a/examples/aws-open-search-local/.gitignore b/examples/aws-open-search-local/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-open-search-local/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-open-search-local/index.ts b/examples/aws-open-search-local/index.ts deleted file mode 100644 index a31d07708e..0000000000 --- a/examples/aws-open-search-local/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Resource } from "sst"; -import { Client } from "@opensearch-project/opensearch"; - -const client = new Client({ - node: Resource.MySearch.url, - auth: { - username: Resource.MySearch.username, - password: Resource.MySearch.password, - }, -}); - -export async function handler() { - // Add a document - await client.index({ - index: "my-index", - body: { message: "Hello world!" }, - }); - - // Search for documents - const result = await client.search({ - index: "my-index", - body: { query: { match: { message: "world" } } }, - }); - - return { - statusCode: 200, - body: - `Querying ${Resource.MySearch.url}\n\n` + - JSON.stringify(result.body.hits, null, 2), - }; -} diff --git a/examples/aws-open-search-local/package.json b/examples/aws-open-search-local/package.json deleted file mode 100644 index 599559797b..0000000000 --- a/examples/aws-open-search-local/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-open-search-local", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@opensearch-project/opensearch": "^3.5.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-open-search-local/sst.config.ts b/examples/aws-open-search-local/sst.config.ts deleted file mode 100644 index 19429f8814..0000000000 --- a/examples/aws-open-search-local/sst.config.ts +++ /dev/null @@ -1,79 +0,0 @@ -/// - -/** - * ## AWS OpenSearch local - * - * In this example, we connect to a locally running OpenSearch process for dev. While - * on deploy, we use AWS' OpenSearch Service. - * - * We use the [`docker run`](https://docs.docker.com/reference/cli/docker/container/run/) - * CLI to start a local container with OpenSearch. You don't have to use Docker, you can use - * any other way to run OpenSearch locally. - * - * ```bash - * docker run \ - * --rm \ - * -p 9200:9200 \ - * -v $(pwd)/.sst/storage/opensearch:/usr/share/opensearch/data \ - * -e discovery.type=single-node \ - * -e plugins.security.disabled=true \ - * -e OPENSEARCH_INITIAL_ADMIN_PASSWORD=^Passw0rd^ \ - * opensearchproject/opensearch:2.17.0 - * ``` - * - * The data is saved to the `.sst/storage` directory. So if you restart the dev server, the - * data will still be there. - * - * We then configure the `dev` property of the `OpenSearch` component with the settings for - * the local OpenSearch instance. - * - * ```ts title="sst.config.ts" - * dev: { - * url: "http://localhost:9200", - * username: "admin", - * password: "^Passw0rd^" - * } - * ``` - * - * By providing the `dev` prop for OpenSearch, SST will use the local OpenSearch process and - * not deploy a new OpenSearch domain when running `sst dev`. - * - * It also allows us to access the local process through a Resource `link` without having - * to conditionally check if we are running locally. - * - * ```ts title="index.ts" - * const client = new Client({ - * node: Resource.MySearch.url, - * auth: { - * username: Resource.MySearch.username, - * password: Resource.MySearch.password, - * }, - * }); - * ``` - * - * The above will work in both `sst dev` and `sst deploy`. - */ -export default $config({ - app(input) { - return { - name: "aws-open-search-local", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const search = new sst.aws.OpenSearch("MySearch", { - dev: { - url: "http://localhost:9200", - username: "admin", - password: "^Passw0rd^", - }, - }); - - new sst.aws.Function("MyApp", { - handler: "index.handler", - url: true, - link: [search], - }); - }, -}); diff --git a/examples/aws-open-search-local/tsconfig.json b/examples/aws-open-search-local/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-open-search-local/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-open-search/index.ts b/examples/aws-open-search/index.ts deleted file mode 100644 index a31d07708e..0000000000 --- a/examples/aws-open-search/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Resource } from "sst"; -import { Client } from "@opensearch-project/opensearch"; - -const client = new Client({ - node: Resource.MySearch.url, - auth: { - username: Resource.MySearch.username, - password: Resource.MySearch.password, - }, -}); - -export async function handler() { - // Add a document - await client.index({ - index: "my-index", - body: { message: "Hello world!" }, - }); - - // Search for documents - const result = await client.search({ - index: "my-index", - body: { query: { match: { message: "world" } } }, - }); - - return { - statusCode: 200, - body: - `Querying ${Resource.MySearch.url}\n\n` + - JSON.stringify(result.body.hits, null, 2), - }; -} diff --git a/examples/aws-open-search/package.json b/examples/aws-open-search/package.json deleted file mode 100644 index 8776398850..0000000000 --- a/examples/aws-open-search/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-open-search", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "@opensearch-project/opensearch": "^3.5.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-open-search/sst.config.ts b/examples/aws-open-search/sst.config.ts deleted file mode 100644 index 009e1491fb..0000000000 --- a/examples/aws-open-search/sst.config.ts +++ /dev/null @@ -1,55 +0,0 @@ -/// - -/** - * ## AWS OpenSearch - * - * In this example we create a new OpenSearch domain, link it to a function, and - * then query it. - * - * Start by creating a new OpenSearch domain. - * - * ```ts title="sst.config.ts" - * const search = new sst.aws.OpenSearch("MySearch"); - * ``` - * - * Once linked to a function, we can connect to it. - * - * ```ts title="index.ts" - * import { Resource } from "sst"; - * import { Client } from "@opensearch-project/opensearch"; - * - * const client = new Client({ - * node: Resource.MySearch.url, - * auth: { - * username: Resource.MySearch.username, - * password: Resource.MySearch.password - * } - * }); - * ``` - * - * This is using the [OpenSearch JS SDK](https://docs.opensearch.org/docs/latest/clients/javascript/index) to connect to the OpenSearch domain.. - */ -export default $config({ - app(input) { - return { - name: "aws-open-search", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const search = new sst.aws.OpenSearch("MySearch"); - const app = new sst.aws.Function("MyApp", { - handler: "index.handler", - url: true, - link: [search], - }); - - return { - app: app.url, - url: search.url, - username: search.username, - password: search.password, - }; - }, -}); diff --git a/examples/aws-planetscale-drizzle-mysql/.gitignore b/examples/aws-planetscale-drizzle-mysql/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-planetscale-drizzle-mysql/drizzle.config.ts b/examples/aws-planetscale-drizzle-mysql/drizzle.config.ts deleted file mode 100644 index 1fd6c1a4d3..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/drizzle.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from "drizzle-kit"; -import { Resource } from "sst"; - -export default defineConfig({ - dialect: "mysql", - dbCredentials: { - url: `mysql://${Resource.Database.username}:${Resource.Database.password}@${Resource.Database.host}/${Resource.Database.database}?ssl={"rejectUnauthorized":true}`, - }, - schema: ["./src/schema.ts"], -}); diff --git a/examples/aws-planetscale-drizzle-mysql/package.json b/examples/aws-planetscale-drizzle-mysql/package.json deleted file mode 100644 index 760c01bdce..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-planetscale-drizzle-mysql", - "version": "0.0.0", - "scripts": { - "db": "sst shell drizzle-kit", - "db:push": "sst shell drizzle-kit push", - "db:studio": "sst shell drizzle-kit studio" - }, - "dependencies": { - "@planetscale/database": "^1.19.0", - "drizzle-kit": "^0.31.10", - "drizzle-orm": "^0.45.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-planetscale-drizzle-mysql/src/api.ts b/examples/aws-planetscale-drizzle-mysql/src/api.ts deleted file mode 100644 index 025826383a..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/src/api.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { db } from "./drizzle"; -import { todosTable } from "./schema"; -import { APIGatewayProxyHandlerV2 } from "aws-lambda"; - -export const handler: APIGatewayProxyHandlerV2 = async (evt) => { - if (evt.requestContext.http.method === "GET") { - const result = await db.select().from(todosTable).execute(); - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } - - if (evt.requestContext.http.method === "POST") { - await db.insert(todosTable).values({ title: "new todosTable" }).execute(); - return { - statusCode: 200, - body: "created", - }; - } - - return { - statusCode: 404, - body: "not found", - }; -}; diff --git a/examples/aws-planetscale-drizzle-mysql/src/drizzle.ts b/examples/aws-planetscale-drizzle-mysql/src/drizzle.ts deleted file mode 100644 index bd89904058..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/src/drizzle.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { drizzle } from "drizzle-orm/planetscale-serverless"; -import { Resource } from "sst"; - -export const db = drizzle({ - connection: { - host: Resource.Database.host, - username: Resource.Database.username, - password: Resource.Database.password, - }, -}); diff --git a/examples/aws-planetscale-drizzle-mysql/src/schema.ts b/examples/aws-planetscale-drizzle-mysql/src/schema.ts deleted file mode 100644 index d987a283ee..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/src/schema.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { mysqlTable, int, text, varchar } from "drizzle-orm/mysql-core"; - -export const todosTable = mysqlTable("todo", { - id: int("id").primaryKey().autoincrement(), - title: varchar("title", { length: 255 }).notNull(), - description: text("description"), -}); diff --git a/examples/aws-planetscale-drizzle-mysql/sst.config.ts b/examples/aws-planetscale-drizzle-mysql/sst.config.ts deleted file mode 100644 index 1778249823..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/sst.config.ts +++ /dev/null @@ -1,122 +0,0 @@ -/// - -/** - * ## AWS PlanetScale Drizzle MySQL - * - * In this example, we use PlanetScale with a branch-per-stage pattern. Every stage gets its own - * database branch — so each PR can have an isolated database. - * - * ```ts title="sst.config.ts" - * const db = planetscale.getDatabaseVitessOutput({ - * id: "mydb", - * organization: "myorg", - * }); - * - * const branch = - * $app.stage === "production" - * ? planetscale.getVitessBranchOutput({ - * id: db.defaultBranch, - * organization: db.organization, - * database: db.name, - * }) - * : new planetscale.VitessBranch("DatabaseBranch", { - * database: db.name, - * organization: db.organization, - * name: $app.stage, - * parentBranch: db.defaultBranch, - * }); - * ``` - * - * We then create a password and wrap it in a `Linkable` to link it to a function. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Function("Api", { - * handler: "src/api.handler", - * link: [database], - * url: true, - * }); - * ``` - * - * You can push your Drizzle schema changes to PlanetScale with: - * - * ```bash - * bun run db:push - * ``` - * - * In the function we use [Drizzle ORM](https://orm.drizzle.team) with the - * [`Resource`](/docs/reference/sdk/#resource) helper. - * - * ```ts title="src/drizzle.ts" - * import { drizzle } from "drizzle-orm/planetscale-serverless"; - * import { Resource } from "sst"; - * - * export const db = drizzle({ - * connection: { - * host: Resource.Database.host, - * username: Resource.Database.username, - * password: Resource.Database.password, - * }, - * }); - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-planetscale-drizzle-mysql", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - planetscale: "1.0.0", - }, - }; - }, - async run() { - const db = planetscale.getDatabaseVitessOutput({ - id: "example", - organization: "vimtor", - }); - - const branch = - $app.stage === "production" - ? planetscale.getVitessBranchOutput({ - id: db.defaultBranch, - organization: db.organization, - database: db.name, - }) - : new planetscale.VitessBranch("DatabaseBranch", { - database: db.name, - organization: db.organization, - name: $app.stage, - parentBranch: db.defaultBranch, - }); - - const password = new planetscale.VitessBranchPassword("DatabasePassword", { - database: db.name, - organization: db.organization, - branch: branch.name, - role: "admin", - name: `${$app.name}-${$app.stage}`, - }); - - const database = new sst.Linkable("Database", { - properties: { - host: password.accessHostUrl, - username: password.username, - password: password.plainText, - database: db.name, - port: 3306, - }, - }); - - const api = new sst.aws.Function("Api", { - handler: "src/api.handler", - link: [database], - url: true, - }); - - return { - url: api.url, - }; - }, -}); diff --git a/examples/aws-planetscale-drizzle-mysql/tsconfig.json b/examples/aws-planetscale-drizzle-mysql/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-planetscale-drizzle-mysql/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-planetscale-drizzle-postgres/.gitignore b/examples/aws-planetscale-drizzle-postgres/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-planetscale-drizzle-postgres/drizzle.config.ts b/examples/aws-planetscale-drizzle-postgres/drizzle.config.ts deleted file mode 100644 index 03f4e900e9..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/drizzle.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from "drizzle-kit"; -import { Resource } from "sst"; - -export default defineConfig({ - dialect: "postgresql", - dbCredentials: { - url: `postgresql://${Resource.Database.username}:${Resource.Database.password}@${Resource.Database.host}/${Resource.Database.database}?sslmode=require`, - }, - schema: ["./src/schema.ts"], -}); diff --git a/examples/aws-planetscale-drizzle-postgres/package.json b/examples/aws-planetscale-drizzle-postgres/package.json deleted file mode 100644 index 8c4f0ecd74..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-planetscale-drizzle-postgres", - "version": "0.0.0", - "scripts": { - "db": "sst shell drizzle-kit", - "db:push": "sst shell drizzle-kit push", - "db:studio": "sst shell drizzle-kit studio" - }, - "dependencies": { - "@neondatabase/serverless": "^1.0.2", - "drizzle-kit": "^0.31.10", - "drizzle-orm": "^0.45.1", - "postgres": "^3.4.5", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-planetscale-drizzle-postgres/src/api.ts b/examples/aws-planetscale-drizzle-postgres/src/api.ts deleted file mode 100644 index 025826383a..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/src/api.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { db } from "./drizzle"; -import { todosTable } from "./schema"; -import { APIGatewayProxyHandlerV2 } from "aws-lambda"; - -export const handler: APIGatewayProxyHandlerV2 = async (evt) => { - if (evt.requestContext.http.method === "GET") { - const result = await db.select().from(todosTable).execute(); - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } - - if (evt.requestContext.http.method === "POST") { - await db.insert(todosTable).values({ title: "new todosTable" }).execute(); - return { - statusCode: 200, - body: "created", - }; - } - - return { - statusCode: 404, - body: "not found", - }; -}; diff --git a/examples/aws-planetscale-drizzle-postgres/src/drizzle.ts b/examples/aws-planetscale-drizzle-postgres/src/drizzle.ts deleted file mode 100644 index a521bdc43f..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/src/drizzle.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Resource } from "sst"; -import { neon, neonConfig } from "@neondatabase/serverless"; -import { drizzle } from "drizzle-orm/neon-http"; - -// Required for PlanetScale Postgres connections -neonConfig.fetchEndpoint = (host) => `https://${host}/sql`; -const sql = neon( - `postgresql://${Resource.Database.username}:${Resource.Database.password}@${Resource.Database.host}:${Resource.Database.port}/postgres?sslmode=verify-full`, -); - -export const db = drizzle({ client: sql }); diff --git a/examples/aws-planetscale-drizzle-postgres/src/schema.ts b/examples/aws-planetscale-drizzle-postgres/src/schema.ts deleted file mode 100644 index f75c5cd19e..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/src/schema.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { pgTable, serial, text, varchar } from "drizzle-orm/pg-core"; - -export const todosTable = pgTable("todo", { - id: serial("id").primaryKey(), - title: varchar("title", { length: 255 }).notNull(), - description: text("description"), -}); diff --git a/examples/aws-planetscale-drizzle-postgres/sst.config.ts b/examples/aws-planetscale-drizzle-postgres/sst.config.ts deleted file mode 100644 index 3128227068..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/sst.config.ts +++ /dev/null @@ -1,128 +0,0 @@ -/// - -/** - * ## AWS PlanetScale Drizzle Postgres - * - * In this example, we use PlanetScale Postgres with a branch-per-stage pattern. Every stage - * gets its own database branch — so each PR can have an isolated database. - * - * ```ts title="sst.config.ts" - * const db = planetscale.getDatabasePostgresOutput({ - * id: "mydb", - * organization: "myorg", - * }); - * - * const branch = - * $app.stage === "production" - * ? planetscale.getPostgresBranchOutput({ - * id: db.defaultBranch, - * organization: db.organization, - * database: db.name, - * }) - * : new planetscale.PostgresBranch("DatabaseBranch", { - * database: db.name, - * organization: db.organization, - * name: $app.stage, - * parentBranch: db.defaultBranch, - * }); - * ``` - * - * We then create a role and wrap it in a `Linkable` to link it to a function. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Function("Api", { - * handler: "src/api.handler", - * link: [database], - * url: true, - * }); - * ``` - * - * You can push your Drizzle schema changes to PlanetScale with: - * - * ```bash - * bun run db:push - * ``` - * - * In the function we use [Drizzle ORM](https://orm.drizzle.team) with the - * [`Resource`](/docs/reference/sdk/#resource) helper. - * - * ```ts title="src/drizzle.ts" - * import { drizzle } from "drizzle-orm/postgres-js"; - * import { Resource } from "sst"; - * import postgres from "postgres"; - * - * const client = postgres({ - * host: Resource.Database.host, - * username: Resource.Database.username, - * password: Resource.Database.password, - * database: Resource.Database.database, - * }); - * - * export const db = drizzle(client); - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-planetscale-drizzle-postgres", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - planetscale: "1.0.0", - }, - }; - }, - async run() { - const db = planetscale.getDatabasePostgresOutput({ - id: "mydb", - organization: "myorg", - }); - - const branch = - $app.stage === "production" - ? planetscale.getPostgresBranchOutput({ - id: db.defaultBranch, - organization: db.organization, - database: db.name, - }) - : new planetscale.PostgresBranch("DatabaseBranch", { - database: db.name, - organization: db.organization, - name: $app.stage, - parentBranch: db.defaultBranch, - }); - - const role = new planetscale.PostgresBranchRole("DatabaseRole", { - database: db.name, - organization: db.organization, - branch: branch.name, - name: `${$app.name}-${$app.stage}`, - inheritedRoles: [ - "pg_read_all_data", - "pg_write_all_data", - "postgres", // Only needed for pushing schema changes - ], - }); - - const database = new sst.Linkable("Database", { - properties: { - host: role.accessHostUrl, - username: role.username, - password: role.password, - database: role.databaseName, - port: 6432, // Use 5432 for direct connection instead of PgBouncer - }, - }); - - const api = new sst.aws.Function("Api", { - handler: "src/api.handler", - link: [database], - url: true, - }); - - return { - url: api.url, - }; - }, -}); diff --git a/examples/aws-planetscale-drizzle-postgres/tsconfig.json b/examples/aws-planetscale-drizzle-postgres/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-planetscale-drizzle-postgres/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-policy-pack/package.json b/examples/aws-policy-pack/package.json deleted file mode 100644 index b984f65082..0000000000 --- a/examples/aws-policy-pack/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-policy-pack", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-policy-pack/policy-pack/.gitignore b/examples/aws-policy-pack/policy-pack/.gitignore deleted file mode 100644 index 6ba7daaf94..0000000000 --- a/examples/aws-policy-pack/policy-pack/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/bin/ -/node_modules/ -bun.lock diff --git a/examples/aws-policy-pack/policy-pack/PulumiPolicy.yaml b/examples/aws-policy-pack/policy-pack/PulumiPolicy.yaml deleted file mode 100644 index c6c1e5b116..0000000000 --- a/examples/aws-policy-pack/policy-pack/PulumiPolicy.yaml +++ /dev/null @@ -1,3 +0,0 @@ -description: A minimal Policy Pack for AWS using TypeScript. -runtime: nodejs -main: dist/index.js diff --git a/examples/aws-policy-pack/policy-pack/index.ts b/examples/aws-policy-pack/policy-pack/index.ts deleted file mode 100644 index a684f3ff21..0000000000 --- a/examples/aws-policy-pack/policy-pack/index.ts +++ /dev/null @@ -1,50 +0,0 @@ -import * as aws from "@pulumi/aws"; -import { PolicyPack, validateResourceOfType } from "@pulumi/policy"; - -new PolicyPack("iam-roles-policies", { - policies: [ - { - name: "iam-role-requires-permission-boundary", - description: "IAM roles must have a permission boundary.", - enforcementLevel: "mandatory", - validateResource: validateResourceOfType( - aws.iam.Role, - (role, _args, reportViolation) => { - if (!role.permissionsBoundary) { - reportViolation( - "Permission boundaries are important for limiting the maximum permissions that can be granted to an IAM role." - ); - } - }, - ), - }, - { - name: "iam-role-policy-no-wildcard-resources", - description: - "IAM role policies should avoid wildcard resources for better security.", - enforcementLevel: "advisory", - validateResource: validateResourceOfType( - aws.iam.RolePolicy, - (policy, _args, reportViolation) => { - if (policy.policy && typeof policy.policy === "string") { - try { - const policyDoc = JSON.parse(policy.policy); - const statements = policyDoc.Statement || []; - for (const statement of statements) { - const resources = Array.isArray(statement.Resource) - ? statement.Resource - : [statement.Resource]; - if (resources.includes("*")) { - reportViolation( - "IAM role policies should not use wildcard (*) for resources. Specify explicit resource ARNs to follow the principle of least privilege." - ); - break; - } - } - } catch (e) {} - } - }, - ), - }, - ], -}); diff --git a/examples/aws-policy-pack/policy-pack/package.json b/examples/aws-policy-pack/policy-pack/package.json deleted file mode 100644 index 2210bd57a9..0000000000 --- a/examples/aws-policy-pack/policy-pack/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "policy-pack", - "version": "0.0.1", - "dependencies": { - "@pulumi/aws": "^6.0.0", - "@pulumi/policy": "^1.20.0" - }, - "devDependencies": { - "@types/node": "^10.0.0" - } -} diff --git a/examples/aws-policy-pack/policy-pack/tsconfig.json b/examples/aws-policy-pack/policy-pack/tsconfig.json deleted file mode 100644 index ecb951b692..0000000000 --- a/examples/aws-policy-pack/policy-pack/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2018", - "module": "CommonJS", - "moduleResolution": "node", - "declaration": true, - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "dist" - }, - "include": ["index.ts"] -} diff --git a/examples/aws-policy-pack/sst.config.ts b/examples/aws-policy-pack/sst.config.ts deleted file mode 100644 index 7430ea092a..0000000000 --- a/examples/aws-policy-pack/sst.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// - -/** - * ## Policy Pack Validation - * - * You can use Pulumi Policy Packs to enforce compliance and security policies on your - * infrastructure before deployment. Created policies with and enforcement level of "mandatory" will block the deployment. - * - * This example shows how to use the `--policy` flag with `sst diff` and `sst deploy` to - * validate your infrastructure against a policy pack. - * - * Run the diff command with a policy pack to preview changes and check for violations: - * - * ```bash - * sst diff --policy ./policy-pack --stage prod - * ``` - * - * Deploy with policy validation: - * - * ```bash - * sst deploy --policy ./policy-pack --stage prod - * ``` - * - * To get started you can create a new policy pack for AWS using: - * - * ```bash - * mkdir policy-pack - * cd policy-pack - * pulumi policy new aws-typescript - * ``` - * - * The example policy pack (check the full example) enforces that all IAM roles must have a permission boundary, blocking the deployment in this sst example. - */ -export default $config({ - app(input) { - return { - name: "aws-policy-pack", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const role = new aws.iam.Role("ExampleRoleWithBoundary", { - assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({ - Service: "lambda.amazonaws.com", - }), - // To make this compliant with the policy example, uncomment the following line: - // permissionsBoundary: "arn:aws:iam::aws:policy/PowerUserAccess", - }); - - new aws.iam.RolePolicy("S3GetItemPolicy", { - role: role.id, - policy: aws.iam.getPolicyDocumentOutput({ - statements: [ - { - actions: ["s3:GetObject"], - resources: ["*"], - }, - ], - }).json, - }); - }, -}); diff --git a/examples/aws-policy-pack/tsconfig.json b/examples/aws-policy-pack/tsconfig.json deleted file mode 100644 index 7811c6e56f..0000000000 --- a/examples/aws-policy-pack/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "node", - "esModuleInterop": true, - "strict": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": ".build" - }, - "include": ["**/*.ts"] -} diff --git a/examples/aws-postgres-local/.gitignore b/examples/aws-postgres-local/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-postgres-local/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-postgres-local/index.ts b/examples/aws-postgres-local/index.ts deleted file mode 100644 index 318f08fefa..0000000000 --- a/examples/aws-postgres-local/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Pool } from "pg"; -import { Resource } from "sst"; - -const pool = new Pool({ - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, -}); - -export async function handler() { - const client = await pool.connect(); - const result = await client.query('SELECT NOW()'); - client.release(); - - return { - statusCode: 200, - body: `Querying ${Resource.MyPostgres.host}\n\n` - + result.rows[0].now, - }; -} diff --git a/examples/aws-postgres-local/package.json b/examples/aws-postgres-local/package.json deleted file mode 100644 index b5d4a4644c..0000000000 --- a/examples/aws-postgres-local/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-postgres-local", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "pg": "^8.13.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "@types/pg": "^8.11.10" - } -} diff --git a/examples/aws-postgres-local/sst.config.ts b/examples/aws-postgres-local/sst.config.ts deleted file mode 100644 index a88ea4a37b..0000000000 --- a/examples/aws-postgres-local/sst.config.ts +++ /dev/null @@ -1,86 +0,0 @@ -/// - -/** - * ## AWS Postgres local - * - * In this example, we connect to a locally running Postgres instance for dev. While - * on deploy, we use RDS. - * - * We use the [`docker run`](https://docs.docker.com/reference/cli/docker/container/run/) CLI - * to start a local container with Postgres. You don't have to use Docker, you can use - * Postgres.app or any other way to run Postgres locally. - * - * ```bash - * docker run \ - * --rm \ - * -p 5432:5432 \ - * -v $(pwd)/.sst/storage/postgres:/var/lib/postgresql/data \ - * -e POSTGRES_USER=postgres \ - * -e POSTGRES_PASSWORD=password \ - * -e POSTGRES_DB=local \ - * postgres:16.4 - * ``` - * - * The data is saved to the `.sst/storage` directory. So if you restart the dev server, the - * data will still be there. - * - * We then configure the `dev` property of the `Postgres` component with the settings for the - * local Postgres instance. - * - * ```ts title="sst.config.ts" - * dev: { - * username: "postgres", - * password: "password", - * database: "local", - * port: 5432, - * } - * ``` - * - * By providing the `dev` prop for Postgres, SST will use the local Postgres instance and - * not deploy a new RDS database when running `sst dev`. - * - * It also allows us to access the database through a Resource `link` without having to - * conditionally check if we are running locally. - * - * ```ts title="index.ts" - * const pool = new Pool({ - * host: Resource.MyPostgres.host, - * port: Resource.MyPostgres.port, - * user: Resource.MyPostgres.username, - * password: Resource.MyPostgres.password, - * database: Resource.MyPostgres.database, - * }); - * ``` - * - * The above will work in both `sst dev` and `sst deploy`. - */ -export default $config({ - app(input) { - return { - name: "aws-postgres-local", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "ec2" }); - - const rds = new sst.aws.Postgres("MyPostgres", { - dev: { - username: "postgres", - password: "password", - database: "local", - host: "localhost", - port: 5432, - }, - vpc, - }); - - new sst.aws.Function("MyFunction", { - vpc, - url: true, - link: [rds], - handler: "index.handler", - }); - }, -}); diff --git a/examples/aws-postgres-local/tsconfig.json b/examples/aws-postgres-local/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-postgres-local/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-postgres-shared-parameter-group/sst.config.ts b/examples/aws-postgres-shared-parameter-group/sst.config.ts deleted file mode 100644 index ab0e7dc8e6..0000000000 --- a/examples/aws-postgres-shared-parameter-group/sst.config.ts +++ /dev/null @@ -1,72 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-postgres-shared-pg", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - - // Alternative: create a standalone parameter group and reference it - // - // const sharedParameterGroup = new aws.rds.ParameterGroup( - // "SharedParameterGroup", - // { - // name: "shared-parameter-group", - // family: "postgres17", - // parameters: [ - // { name: "rds.force_ssl", value: "0" }, - // { name: "log_min_duration_statement", value: "1000" }, - // ], - // }, - // ); - // - // Then use in each Postgres: - // transform: { - // instance: { parameterGroupName: sharedParameterGroup.name }, - // } - - // First database with custom parameters - const db1 = new sst.aws.Postgres("Database1", { - vpc, - transform: { - parameterGroup: { - parameters: [ - { - name: "rds.force_ssl", - value: "0", - }, - { - name: "rds.logical_replication", - value: "1", - applyMethod: "pending-reboot", - }, - { - name: "log_min_duration_statement", - value: "1000", - }, - ], - }, - }, - }); - - // Second database reuses db1's parameter group - const db2 = new sst.aws.Postgres("Database2", { - vpc, - transform: { - instance: { - parameterGroupName: db1.nodes.instance.parameterGroupName, - }, - }, - }); - - return { - db1Host: db1.host, - db2Host: db2.host, - }; - }, -}); diff --git a/examples/aws-postgres/index.ts b/examples/aws-postgres/index.ts deleted file mode 100644 index 1c6dfd2185..0000000000 --- a/examples/aws-postgres/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import pg from "pg"; -import { Resource } from "sst"; -const { Client } = pg; -const client = new Client({ - user: Resource.MyDatabase.username, - password: Resource.MyDatabase.password, - database: Resource.MyDatabase.database, - host: Resource.MyDatabase.host, - port: Resource.MyDatabase.port, -}); -await client.connect(); - -export async function handler() { - const res = await client.query("SELECT $1::text as message", [ - "Hello world!", - ]); - return { - statusCode: 200, - body: res.rows[0].message, - }; -} diff --git a/examples/aws-postgres/package.json b/examples/aws-postgres/package.json deleted file mode 100644 index b90c7345e2..0000000000 --- a/examples/aws-postgres/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-postgres", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "pg": "^8.13.0", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-postgres/sst.config.ts b/examples/aws-postgres/sst.config.ts deleted file mode 100644 index 8a82eda60b..0000000000 --- a/examples/aws-postgres/sst.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-postgres", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // NAT Gateways are required for Lambda functions - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const postgres = new sst.aws.Postgres("MyDatabase", { - vpc, - }); - const app = new sst.aws.Function("MyApp", { - handler: "index.handler", - url: true, - link: [postgres], - nodejs: { - esbuild: { - external: ["pg"], - }, - }, - }); - - return { - app: app.url, - host: postgres.host, - port: postgres.port, - username: postgres.username, - password: postgres.password, - database: postgres.database, - }; - }, -}); diff --git a/examples/aws-pothos-graphql/.gitignore b/examples/aws-pothos-graphql/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-pothos-graphql/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-pothos-graphql/client.ts b/examples/aws-pothos-graphql/client.ts deleted file mode 100644 index 4216224d56..0000000000 --- a/examples/aws-pothos-graphql/client.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Resource } from "sst"; -import { createClient } from "./graphql/genql"; - -const client = createClient({ - url: `${Resource.Api.url}/graphql`, -}); - -export async function handler() { - const createGiraffe = await client.mutation({ - createGiraffe: { - __args: { - name: "Jonny", - }, - name: true, - }, - }); - - return { - statusCode: 200, - body: createGiraffe, - }; -} diff --git a/examples/aws-pothos-graphql/graphql/genql/index.ts b/examples/aws-pothos-graphql/graphql/genql/index.ts deleted file mode 100644 index d6b343103f..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/index.ts +++ /dev/null @@ -1,65 +0,0 @@ -// @ts-nocheck -import type { - QueryGenqlSelection, - Query, - MutationGenqlSelection, - Mutation, -} from './schema' -import { - linkTypeMap, - createClient as createClientOriginal, - generateGraphqlOperation, - type FieldsSelection, - type GraphqlOperation, - type ClientOptions, - GenqlError, -} from './runtime' -export type { FieldsSelection } from './runtime' -export { GenqlError } - -import types from './types' -export * from './schema' -const typeMap = linkTypeMap(types as any) - -export interface Client { - query( - request: R & { __name?: string }, - ): Promise> - - mutation( - request: R & { __name?: string }, - ): Promise> -} - -export const createClient = function (options?: ClientOptions): Client { - return createClientOriginal({ - url: undefined, - - ...options, - queryRoot: typeMap.Query!, - mutationRoot: typeMap.Mutation!, - subscriptionRoot: typeMap.Subscription!, - }) as any -} - -export const everything = { - __scalar: true, -} - -export type QueryResult = FieldsSelection< - Query, - fields -> -export const generateQueryOp: ( - fields: QueryGenqlSelection & { __name?: string }, -) => GraphqlOperation = function (fields) { - return generateGraphqlOperation('query', typeMap.Query!, fields as any) -} - -export type MutationResult = - FieldsSelection -export const generateMutationOp: ( - fields: MutationGenqlSelection & { __name?: string }, -) => GraphqlOperation = function (fields) { - return generateGraphqlOperation('mutation', typeMap.Mutation!, fields as any) -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/batcher.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/batcher.ts deleted file mode 100644 index c092551010..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/batcher.ts +++ /dev/null @@ -1,275 +0,0 @@ -// @ts-nocheck -import type { GraphqlOperation } from './generateGraphqlOperation' -import { GenqlError } from './error' - -type Variables = Record - -type QueryError = Error & { - message: string - - locations?: Array<{ - line: number - column: number - }> - path?: any - rid: string - details?: Record -} -type Result = { - data: Record - errors: Array -} -type Fetcher = ( - batchedQuery: GraphqlOperation | Array, -) => Promise> -type Options = { - batchInterval?: number - shouldBatch?: boolean - maxBatchSize?: number -} -type Queue = Array<{ - request: GraphqlOperation - resolve: (...args: Array) => any - reject: (...args: Array) => any -}> - -/** - * takes a list of requests (queue) and batches them into a single server request. - * It will then resolve each individual requests promise with the appropriate data. - * @private - * @param {QueryBatcher} client - the client to use - * @param {Queue} queue - the list of requests to batch - */ -function dispatchQueueBatch(client: QueryBatcher, queue: Queue): void { - let batchedQuery: any = queue.map((item) => item.request) - - if (batchedQuery.length === 1) { - batchedQuery = batchedQuery[0] - } - (() => { - try { - return client.fetcher(batchedQuery); - } catch(e) { - return Promise.reject(e); - } - })().then((responses: any) => { - if (queue.length === 1 && !Array.isArray(responses)) { - if (responses.errors && responses.errors.length) { - queue[0].reject( - new GenqlError(responses.errors, responses.data), - ) - return - } - - queue[0].resolve(responses) - return - } else if (responses.length !== queue.length) { - throw new Error('response length did not match query length') - } - - for (let i = 0; i < queue.length; i++) { - if (responses[i].errors && responses[i].errors.length) { - queue[i].reject( - new GenqlError(responses[i].errors, responses[i].data), - ) - } else { - queue[i].resolve(responses[i]) - } - } - }) - .catch((e) => { - for (let i = 0; i < queue.length; i++) { - queue[i].reject(e) - } - }); -} - -/** - * creates a list of requests to batch according to max batch size. - * @private - * @param {QueryBatcher} client - the client to create list of requests from from - * @param {Options} options - the options for the batch - */ -function dispatchQueue(client: QueryBatcher, options: Options): void { - const queue = client._queue - const maxBatchSize = options.maxBatchSize || 0 - client._queue = [] - - if (maxBatchSize > 0 && maxBatchSize < queue.length) { - for (let i = 0; i < queue.length / maxBatchSize; i++) { - dispatchQueueBatch( - client, - queue.slice(i * maxBatchSize, (i + 1) * maxBatchSize), - ) - } - } else { - dispatchQueueBatch(client, queue) - } -} -/** - * Create a batcher client. - * @param {Fetcher} fetcher - A function that can handle the network requests to graphql endpoint - * @param {Options} options - the options to be used by client - * @param {boolean} options.shouldBatch - should the client batch requests. (default true) - * @param {integer} options.batchInterval - duration (in MS) of each batch window. (default 6) - * @param {integer} options.maxBatchSize - max number of requests in a batch. (default 0) - * @param {boolean} options.defaultHeaders - default headers to include with every request - * - * @example - * const fetcher = batchedQuery => fetch('path/to/graphql', { - * method: 'post', - * headers: { - * Accept: 'application/json', - * 'Content-Type': 'application/json', - * }, - * body: JSON.stringify(batchedQuery), - * credentials: 'include', - * }) - * .then(response => response.json()) - * - * const client = new QueryBatcher(fetcher, { maxBatchSize: 10 }) - */ - -export class QueryBatcher { - fetcher: Fetcher - _options: Options - _queue: Queue - - constructor( - fetcher: Fetcher, - { - batchInterval = 6, - shouldBatch = true, - maxBatchSize = 0, - }: Options = {}, - ) { - this.fetcher = fetcher - this._options = { - batchInterval, - shouldBatch, - maxBatchSize, - } - this._queue = [] - } - - /** - * Fetch will send a graphql request and return the parsed json. - * @param {string} query - the graphql query. - * @param {Variables} variables - any variables you wish to inject as key/value pairs. - * @param {[string]} operationName - the graphql operationName. - * @param {Options} overrides - the client options overrides. - * - * @return {promise} resolves to parsed json of server response - * - * @example - * client.fetch(` - * query getHuman($id: ID!) { - * human(id: $id) { - * name - * height - * } - * } - * `, { id: "1001" }, 'getHuman') - * .then(human => { - * // do something with human - * console.log(human); - * }); - */ - fetch( - query: string, - variables?: Variables, - operationName?: string, - overrides: Options = {}, - ): Promise { - const request: GraphqlOperation = { - query, - } - const options = Object.assign({}, this._options, overrides) - - if (variables) { - request.variables = variables - } - - if (operationName) { - request.operationName = operationName - } - - const promise = new Promise((resolve, reject) => { - this._queue.push({ - request, - resolve, - reject, - }) - - if (this._queue.length === 1) { - if (options.shouldBatch) { - setTimeout( - () => dispatchQueue(this, options), - options.batchInterval, - ) - } else { - dispatchQueue(this, options) - } - } - }) - return promise - } - - /** - * Fetch will send a graphql request and return the parsed json. - * @param {string} query - the graphql query. - * @param {Variables} variables - any variables you wish to inject as key/value pairs. - * @param {[string]} operationName - the graphql operationName. - * @param {Options} overrides - the client options overrides. - * - * @return {Promise>} resolves to parsed json of server response - * - * @example - * client.forceFetch(` - * query getHuman($id: ID!) { - * human(id: $id) { - * name - * height - * } - * } - * `, { id: "1001" }, 'getHuman') - * .then(human => { - * // do something with human - * console.log(human); - * }); - */ - forceFetch( - query: string, - variables?: Variables, - operationName?: string, - overrides: Options = {}, - ): Promise { - const request: GraphqlOperation = { - query, - } - const options = Object.assign({}, this._options, overrides, { - shouldBatch: false, - }) - - if (variables) { - request.variables = variables - } - - if (operationName) { - request.operationName = operationName - } - - const promise = new Promise((resolve, reject) => { - const client = new QueryBatcher(this.fetcher, this._options) - client._queue = [ - { - request, - resolve, - reject, - }, - ] - dispatchQueue(client, options) - }) - return promise - } -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/createClient.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/createClient.ts deleted file mode 100644 index 755617ed7a..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/createClient.ts +++ /dev/null @@ -1,68 +0,0 @@ -// @ts-nocheck - -import { type BatchOptions, createFetcher } from './fetcher' -import type { ExecutionResult, LinkedType } from './types' -import { - generateGraphqlOperation, - type GraphqlOperation, -} from './generateGraphqlOperation' - -export type Headers = - | HeadersInit - | (() => HeadersInit) - | (() => Promise) - -export type BaseFetcher = ( - operation: GraphqlOperation | GraphqlOperation[], -) => Promise - -export type ClientOptions = Omit & { - url?: string - batch?: BatchOptions | boolean - fetcher?: BaseFetcher - fetch?: Function - headers?: Headers -} - -export const createClient = ({ - queryRoot, - mutationRoot, - subscriptionRoot, - ...options -}: ClientOptions & { - queryRoot?: LinkedType - mutationRoot?: LinkedType - subscriptionRoot?: LinkedType -}) => { - const fetcher = createFetcher(options) - const client: { - query?: Function - mutation?: Function - } = {} - - if (queryRoot) { - client.query = (request: any) => { - if (!queryRoot) throw new Error('queryRoot argument is missing') - - const resultPromise = fetcher( - generateGraphqlOperation('query', queryRoot, request), - ) - - return resultPromise - } - } - if (mutationRoot) { - client.mutation = (request: any) => { - if (!mutationRoot) - throw new Error('mutationRoot argument is missing') - - const resultPromise = fetcher( - generateGraphqlOperation('mutation', mutationRoot, request), - ) - - return resultPromise - } - } - - return client as any -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/error.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/error.ts deleted file mode 100644 index d9039ebe0c..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/error.ts +++ /dev/null @@ -1,29 +0,0 @@ -// @ts-nocheck -export class GenqlError extends Error { - errors: Array = [] - /** - * Partial data returned by the server - */ - data?: any - constructor(errors: any[], data: any) { - let message = Array.isArray(errors) - ? errors.map((x) => x?.message || '').join('\n') - : '' - if (!message) { - message = 'GraphQL error' - } - super(message) - this.errors = errors - this.data = data - } -} - -interface GraphqlError { - message: string - locations?: Array<{ - line: number - column: number - }> - path?: string[] - extensions?: Record -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/fetcher.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/fetcher.ts deleted file mode 100644 index 74e6d4ce9a..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/fetcher.ts +++ /dev/null @@ -1,97 +0,0 @@ -// @ts-nocheck -import { QueryBatcher } from './batcher' - -import type { ClientOptions } from './createClient' -import type { GraphqlOperation } from './generateGraphqlOperation' -import { GenqlError } from './error' - -export interface Fetcher { - (gql: GraphqlOperation): Promise -} - -export type BatchOptions = { - batchInterval?: number // ms - maxBatchSize?: number -} - -const DEFAULT_BATCH_OPTIONS = { - maxBatchSize: 10, - batchInterval: 40, -} - -export const createFetcher = ({ - url, - headers = {}, - fetcher, - fetch: _fetch, - batch = false, - ...rest -}: ClientOptions): Fetcher => { - if (!url && !fetcher) { - throw new Error('url or fetcher is required') - } - - fetcher = fetcher || (async (body) => { - let headersObject = - typeof headers == 'function' ? await headers() : headers - headersObject = headersObject || {} - if (typeof fetch === 'undefined' && !_fetch) { - throw new Error( - 'Global `fetch` function is not available, pass a fetch polyfill to Genql `createClient`', - ) - } - let fetchImpl = _fetch || fetch - const res = await fetchImpl(url!, { - headers: { - 'Content-Type': 'application/json', - ...headersObject, - }, - method: 'POST', - body: JSON.stringify(body), - ...rest, - }) - if (!res.ok) { - throw new Error(`${res.statusText}: ${await res.text()}`) - } - const json = await res.json() - return json - }) - - if (!batch) { - return async (body) => { - const json = await fetcher!(body) - if (Array.isArray(json)) { - return json.map((json) => { - if (json?.errors?.length) { - throw new GenqlError(json.errors || [], json.data) - } - return json.data - }) - } else { - if (json?.errors?.length) { - throw new GenqlError(json.errors || [], json.data) - } - return json.data - } - } - } - - const batcher = new QueryBatcher( - async (batchedQuery) => { - // console.log(batchedQuery) // [{ query: 'query{user{age}}', variables: {} }, ...] - const json = await fetcher!(batchedQuery) - return json as any - }, - batch === true ? DEFAULT_BATCH_OPTIONS : batch, - ) - - return async ({ query, variables }) => { - const json = await batcher.fetch(query, variables) - if (json?.data) { - return json.data - } - throw new Error( - 'Genql batch fetcher returned unexpected result ' + JSON.stringify(json), - ) - } -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/generateGraphqlOperation.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/generateGraphqlOperation.ts deleted file mode 100644 index c618019ec8..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/generateGraphqlOperation.ts +++ /dev/null @@ -1,225 +0,0 @@ -// @ts-nocheck -import type { LinkedField, LinkedType } from './types' - -export interface Args { - [arg: string]: any | undefined -} - -export interface Fields { - [field: string]: Request -} - -export type Request = boolean | number | Fields - -export interface Variables { - [name: string]: { - value: any - typing: [LinkedType, string] - } -} - -export interface Context { - root: LinkedType - varCounter: number - variables: Variables - fragmentCounter: number - fragments: string[] -} - -export interface GraphqlOperation { - query: string - variables?: { [name: string]: any } - operationName?: string -} - -const parseRequest = ( - request: Request | undefined, - ctx: Context, - path: string[], -): string => { - if (typeof request === 'object' && '__args' in request) { - const args: any = request.__args - let fields: Request | undefined = { ...request } - delete fields.__args - const argNames = Object.keys(args) - - if (argNames.length === 0) { - return parseRequest(fields, ctx, path) - } - - const field = getFieldFromPath(ctx.root, path) - - const argStrings = argNames.map((argName) => { - ctx.varCounter++ - const varName = `v${ctx.varCounter}` - - const typing = field.args && field.args[argName] // typeMap used here, .args - - if (!typing) { - throw new Error( - `no typing defined for argument \`${argName}\` in path \`${path.join( - '.', - )}\``, - ) - } - - ctx.variables[varName] = { - value: args[argName], - typing, - } - - return `${argName}:$${varName}` - }) - return `(${argStrings})${parseRequest(fields, ctx, path)}` - } else if (typeof request === 'object' && Object.keys(request).length > 0) { - const fields = request - const fieldNames = Object.keys(fields).filter((k) => Boolean(fields[k])) - - if (fieldNames.length === 0) { - throw new Error( - `field selection should not be empty: ${path.join('.')}`, - ) - } - - const type = - path.length > 0 ? getFieldFromPath(ctx.root, path).type : ctx.root - const scalarFields = type.scalar - - let scalarFieldsFragment: string | undefined - - if (fieldNames.includes('__scalar')) { - const falsyFieldNames = new Set( - Object.keys(fields).filter((k) => !Boolean(fields[k])), - ) - if (scalarFields?.length) { - ctx.fragmentCounter++ - scalarFieldsFragment = `f${ctx.fragmentCounter}` - - ctx.fragments.push( - `fragment ${scalarFieldsFragment} on ${ - type.name - }{${scalarFields - .filter((f) => !falsyFieldNames.has(f)) - .join(',')}}`, - ) - } - } - - const fieldsSelection = fieldNames - .filter((f) => !['__scalar', '__name'].includes(f)) - .map((f) => { - const parsed = parseRequest(fields[f], ctx, [...path, f]) - - if (f.startsWith('on_')) { - ctx.fragmentCounter++ - const implementationFragment = `f${ctx.fragmentCounter}` - - const typeMatch = f.match(/^on_(.+)/) - - if (!typeMatch || !typeMatch[1]) - throw new Error('match failed') - - ctx.fragments.push( - `fragment ${implementationFragment} on ${typeMatch[1]}${parsed}`, - ) - - return `...${implementationFragment}` - } else { - return `${f}${parsed}` - } - }) - .concat(scalarFieldsFragment ? [`...${scalarFieldsFragment}`] : []) - .join(',') - - return `{${fieldsSelection}}` - } else { - return '' - } -} - -export const generateGraphqlOperation = ( - operation: 'query' | 'mutation' | 'subscription', - root: LinkedType, - fields?: Fields, -): GraphqlOperation => { - const ctx: Context = { - root: root, - varCounter: 0, - variables: {}, - fragmentCounter: 0, - fragments: [], - } - const result = parseRequest(fields, ctx, []) - - const varNames = Object.keys(ctx.variables) - - const varsString = - varNames.length > 0 - ? `(${varNames.map((v) => { - const variableType = ctx.variables[v].typing[1] - return `$${v}:${variableType}` - })})` - : '' - - const operationName = fields?.__name || '' - - return { - query: [ - `${operation} ${operationName}${varsString}${result}`, - ...ctx.fragments, - ].join(','), - variables: Object.keys(ctx.variables).reduce<{ [name: string]: any }>( - (r, v) => { - r[v] = ctx.variables[v].value - return r - }, - {}, - ), - ...(operationName ? { operationName: operationName.toString() } : {}), - } -} - -export const getFieldFromPath = ( - root: LinkedType | undefined, - path: string[], -) => { - let current: LinkedField | undefined - - if (!root) throw new Error('root type is not provided') - - if (path.length === 0) throw new Error(`path is empty`) - - path.forEach((f) => { - const type = current ? current.type : root - - if (!type.fields) - throw new Error(`type \`${type.name}\` does not have fields`) - - const possibleTypes = Object.keys(type.fields) - .filter((i) => i.startsWith('on_')) - .reduce( - (types, fieldName) => { - const field = type.fields && type.fields[fieldName] - if (field) types.push(field.type) - return types - }, - [type], - ) - - let field: LinkedField | null = null - - possibleTypes.forEach((type) => { - const found = type.fields && type.fields[f] - if (found) field = found - }) - - if (!field) - throw new Error( - `type \`${type.name}\` does not have a field \`${f}\``, - ) - - current = field - }) - - return current as LinkedField -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/index.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/index.ts deleted file mode 100644 index 130ed4bf79..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -// @ts-nocheck -export { createClient } from './createClient' -export type { ClientOptions } from './createClient' -export type { FieldsSelection } from './typeSelection' -export { generateGraphqlOperation } from './generateGraphqlOperation' -export type { GraphqlOperation } from './generateGraphqlOperation' -export { linkTypeMap } from './linkTypeMap' -// export { Observable } from 'zen-observable-ts' -export { createFetcher } from './fetcher' -export { GenqlError } from './error' -export const everything = { - __scalar: true, -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/linkTypeMap.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/linkTypeMap.ts deleted file mode 100644 index 3e12c54598..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/linkTypeMap.ts +++ /dev/null @@ -1,156 +0,0 @@ -// @ts-nocheck -import type { - CompressedType, - CompressedTypeMap, - LinkedArgMap, - LinkedField, - LinkedType, - LinkedTypeMap, -} from './types' - -export interface PartialLinkedFieldMap { - [field: string]: { - type: string - args?: LinkedArgMap - } -} - -export const linkTypeMap = ( - typeMap: CompressedTypeMap, -): LinkedTypeMap => { - const indexToName: Record = Object.assign( - {}, - ...Object.keys(typeMap.types).map((k, i) => ({ [i]: k })), - ) - - let intermediaryTypeMap = Object.assign( - {}, - ...Object.keys(typeMap.types || {}).map( - (k): Record => { - const type: CompressedType = typeMap.types[k]! - const fields = type || {} - return { - [k]: { - name: k, - // type scalar properties - scalar: Object.keys(fields).filter((f) => { - const [type] = fields[f] || [] - - const isScalar = - type && typeMap.scalars.includes(type) - if (!isScalar) { - return false - } - const args = fields[f]?.[1] - const argTypes = Object.values(args || {}) - .map((x) => x?.[1]) - .filter(Boolean) - - const hasRequiredArgs = argTypes.some( - (str) => str && str.endsWith('!'), - ) - if (hasRequiredArgs) { - return false - } - return true - }), - // fields with corresponding `type` and `args` - fields: Object.assign( - {}, - ...Object.keys(fields).map( - (f): PartialLinkedFieldMap => { - const [typeIndex, args] = fields[f] || [] - if (typeIndex == null) { - return {} - } - return { - [f]: { - // replace index with type name - type: indexToName[typeIndex], - args: Object.assign( - {}, - ...Object.keys(args || {}).map( - (k) => { - // if argTypeString == argTypeName, argTypeString is missing, need to readd it - if (!args || !args[k]) { - return - } - const [ - argTypeName, - argTypeString, - ] = args[k] as any - return { - [k]: [ - indexToName[ - argTypeName - ], - argTypeString || - indexToName[ - argTypeName - ], - ], - } - }, - ), - ), - }, - } - }, - ), - ), - }, - } - }, - ), - ) - const res = resolveConcreteTypes(intermediaryTypeMap) - return res -} - -// replace typename with concrete type -export const resolveConcreteTypes = (linkedTypeMap: LinkedTypeMap) => { - Object.keys(linkedTypeMap).forEach((typeNameFromKey) => { - const type: LinkedType = linkedTypeMap[typeNameFromKey]! - // type.name = typeNameFromKey - if (!type.fields) { - return - } - - const fields = type.fields - - Object.keys(fields).forEach((f) => { - const field: LinkedField = fields[f]! - - if (field.args) { - const args = field.args - Object.keys(args).forEach((key) => { - const arg = args[key] - - if (arg) { - const [typeName] = arg - - if (typeof typeName === 'string') { - if (!linkedTypeMap[typeName]) { - linkedTypeMap[typeName] = { name: typeName } - } - - arg[0] = linkedTypeMap[typeName]! - } - } - }) - } - - const typeName = field.type as LinkedType | string - - if (typeof typeName === 'string') { - if (!linkedTypeMap[typeName]) { - linkedTypeMap[typeName] = { name: typeName } - } - - field.type = linkedTypeMap[typeName]! - } - }) - }) - - return linkedTypeMap -} diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/typeSelection.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/typeSelection.ts deleted file mode 100644 index a021d00bf5..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/typeSelection.ts +++ /dev/null @@ -1,95 +0,0 @@ -// @ts-nocheck -////////////////////////////////////////////////// - -// SOME THINGS TO KNOW BEFORE DIVING IN -/* -0. DST is the request type, SRC is the response type - -1. FieldsSelection uses an object because currently is impossible to make recursive types - -2. FieldsSelection is a recursive type that makes a type based on request type and fields - -3. HandleObject handles object types - -4. Handle__scalar adds all scalar properties excluding non scalar props -*/ - -export type FieldsSelection | undefined, DST> = { - scalar: SRC - union: Handle__isUnion - object: HandleObject - array: SRC extends Nil - ? never - : SRC extends Array - ? Array> - : never - __scalar: Handle__scalar - never: never -}[DST extends Nil - ? 'never' - : DST extends false | 0 - ? 'never' - : SRC extends Scalar - ? 'scalar' - : SRC extends any[] - ? 'array' - : SRC extends { __isUnion?: any } - ? 'union' - : DST extends { __scalar?: any } - ? '__scalar' - : DST extends {} - ? 'object' - : 'never'] - -type HandleObject, DST> = DST extends boolean - ? SRC - : SRC extends Nil - ? never - : Pick< - { - // using keyof SRC to maintain ?: relations of SRC type - [Key in keyof SRC]: Key extends keyof DST - ? FieldsSelection> - : SRC[Key] - }, - Exclude - // { - // // remove falsy values - // [Key in keyof DST]: DST[Key] extends false | 0 ? never : Key - // }[keyof DST] - > - -type Handle__scalar, DST> = SRC extends Nil - ? never - : Pick< - // continue processing fields that are in DST, directly pass SRC type if not in DST - { - [Key in keyof SRC]: Key extends keyof DST - ? FieldsSelection - : SRC[Key] - }, - // remove fields that are not scalars or are not in DST - { - [Key in keyof SRC]: SRC[Key] extends Nil - ? never - : Key extends FieldsToRemove - ? never - : SRC[Key] extends Scalar - ? Key - : Key extends keyof DST - ? Key - : never - }[keyof SRC] - > - -type Handle__isUnion, DST> = SRC extends Nil - ? never - : Omit // just return the union type - -type Scalar = string | number | Date | boolean | null | undefined - -type Anify = { [P in keyof T]?: any } - -type FieldsToRemove = '__isUnion' | '__scalar' | '__name' | '__args' - -type Nil = undefined | null diff --git a/examples/aws-pothos-graphql/graphql/genql/runtime/types.ts b/examples/aws-pothos-graphql/graphql/genql/runtime/types.ts deleted file mode 100644 index 3f0bc30b9e..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/runtime/types.ts +++ /dev/null @@ -1,69 +0,0 @@ -// @ts-nocheck - -export interface ExecutionResult { - errors?: Array - data?: TData | null -} - -export interface ArgMap { - [arg: string]: [keyType, string] | [keyType] | undefined -} - -export type CompressedField = [ - type: keyType, - args?: ArgMap, -] - -export interface CompressedFieldMap { - [field: string]: CompressedField | undefined -} - -export type CompressedType = CompressedFieldMap - -export interface CompressedTypeMap { - scalars: Array - types: { - [type: string]: CompressedType | undefined - } -} - -// normal types -export type Field = { - type: keyType - args?: ArgMap -} - -export interface FieldMap { - [field: string]: Field | undefined -} - -export type Type = FieldMap - -export interface TypeMap { - scalars: Array - types: { - [type: string]: Type | undefined - } -} - -export interface LinkedArgMap { - [arg: string]: [LinkedType, string] | undefined -} -export interface LinkedField { - type: LinkedType - args?: LinkedArgMap -} - -export interface LinkedFieldMap { - [field: string]: LinkedField | undefined -} - -export interface LinkedType { - name: string - fields?: LinkedFieldMap - scalar?: string[] -} - -export interface LinkedTypeMap { - [type: string]: LinkedType | undefined -} diff --git a/examples/aws-pothos-graphql/graphql/genql/schema.graphql b/examples/aws-pothos-graphql/graphql/genql/schema.graphql deleted file mode 100644 index 017afa4426..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/schema.graphql +++ /dev/null @@ -1,12 +0,0 @@ -"""Long necks, cool patterns, taller than you.""" -type Giraffe { - name: String! -} - -type Mutation { - createGiraffe(name: String!): Giraffe! -} - -type Query { - giraffe: Giraffe! -} \ No newline at end of file diff --git a/examples/aws-pothos-graphql/graphql/genql/schema.ts b/examples/aws-pothos-graphql/graphql/genql/schema.ts deleted file mode 100644 index 9677818f0e..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/schema.ts +++ /dev/null @@ -1,70 +0,0 @@ -// @ts-nocheck -/* istanbul ignore file */ -/* tslint:disable */ -/* eslint-disable */ - -export type Scalars = { - String: string, - Boolean: boolean, -} - - -/** Long necks, cool patterns, taller than you. */ -export interface Giraffe { - name: Scalars['String'] - __typename: 'Giraffe' -} - -export interface Mutation { - createGiraffe: Giraffe - __typename: 'Mutation' -} - -export interface Query { - giraffe: Giraffe - __typename: 'Query' -} - - -/** Long necks, cool patterns, taller than you. */ -export interface GiraffeGenqlSelection{ - name?: boolean | number - __typename?: boolean | number - __scalar?: boolean | number -} - -export interface MutationGenqlSelection{ - createGiraffe?: (GiraffeGenqlSelection & { __args: {name: Scalars['String']} }) - __typename?: boolean | number - __scalar?: boolean | number -} - -export interface QueryGenqlSelection{ - giraffe?: GiraffeGenqlSelection - __typename?: boolean | number - __scalar?: boolean | number -} - - - const Giraffe_possibleTypes: string[] = ['Giraffe'] - export const isGiraffe = (obj?: { __typename?: any } | null): obj is Giraffe => { - if (!obj?.__typename) throw new Error('__typename is missing in "isGiraffe"') - return Giraffe_possibleTypes.includes(obj.__typename) - } - - - - const Mutation_possibleTypes: string[] = ['Mutation'] - export const isMutation = (obj?: { __typename?: any } | null): obj is Mutation => { - if (!obj?.__typename) throw new Error('__typename is missing in "isMutation"') - return Mutation_possibleTypes.includes(obj.__typename) - } - - - - const Query_possibleTypes: string[] = ['Query'] - export const isQuery = (obj?: { __typename?: any } | null): obj is Query => { - if (!obj?.__typename) throw new Error('__typename is missing in "isQuery"') - return Query_possibleTypes.includes(obj.__typename) - } - \ No newline at end of file diff --git a/examples/aws-pothos-graphql/graphql/genql/types.ts b/examples/aws-pothos-graphql/graphql/genql/types.ts deleted file mode 100644 index 8ddc017cce..0000000000 --- a/examples/aws-pothos-graphql/graphql/genql/types.ts +++ /dev/null @@ -1,40 +0,0 @@ -export default { - "scalars": [ - 1, - 4 - ], - "types": { - "Giraffe": { - "name": [ - 1 - ], - "__typename": [ - 1 - ] - }, - "String": {}, - "Mutation": { - "createGiraffe": [ - 0, - { - "name": [ - 1, - "String!" - ] - } - ], - "__typename": [ - 1 - ] - }, - "Query": { - "giraffe": [ - 0 - ], - "__typename": [ - 1 - ] - }, - "Boolean": {} - } -} \ No newline at end of file diff --git a/examples/aws-pothos-graphql/graphql/schema.graphql b/examples/aws-pothos-graphql/graphql/schema.graphql deleted file mode 100644 index 017afa4426..0000000000 --- a/examples/aws-pothos-graphql/graphql/schema.graphql +++ /dev/null @@ -1,12 +0,0 @@ -"""Long necks, cool patterns, taller than you.""" -type Giraffe { - name: String! -} - -type Mutation { - createGiraffe(name: String!): Giraffe! -} - -type Query { - giraffe: Giraffe! -} \ No newline at end of file diff --git a/examples/aws-pothos-graphql/graphql/urql.ts b/examples/aws-pothos-graphql/graphql/urql.ts deleted file mode 100644 index 60833df69e..0000000000 --- a/examples/aws-pothos-graphql/graphql/urql.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { - useQuery, - useClient, - createRequest, - RequestPolicy, - OperationResult, - UseMutationState, - OperationContext, - UseMutationResponse, -} from "urql"; -import { useEffect, useState, useCallback, useRef } from "react"; -import { - QueryResult, - QueryGenqlSelection, - MutationResult, - MutationGenqlSelection, - generateQueryOp, - generateMutationOp, -} from "./genql"; - -import { pipe, toPromise } from "wonka"; - -export function useTypedQuery(opts: { - query: Query; - pause?: boolean; - requestPolicy?: RequestPolicy; - context?: Partial; -}) { - const { query, variables } = generateQueryOp(opts.query); - return useQuery>({ - ...opts, - query, - variables, - }); -} - -const initialState = { - stale: false, - fetching: false, - data: undefined, - error: undefined, - operation: undefined, - extensions: undefined, -}; - -export function useTypedMutation< - Variables extends Record, - Mutation extends MutationGenqlSelection, - Data extends MutationResult ->( - builder: (vars: Variables) => Mutation, - opts?: Partial -): UseMutationResponse { - const client = useClient(); - const isMounted = useRef(true); - const [state, setState] = - useState>(initialState); - const executeMutation = useCallback( - ( - vars?: Variables, - context?: Partial - ): Promise> => { - setState({ ...initialState, fetching: true }); - const buildArgs = vars || ({} as Variables); - const built = builder(buildArgs); - const { query, variables } = generateMutationOp(built); - return pipe( - client.executeMutation( - createRequest(query, variables as Variables), - { ...opts, ...context } - ), - toPromise - ).then((result: OperationResult) => { - if (isMounted.current) { - setState({ - fetching: false, - stale: !!result.stale, - data: result.data, - error: result.error, - extensions: result.extensions, - operation: result.operation, - }); - } - return result; - }); - }, - [state, setState] - ); - - useEffect(() => { - isMounted.current = true; - return () => { - isMounted.current = false; - }; - }, []); - - return [state, executeMutation]; -} diff --git a/examples/aws-pothos-graphql/package.json b/examples/aws-pothos-graphql/package.json deleted file mode 100644 index cb287214e0..0000000000 --- a/examples/aws-pothos-graphql/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "aws-pothos-graphql", - "dependencies": { - "@pothos/core": "^3.41.1", - "@urql/core": "^5.0.4", - "graphql-yoga": "^5.3.1", - "react": "^18.3.1", - "sst": "file:../../sdk/js", - "urql": "^4.1.0", - "wonka": "^6.3.4" - }, - "devDependencies": { - "@genql/cli": "^6.3.3", - "@types/aws-lambda": "8.10.138", - "@types/react": "^18.3.3" - } -} diff --git a/examples/aws-pothos-graphql/pothos/builder.ts b/examples/aws-pothos-graphql/pothos/builder.ts deleted file mode 100644 index 3dc1195588..0000000000 --- a/examples/aws-pothos-graphql/pothos/builder.ts +++ /dev/null @@ -1,6 +0,0 @@ -import SchemaBuilder from "@pothos/core"; - -export const builder = new SchemaBuilder({}); - -builder.queryType({}); -builder.mutationType({}); diff --git a/examples/aws-pothos-graphql/pothos/extract.ts b/examples/aws-pothos-graphql/pothos/extract.ts deleted file mode 100644 index 0326d4a3fa..0000000000 --- a/examples/aws-pothos-graphql/pothos/extract.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { lexicographicSortSchema, printSchema } from "graphql"; -import path from "path"; -import { schema } from "./schema"; - -async function extract() { - const schemaAsString = printSchema(lexicographicSortSchema(schema)); - - await Bun.write("./graphql/schema.graphql", schemaAsString); - - const proc = Bun.spawn( - [ - "bun", - "x", - "@genql/cli", - "--output", - "./genql", - "--schema", - "./schema.graphql", - "--esm", - ], - { - cwd: "./graphql", - } - ); - - const exitCode = await proc.exited; - if (exitCode !== 0) { - throw Error(`Genegration faild with code ${exitCode}`); - } -} - -extract() - .then(() => { - console.log("Pothos schema extracted successfully."); - }) - .catch((error) => { - console.error("Failed to extract pothos schema the database:", error); - }); diff --git a/examples/aws-pothos-graphql/pothos/graphql.ts b/examples/aws-pothos-graphql/pothos/graphql.ts deleted file mode 100644 index a11cb0cfb7..0000000000 --- a/examples/aws-pothos-graphql/pothos/graphql.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { schema } from "./schema"; -import { awsLambdaRequestHandler } from "./server"; - -export const handler = awsLambdaRequestHandler({ - schema, -}); diff --git a/examples/aws-pothos-graphql/pothos/schema.ts b/examples/aws-pothos-graphql/pothos/schema.ts deleted file mode 100644 index fb2921ffe5..0000000000 --- a/examples/aws-pothos-graphql/pothos/schema.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { builder } from "./builder"; - -import "./types/giraffe"; - -export const schema = builder.toSchema({}); diff --git a/examples/aws-pothos-graphql/pothos/server.ts b/examples/aws-pothos-graphql/pothos/server.ts deleted file mode 100644 index 56536f2bc6..0000000000 --- a/examples/aws-pothos-graphql/pothos/server.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { - APIGatewayProxyEventV2, - APIGatewayProxyResult, - Context, -} from "aws-lambda"; -import { createYoga, YogaServerOptions } from "graphql-yoga"; - -type ServerContext = { - event: APIGatewayProxyEventV2; - context: Context; -}; - -export function awsLambdaRequestHandler( - options: YogaServerOptions -) { - const yoga = createYoga({ - ...options, - }); - - return async ( - event: APIGatewayProxyEventV2, - lambdaContext: Context - ): Promise => { - const parameters = new URLSearchParams( - (event.queryStringParameters as Record) || {} - ).toString(); - - const url = `${event.rawPath}?${parameters}`; - - const request: RequestInit = { - method: event.requestContext.http.method, - headers: event.headers as HeadersInit, - body: event.body - ? Buffer.from(event.body, event.isBase64Encoded ? "base64" : "utf8") - : undefined, - }; - - const serverContext: ServerContext = { - event, - context: lambdaContext, - }; - - const response = await yoga.fetch(url, request, serverContext); - const responseHeaders = Object.fromEntries(response.headers.entries()); - - return { - statusCode: response.status, - headers: responseHeaders, - body: await response.text(), - isBase64Encoded: false, - }; - }; -} diff --git a/examples/aws-pothos-graphql/pothos/types/giraffe.ts b/examples/aws-pothos-graphql/pothos/types/giraffe.ts deleted file mode 100644 index d0dbeab188..0000000000 --- a/examples/aws-pothos-graphql/pothos/types/giraffe.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { builder } from "../builder"; - -export class Giraffe { - name: string; - - constructor(name: string) { - this.name = name; - } -} - -builder.objectType(Giraffe, { - name: "Giraffe", - description: "Long necks, cool patterns, taller than you.", - fields: (t) => ({ - name: t.exposeString("name", {}), - }), -}); - -builder.queryFields((t) => ({ - giraffe: t.field({ - type: Giraffe, - resolve: () => new Giraffe("James"), - }), -})); - -builder.mutationFields((t) => ({ - createGiraffe: t.field({ - type: Giraffe, - args: { - name: t.arg.string({ required: true }), - }, - resolve: async (root, args) => { - const giraffe = { name: args.name }; - - return giraffe; - }, - }), -})); diff --git a/examples/aws-pothos-graphql/sst.config.ts b/examples/aws-pothos-graphql/sst.config.ts deleted file mode 100644 index ef154806d8..0000000000 --- a/examples/aws-pothos-graphql/sst.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-pothos-graphql", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - if ($dev) { - new sst.x.DevCommand("PothosGraphqlExtractor", { - dev: { - command: "bun --watch run pothos/extract.ts", - autostart: true, - }, - }); - } - - const api = new sst.aws.ApiGatewayV2("Api"); - api.route("POST /graphql", "pothos/graphql.handler"); - - const client = new sst.aws.Function("Client", { - url: true, - link: [api], - handler: "client.handler", - }); - - return { - api: api.url, - client: client.url, - }; - }, -}); diff --git a/examples/aws-pothos-graphql/tsconfig.json b/examples/aws-pothos-graphql/tsconfig.json deleted file mode 100644 index aee0ec940f..0000000000 --- a/examples/aws-pothos-graphql/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "strict": true - } -} diff --git a/examples/aws-prisma-lambda/.gitignore b/examples/aws-prisma-lambda/.gitignore deleted file mode 100644 index 11ddd8dbe6..0000000000 --- a/examples/aws-prisma-lambda/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -# Keep environment variables out of version control -.env diff --git a/examples/aws-prisma-lambda/index.ts b/examples/aws-prisma-lambda/index.ts deleted file mode 100644 index 99633c21b1..0000000000 --- a/examples/aws-prisma-lambda/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { prisma } from "./prisma"; - -async function createUser(name: string, email: string) { - return prisma.user.create({ - data: { name, email }, - }); -} - -export async function handler() { - const user = await createUser("Alice", `alice-${crypto.randomUUID()}@example.com`); - return { - statusCode: 201, - body: JSON.stringify({ user }), - }; -} diff --git a/examples/aws-prisma-lambda/package.json b/examples/aws-prisma-lambda/package.json deleted file mode 100644 index 423d683d52..0000000000 --- a/examples/aws-prisma-lambda/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "aws-prisma-lambda", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "postinstall": "prisma generate", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "@types/aws-lambda": "^8.10.145", - "@types/node": "^22.5.4", - "prisma": "^5.19.1", - "ts-node": "^10.9.2", - "typescript": "^5.5.4" - }, - "dependencies": { - "@prisma/client": "^5.19.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-prisma-lambda/prisma.ts b/examples/aws-prisma-lambda/prisma.ts deleted file mode 100644 index 4a1ae94b80..0000000000 --- a/examples/aws-prisma-lambda/prisma.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Resource } from "sst"; -import { PrismaClient } from '@prisma/client'; - -const globalForPrisma = global as unknown as { prisma: PrismaClient } - -export const prisma = globalForPrisma.prisma || - new PrismaClient({ - datasources: { - db: { - url: `postgresql://${Resource.MyPostgres.username}:${Resource.MyPostgres.password}@${Resource.MyPostgres.host}:${Resource.MyPostgres.port}/${Resource.MyPostgres.database}?connection_limit=1`, - }, - }, - }); - -// Create single client in `sst dev` -if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma diff --git a/examples/aws-prisma-lambda/prisma/migrations/0_init/migration.sql b/examples/aws-prisma-lambda/prisma/migrations/0_init/migration.sql deleted file mode 100644 index 1e9eb8fd02..0000000000 --- a/examples/aws-prisma-lambda/prisma/migrations/0_init/migration.sql +++ /dev/null @@ -1,11 +0,0 @@ --- CreateTable -CREATE TABLE "User" ( - "id" SERIAL NOT NULL, - "name" TEXT, - "email" TEXT NOT NULL, - - CONSTRAINT "User_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); diff --git a/examples/aws-prisma-lambda/prisma/schema.prisma b/examples/aws-prisma-lambda/prisma/schema.prisma deleted file mode 100644 index c377c80546..0000000000 --- a/examples/aws-prisma-lambda/prisma/schema.prisma +++ /dev/null @@ -1,18 +0,0 @@ -generator client { - provider = "prisma-client-js" - // For x86 - binaryTargets = ["native", "rhel-openssl-3.0.x"] - // For ARM - // binaryTargets = ["native", "linux-arm64-openssl-3.0.x"] -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} - -model User { - id Int @id @default(autoincrement()) - name String? - email String @unique -} diff --git a/examples/aws-prisma-lambda/sst.config.ts b/examples/aws-prisma-lambda/sst.config.ts deleted file mode 100644 index a10fb65e69..0000000000 --- a/examples/aws-prisma-lambda/sst.config.ts +++ /dev/null @@ -1,98 +0,0 @@ -/// - -/** - * ## Prisma in Lambda - * - * To use Prisma in a Lambda function you need to - * - * - Generate the Prisma Client with the right architecture - * - Copy the generated client to the function - * - Run the function inside a VPC - * - * You can set the architecture using the `binaryTargets` option in `prisma/schema.prisma`. - * - * ```prisma title="prisma/schema.prisma" - * // For x86 - * binaryTargets = ["native", "rhel-openssl-3.0.x"] - * // For ARM - * // binaryTargets = ["native", "linux-arm64-openssl-3.0.x"] - * ``` - * - * You can also switch to ARM, just make sure to also change the function architecture in your - * `sst.config.ts`. - * - * ```ts title="sst.config.ts" - * { - * // For ARM - * architecture: "arm64" - * } - * ``` - * - * To generate the client, you need to run `prisma generate` when you make changes to the - * schema. - * - * Since this [needs to be done on every deploy](https://www.prisma.io/docs/orm/more/help-and-troubleshooting/help-articles/vercel-caching-issue#a-custom-postinstall-script), we add a `postinstall` script to the `package.json`. - * - * ```json title="package.json" - * "scripts": { - * "postinstall": "prisma generate" - * } - * ``` - * - * This runs the command on `npm install`. - * - * We then need to copy the generated client to the function when we deploy. - * - * ```ts title="sst.config.ts" - * { - * copyFiles: [{ from: "node_modules/.prisma/client/" }] - * } - * ``` - * - * Our function also needs to run inside a VPC, since Prisma doesn't support the Data API. - * - * ```ts title="sst.config.ts" - * { - * vpc - * } - * ``` - * - * #### Prisma in serverless environments - * - * Prisma is [not great in serverless environments](https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/databases-connections#serverless-environments-faas). For a couple of reasons: - * - * 1. It doesn't support Data API, so you need to manage the connection pool on your own. - * 2. Without the Data API, your functions need to run inside a VPC. - * - You cannot use `sst dev` without [connecting to the VPC](/docs/live#using-a-vpc). - * 3. Due to the internal architecture of their client, it's also has slower cold starts. - * - * Instead we recommend using [Drizzle](https://orm.drizzle.team). This example is here for - * reference for people that are already using Prisma. - */ -export default $config({ - app(input) { - return { - name: "aws-prisma-lambda", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "managed" }); - const rds = new sst.aws.Postgres("MyPostgres", { vpc }); - - const api = new sst.aws.Function("MyApi", { - vpc, - url: true, - link: [rds], - // For ARM - // architecture: "arm64", - handler: "index.handler", - copyFiles: [{ from: "node_modules/.prisma/client/" }], - }); - - return { - api: api.url, - }; - }, -}); diff --git a/examples/aws-prisma-lambda/tsconfig.json b/examples/aws-prisma-lambda/tsconfig.json deleted file mode 100644 index 8bb6097f80..0000000000 --- a/examples/aws-prisma-lambda/tsconfig.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } -} diff --git a/examples/aws-prisma/.dockerignore b/examples/aws-prisma/.dockerignore deleted file mode 100644 index ea0aaeeec9..0000000000 --- a/examples/aws-prisma/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-prisma/.gitignore b/examples/aws-prisma/.gitignore deleted file mode 100644 index 033b3ef1cc..0000000000 --- a/examples/aws-prisma/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -# Keep environment variables out of version control -.env - -# sst -.sst diff --git a/examples/aws-prisma/Dockerfile b/examples/aws-prisma/Dockerfile deleted file mode 100644 index c532d99a54..0000000000 --- a/examples/aws-prisma/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json index.mjs prisma /app/ -RUN npm install - -RUN npx prisma generate - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-prisma/index.mjs b/examples/aws-prisma/index.mjs deleted file mode 100644 index f90c0e4a50..0000000000 --- a/examples/aws-prisma/index.mjs +++ /dev/null @@ -1,21 +0,0 @@ -import express from "express"; -import { PrismaClient } from '@prisma/client'; - -const PORT = 80; - -const app = express(); -const prisma = new PrismaClient(); - -app.get("/", async (_req, res) => { - const user = await prisma.user.create({ - data: { - name: "Alice", - email: `alice-${crypto.randomUUID()}@example.com` - }, - }); - res.send(JSON.stringify(user)); -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-prisma/package.json b/examples/aws-prisma/package.json deleted file mode 100644 index 6be9028453..0000000000 --- a/examples/aws-prisma/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "aws-prisma", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "@types/node": "^22.7.8", - "prisma": "^5.21.1", - "ts-node": "^10.9.2", - "typescript": "^5.6.3" - }, - "dependencies": { - "@prisma/client": "^5.21.1", - "express": "^4.21.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-prisma/prisma/migrations/20241022202928_init/migration.sql b/examples/aws-prisma/prisma/migrations/20241022202928_init/migration.sql deleted file mode 100644 index 1e9eb8fd02..0000000000 --- a/examples/aws-prisma/prisma/migrations/20241022202928_init/migration.sql +++ /dev/null @@ -1,11 +0,0 @@ --- CreateTable -CREATE TABLE "User" ( - "id" SERIAL NOT NULL, - "name" TEXT, - "email" TEXT NOT NULL, - - CONSTRAINT "User_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); diff --git a/examples/aws-prisma/prisma/schema.prisma b/examples/aws-prisma/prisma/schema.prisma deleted file mode 100644 index 3c4e2ed8f5..0000000000 --- a/examples/aws-prisma/prisma/schema.prisma +++ /dev/null @@ -1,20 +0,0 @@ -// This is your Prisma schema file, -// learn more about it in the docs: https://pris.ly/d/prisma-schema - -// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions? -// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init - -generator client { - provider = "prisma-client-js" -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} - -model User { - id Int @id @default(autoincrement()) - name String? - email String @unique -} diff --git a/examples/aws-prisma/sst.config.ts b/examples/aws-prisma/sst.config.ts deleted file mode 100644 index 0b72a75085..0000000000 --- a/examples/aws-prisma/sst.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-prisma", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const rds = new sst.aws.Postgres("MyPostgres", { vpc }); - - const DATABASE_URL = $interpolate`postgresql://${rds.username}:${rds.password}@${rds.host}:${rds.port}/${rds.database}`; - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [rds], - environment: { DATABASE_URL }, - loadBalancer: { - ports: [{ listen: "80/http" }], - }, - dev: { - command: "node --watch index.mjs", - }, - }); - - new sst.x.DevCommand("Prisma", { - environment: { DATABASE_URL }, - dev: { - autostart: false, - command: "npx prisma studio", - }, - }); - }, -}); diff --git a/examples/aws-prisma/tsconfig.json b/examples/aws-prisma/tsconfig.json deleted file mode 100644 index 56a8ab8109..0000000000 --- a/examples/aws-prisma/tsconfig.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } -} diff --git a/examples/aws-puppeteer/.gitignore b/examples/aws-puppeteer/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-puppeteer/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-puppeteer/index.ts b/examples/aws-puppeteer/index.ts deleted file mode 100644 index da3500de7c..0000000000 --- a/examples/aws-puppeteer/index.ts +++ /dev/null @@ -1,42 +0,0 @@ -import puppeteer from "puppeteer-core"; -import chromium from "@sparticuz/chromium"; - -// This is the path to the local Chromium binary -const YOUR_LOCAL_CHROMIUM_PATH = - "/tmp/localChromium/chromium/mac_arm-1350406/chrome-mac/Chromium.app/Contents/MacOS/Chromium"; - -export async function handler() { - const url = "https://sst.dev"; - const width = 1024; - const height = 768; - - const browser = await puppeteer.launch({ - args: chromium.args, - defaultViewport: chromium.defaultViewport, - executablePath: process.env.SST_DEV - ? YOUR_LOCAL_CHROMIUM_PATH - : await chromium.executablePath(), - headless: chromium.headless, - }); - - const page = await browser.newPage(); - - await page.setViewport({ - width: width, - height: height, - }); - - await page.goto(url!); - - const screenshot = (await page.screenshot({ encoding: "base64" })) as string; - - return { - statusCode: 200, - body: screenshot, - isBase64Encoded: true, - headers: { - "Content-Type": "image/png", - "Content-Disposition": "inline", - }, - }; -} diff --git a/examples/aws-puppeteer/package.json b/examples/aws-puppeteer/package.json deleted file mode 100644 index 892b488539..0000000000 --- a/examples/aws-puppeteer/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "aws-puppeteer", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@sparticuz/chromium": "^127.0.0", - "puppeteer-core": "^23.1.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-puppeteer/sst.config.ts b/examples/aws-puppeteer/sst.config.ts deleted file mode 100644 index b65b788afd..0000000000 --- a/examples/aws-puppeteer/sst.config.ts +++ /dev/null @@ -1,108 +0,0 @@ -/// - -/** - * ## Puppeteer in Lambda - * - * To use Puppeteer in a Lambda function you need: - * - * 1. [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) - * 2. Chromium - * - In `sst dev`, we'll use a locally installed Chromium version. - * - In `sst deploy`, we'll use the [`@sparticuz/chromium`](https://github.com/sparticuz/chromium) package. It comes with a pre-built binary for Lambda. - * - * #### Chromium version - * - * Since Puppeteer has a preferred version of Chromium, we'll need to check the version of - * Chrome that a given version of Puppeteer supports. Head over to the - * [Puppeteer's Chromium Support page](https://pptr.dev/chromium-support) and check which - * versions work together. - * - * For example, Puppeteer v23.1.1 supports Chrome for Testing 127.0.6533.119. So, we'll use the - * v127 of `@sparticuz/chromium`. - * - * ```bash - * npm install puppeteer-core@23.1.1 @sparticuz/chromium@127.0.0 - * ``` - * - * #### Install Chromium locally - * - * To use this locally, you'll need to install Chromium. - * - * ```bash - * npx @puppeteer/browsers install chromium@latest --path /tmp/localChromium - * ``` - * - * Once installed you'll see the location of the Chromium binary, `/tmp/localChromium/chromium/mac_arm-1350406/chrome-mac/Chromium.app/Contents/MacOS/Chromium`. - * - * Update this in your Lambda function. - * - * ```ts title="index.ts" - * // This is the path to the local Chromium binary - * const YOUR_LOCAL_CHROMIUM_PATH = "/tmp/localChromium/chromium/mac_arm-1350406/chrome-mac/Chromium.app/Contents/MacOS/Chromium"; - * ``` - * - * You'll notice we are using the right binary with the `SST_DEV` environment variable. - * - * ```ts title="index.ts" {4-6} - * const browser = await puppeteer.launch({ - * args: chromium.args, - * defaultViewport: chromium.defaultViewport, - * executablePath: process.env.SST_DEV - * ? YOUR_LOCAL_CHROMIUM_PATH - * : await chromium.executablePath(), - * headless: chromium.headless, - * }); - * ``` - * - * #### Deploy - * - * We don't need a layer to deploy this because `@sparticuz/chromium` comes with a pre-built - * binary for Lambda. - * - * :::note - * As of writing this, `arm64` is not supported by `@sparticuz/chromium`. - * ::: - * - * We just need to set it in the [`nodejs.install`](/docs/component/aws/function#nodejs-install). - * - * ```ts title="sst.config.ts" - * { - * nodejs: { - * install: ["@sparticuz/chromium"] - * } - * } - * ``` - * - * And on deploy, SST will use the right binary. - * - * :::tip - * You don't need to use a Lambda layer to use Puppeteer. - * ::: - * - * We are giving our function more memory and a longer timeout since running Puppeteer can - * take a while. - */ -export default $config({ - app(input) { - return { - name: "aws-puppeteer", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const api = new sst.aws.Function("MyFunction", { - url: true, - memory: "2 GB", - timeout: "15 minutes", - handler: "index.handler", - nodejs: { - install: ["@sparticuz/chromium"], - }, - }); - - return { - url: api.url, - }; - }, -}); diff --git a/examples/aws-puppeteer/tsconfig.json b/examples/aws-puppeteer/tsconfig.json deleted file mode 100644 index 2f98042715..0000000000 --- a/examples/aws-puppeteer/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "esModuleInterop": true - } -} diff --git a/examples/aws-python-container/.gitignore b/examples/aws-python-container/.gitignore deleted file mode 100644 index 17ace783f5..0000000000 --- a/examples/aws-python-container/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.sst -.venv \ No newline at end of file diff --git a/examples/aws-python-container/core/pyproject.toml b/examples/aws-python-container/core/pyproject.toml deleted file mode 100644 index 4d9ed5884e..0000000000 --- a/examples/aws-python-container/core/pyproject.toml +++ /dev/null @@ -1,11 +0,0 @@ -[project] -name = "core" -version = "0.1.0" -description = "Add your description here" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -requires-python = "==3.11.*" -dependencies = ["requests>=2.32.3"] - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" diff --git a/examples/aws-python-container/core/src/core/__init__.py b/examples/aws-python-container/core/src/core/__init__.py deleted file mode 100644 index 8b13789179..0000000000 --- a/examples/aws-python-container/core/src/core/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/aws-python-container/core/src/core/ping.py b/examples/aws-python-container/core/src/core/ping.py deleted file mode 100644 index c13cfd5726..0000000000 --- a/examples/aws-python-container/core/src/core/ping.py +++ /dev/null @@ -1,5 +0,0 @@ -import requests - - -def ping(): - return requests.get("https://api.github.com").status_code diff --git a/examples/aws-python-container/custom_dockerfile/Dockerfile b/examples/aws-python-container/custom_dockerfile/Dockerfile deleted file mode 100644 index a8383a707c..0000000000 --- a/examples/aws-python-container/custom_dockerfile/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# The python version to use is supplied as an arg from SST -ARG PYTHON_VERSION=3.11 - -# Use an official AWS Lambda base image for Python -FROM public.ecr.aws/lambda/python:${PYTHON_VERSION} - -# # Ensure git is installed so we can install git based dependencies (such as sst) -RUN if command -v dnf > /dev/null 2>&1; then \ - dnf update -y && dnf install -y git gcc && dnf clean all; \ - elif command -v yum > /dev/null 2>&1; then \ - yum install -y git gcc && yum clean all; \ - fi - -# Install UV to manage your python runtime -COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv - -# Copy everything first so workspace packages (referenced as ./pkg in requirements.txt) -# are available during dependency installation -COPY . ${LAMBDA_TASK_ROOT} - -# Install the dependencies to the lambda runtime -RUN uv pip install -r requirements.txt --target ${LAMBDA_TASK_ROOT} --system - -# Perform any steps that you want here: -# Example: pre-bake in model weights from huggingface to image - -# No need to configure the handler or entrypoint - SST will do that diff --git a/examples/aws-python-container/custom_dockerfile/pyproject.toml b/examples/aws-python-container/custom_dockerfile/pyproject.toml deleted file mode 100644 index feae2e5b61..0000000000 --- a/examples/aws-python-container/custom_dockerfile/pyproject.toml +++ /dev/null @@ -1,14 +0,0 @@ -[project] -name = "custom_dockerfile" -version = "0.1.0" -description = "Custom Dockerfile" -dependencies = ["core", "sst-sdk"] -requires-python = "==3.11.*" - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[tool.uv.sources] -core = { workspace = true } -sst-sdk = { git = "https://github.com/anomalyco/sst.git", branch = "dev", subdirectory = "sdk/python" } diff --git a/examples/aws-python-container/custom_dockerfile/src/custom_dockerfile/api.py b/examples/aws-python-container/custom_dockerfile/src/custom_dockerfile/api.py deleted file mode 100644 index 62a8ff638b..0000000000 --- a/examples/aws-python-container/custom_dockerfile/src/custom_dockerfile/api.py +++ /dev/null @@ -1,12 +0,0 @@ -from core.ping import ping -from sst import Resource - - -def handler(event, context): - response_code = ping() - print(f"Response code: {response_code}") - - return { - "statusCode": 200, - "body": f"Hello, World! - Linkable value: {Resource.MyLinkableValue.foo}", - } diff --git a/examples/aws-python-container/functions/pyproject.toml b/examples/aws-python-container/functions/pyproject.toml deleted file mode 100644 index 8eefe8e19d..0000000000 --- a/examples/aws-python-container/functions/pyproject.toml +++ /dev/null @@ -1,14 +0,0 @@ -[project] -name = "functions" -version = "0.1.0" -description = "Lambda function (container-mode)handlers" -dependencies = ["core", "sst-sdk"] -requires-python = "==3.11.*" - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[tool.uv.sources] -core = { workspace = true } -sst-sdk = { git = "https://github.com/anomalyco/sst.git", branch = "dev", subdirectory = "sdk/python" } diff --git a/examples/aws-python-container/functions/src/functions/api.py b/examples/aws-python-container/functions/src/functions/api.py deleted file mode 100644 index 62a8ff638b..0000000000 --- a/examples/aws-python-container/functions/src/functions/api.py +++ /dev/null @@ -1,12 +0,0 @@ -from core.ping import ping -from sst import Resource - - -def handler(event, context): - response_code = ping() - print(f"Response code: {response_code}") - - return { - "statusCode": 200, - "body": f"Hello, World! - Linkable value: {Resource.MyLinkableValue.foo}", - } diff --git a/examples/aws-python-container/pyproject.toml b/examples/aws-python-container/pyproject.toml deleted file mode 100644 index 4cd1c70628..0000000000 --- a/examples/aws-python-container/pyproject.toml +++ /dev/null @@ -1,16 +0,0 @@ -[project] -name = "aws-python-container" -version = "0.1.0" -description = "A SST app" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -dependencies = [] - -# It is recommended to specify your python version to match your Lambda runtime otherwise you may -# encounter issues with dependencies. -requires-python = "==3.11.*" - -[tool.uv.workspace] -members = ["functions", "core", "custom_dockerfile"] - -[tool.uv.sources] -sst-sdk = { git = "https://github.com/anomalyco/sst.git", subdirectory = "sdk/python", branch = "dev" } diff --git a/examples/aws-python-container/sst.config.ts b/examples/aws-python-container/sst.config.ts deleted file mode 100644 index f49506a8f5..0000000000 --- a/examples/aws-python-container/sst.config.ts +++ /dev/null @@ -1,118 +0,0 @@ -/// - -/** - * ## AWS Lambda Python container - * - * Python Lambda function that use large dependencies like `numpy` and `pandas`, can - * hit the 250MB Lambda package limit. To work around this, you can deploy them - * as a container image to Lambda. - * - * :::tip - * Container images on Lambda have a limit of 10GB. - * ::: - * - * In this example, we deploy two functions as container image. - * - * ```ts title="sst.config.ts" {2-4} - * const base = new sst.aws.Function("PythonFn", { - * python: { - * container: true, - * }, - * handler: "./functions/src/functions/api.handler", - * runtime: "python3.11", - * link: [linkableValue], - * url: true, - * }); - * ``` - * - * Now when you run `sst deploy`, it uses a built-in Dockerfile to build the image - * and deploy it. You'll need to have the Docker daemon running. - * - * :::note - * You need to have the Docker daemon running locally. - * ::: - * - * To use a custom Dockerfile, you can place a `Dockerfile` in the root of the - * uv workspace for your function. - * - * ```ts title="sst.config.ts" {5} - * const custom = new sst.aws.Function("PythonFnCustom", { - * python: { - * container: true, - * }, - * handler: "./custom_dockerfile/src/custom_dockerfile/api.handler", - * runtime: "python3.11", - * link: [linkableValue], - * url: true, - * }); - * ``` - * - * Here we have a `Dockerfile` in the `custom_dockerfile/` directory. - * - * ```dockerfile title="custom_dockerfile/Dockerfile" - * # The python version to use is supplied as an arg from SST - * ARG PYTHON_VERSION=3.11 - * - * # Use an official AWS Lambda base image for Python - * FROM public.ecr.aws/lambda/python:${PYTHON_VERSION} - * - * # ... - * ``` - * - * The project structure looks something like this. - * - * ```txt {5} - * ├── sst.config.ts - * ├── pyproject.toml - * └── custom_dockerfile - * ├── pyproject.toml - * ├── Dockerfile - * └── src - * └── custom_dockerfile - * └── api.py - * ``` - * - * Locally, you want to set the Python version in your `pyproject.toml` to make sure - * that `sst dev` uses the same version as `sst deploy`. - */ -export default $config({ - app(input) { - return { - name: "aws-python-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const linkableValue = new sst.Linkable("MyLinkableValue", { - properties: { - foo: "Hello World", - }, - }); - - const base = new sst.aws.Function("PythonFn", { - python: { - container: true, - }, - handler: "./functions/src/functions/api.handler", - runtime: "python3.11", - link: [linkableValue], - url: true, - }); - - const custom = new sst.aws.Function("PythonFnCustom", { - python: { - container: true, - }, - handler: "./custom_dockerfile/src/custom_dockerfile/api.handler", - runtime: "python3.11", - link: [linkableValue], - url: true, - }); - - return { - base: base.url, - custom: custom.url, - }; - }, -}); diff --git a/examples/aws-python-container/tsconfig.json b/examples/aws-python-container/tsconfig.json deleted file mode 100644 index 9e26dfeeb6..0000000000 --- a/examples/aws-python-container/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/examples/aws-python-huggingface/.gitignore b/examples/aws-python-huggingface/.gitignore deleted file mode 100644 index 17ace783f5..0000000000 --- a/examples/aws-python-huggingface/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.sst -.venv \ No newline at end of file diff --git a/examples/aws-python-huggingface/functions/Dockerfile b/examples/aws-python-huggingface/functions/Dockerfile deleted file mode 100644 index b7f8c97a6e..0000000000 --- a/examples/aws-python-huggingface/functions/Dockerfile +++ /dev/null @@ -1,42 +0,0 @@ -# If any docker wizard is interested, a multi-stage build would be better for caching -# and reducing the size of the final image - -# The python version to use is supplied as an arg from SST -ARG PYTHON_VERSION=3.12 - -# Use an official AWS Lambda base image for Python -FROM public.ecr.aws/lambda/python:${PYTHON_VERSION} as builder - -# # Ensure git is installed so we can install git based dependencies (such as sst) -ARG PYTHON_RUNTIME - -# Install git and gcc using appropriate package manager based on Python version -RUN dnf install -y git gcc gcc-c++ openssl-devel - -# Install Rust using rustup -RUN curl https://sh.rustup.rs -sSf | sh -s -- -y - -# Add Cargo to PATH -ENV PATH="/root/.cargo/bin:${PATH}" - -# Install UV to manage your python runtime -COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv - -# Copy everything first so workspace package references (e.g., ./functions) -# in requirements.txt resolve correctly during installation -COPY . ${LAMBDA_TASK_ROOT} - -# Install the dependencies to the lambda runtime -RUN uv pip install -r requirements.txt --target ${LAMBDA_TASK_ROOT} --system --no-verify-hashes - -FROM public.ecr.aws/lambda/python:${PYTHON_VERSION} - -ENV HF_HOME=/tmp/transformers_cache - -# Copy installed dependencies and application code from the builder stage -COPY --from=builder ${LAMBDA_TASK_ROOT} ${LAMBDA_TASK_ROOT} - -# Copy the rest of the code -COPY . ${LAMBDA_TASK_ROOT} - -# No need to configure the handler or entrypoint - SST will do that \ No newline at end of file diff --git a/examples/aws-python-huggingface/functions/pyproject.toml b/examples/aws-python-huggingface/functions/pyproject.toml deleted file mode 100644 index 1c8df57c9a..0000000000 --- a/examples/aws-python-huggingface/functions/pyproject.toml +++ /dev/null @@ -1,22 +0,0 @@ -[project] -name = "functions" -version = "0.1.0" -description = "A SST app" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -dependencies = ["transformers>=4.44.2", "torch==2.3.1"] - -# It is recommended to specify your python version to match your Lambda runtime otherwise you may -# encounter issues with dependencies. -requires-python = "==3.12.*" - -[tool.uv.sources] -torch = [{ index = "pytorch-cpu", marker = "platform_system != 'Darwin'" }] - -[[tool.uv.index]] -name = "pytorch-cpu" -url = "https://download.pytorch.org/whl/cpu" -explicit = true - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" diff --git a/examples/aws-python-huggingface/functions/src/functions/api.py b/examples/aws-python-huggingface/functions/src/functions/api.py deleted file mode 100644 index c25dc9af41..0000000000 --- a/examples/aws-python-huggingface/functions/src/functions/api.py +++ /dev/null @@ -1,29 +0,0 @@ -from transformers import pipeline -import json - -# Initialize the pipeline once (outside the handler) to avoid reloading the model on each request -pipe = pipeline("text-generation", model="roneneldan/TinyStories-1M") - - -def handler(event, context): - # Define the prompt for text generation - prompt = "Write a short story about the magical framework SST that makes the cloud so easy to use!" - - # Generate text using the pipeline - response = pipe( - prompt, - max_length=150, - num_return_sequences=1, - temperature=0.6, - top_k=50, - do_sample=True, - ) - - # Extract the generated text - generated_text = response[0]["generated_text"] - - # Return the response with a status code and JSON-encoded body - return { - "statusCode": 200, - "body": json.dumps({"story": generated_text}), - } diff --git a/examples/aws-python-huggingface/pyproject.toml b/examples/aws-python-huggingface/pyproject.toml deleted file mode 100644 index fb335d9b8f..0000000000 --- a/examples/aws-python-huggingface/pyproject.toml +++ /dev/null @@ -1,16 +0,0 @@ -[project] -name = "aws-python-huggingface" -version = "0.1.0" -description = "A SST app" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -dependencies = [] - -# It is recommended to specify your python version to match your Lambda runtime otherwise you may -# encounter issues with dependencies. -requires-python = "==3.12.*" - -[tool.uv.workspace] -members = ["functions"] - -[tool.uv.sources] -sst-sdk = { git = "https://github.com/anomalyco/sst.git", subdirectory = "sdk/python", branch = "dev" } diff --git a/examples/aws-python-huggingface/sst.config.ts b/examples/aws-python-huggingface/sst.config.ts deleted file mode 100644 index 14d3b52c6e..0000000000 --- a/examples/aws-python-huggingface/sst.config.ts +++ /dev/null @@ -1,43 +0,0 @@ -/// - -/** - * ## AWS Lambda Python Hugging Face - * - * Uses a Python Lambda container image to deploy a lightweight - * [Hugging Face](https://huggingface.co/) model. - * - * Uses the [transformers](https://github.com/huggingface/transformers) library to - * generate text using the - * [TinyStories-33M](https://huggingface.co/roneneldan/TinyStories-33M) model. The - * backend is the pytorch cpu runtime. - * - * :::note - * This is not a production ready example. - * ::: - * - * This example also shows how it is possible to use custom index resolution to get - * dependencies from a private pypi server such as the pytorch cpu link. This - * example also shows how to use a custom Dockerfile to handle complex builds such - * as installing pytorch and pruning the build size. - */ -export default $config({ - app(input) { - return { - name: "aws-python-huggingface", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Function("PythonFunction", { - python: { - container: true, - }, - handler: "functions/src/functions/api.handler", - runtime: "python3.12", - memory: "2048 MB", - timeout: "120 seconds", - url: true, - }); - }, -}); diff --git a/examples/aws-python-huggingface/tsconfig.json b/examples/aws-python-huggingface/tsconfig.json deleted file mode 100644 index 9e26dfeeb6..0000000000 --- a/examples/aws-python-huggingface/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/examples/aws-python/.gitignore b/examples/aws-python/.gitignore deleted file mode 100644 index 17ace783f5..0000000000 --- a/examples/aws-python/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.sst -.venv \ No newline at end of file diff --git a/examples/aws-python/core/pyproject.toml b/examples/aws-python/core/pyproject.toml deleted file mode 100644 index 4d9ed5884e..0000000000 --- a/examples/aws-python/core/pyproject.toml +++ /dev/null @@ -1,11 +0,0 @@ -[project] -name = "core" -version = "0.1.0" -description = "Add your description here" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -requires-python = "==3.11.*" -dependencies = ["requests>=2.32.3"] - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" diff --git a/examples/aws-python/core/src/core/__init__.py b/examples/aws-python/core/src/core/__init__.py deleted file mode 100644 index 437615c6c1..0000000000 --- a/examples/aws-python/core/src/core/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from core.db import get_user - - -def hello() -> str: - return "Hello from core!" - - -__all__ = ["get_user", "hello"] diff --git a/examples/aws-python/core/src/core/db.py b/examples/aws-python/core/src/core/db.py deleted file mode 100644 index c719b87ba4..0000000000 --- a/examples/aws-python/core/src/core/db.py +++ /dev/null @@ -1,5 +0,0 @@ -def get_user(user_id: str) -> dict: - return { - "user_id": user_id, - "name": "John Doe", - } diff --git a/examples/aws-python/core/src/core/ping.py b/examples/aws-python/core/src/core/ping.py deleted file mode 100644 index c13cfd5726..0000000000 --- a/examples/aws-python/core/src/core/ping.py +++ /dev/null @@ -1,5 +0,0 @@ -import requests - - -def ping(): - return requests.get("https://api.github.com").status_code diff --git a/examples/aws-python/functions/pyproject.toml b/examples/aws-python/functions/pyproject.toml deleted file mode 100644 index 2d8dfe7819..0000000000 --- a/examples/aws-python/functions/pyproject.toml +++ /dev/null @@ -1,14 +0,0 @@ -[project] -name = "functions" -version = "0.1.0" -description = "Lambda function handlers" -dependencies = ["core", "sst-sdk"] -requires-python = "==3.11.*" - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[tool.uv.sources] -core = { workspace = true } -sst-sdk = { git = "https://github.com/anomalyco/sst.git", branch = "dev", subdirectory = "sdk/python" } diff --git a/examples/aws-python/functions/src/functions/api.py b/examples/aws-python/functions/src/functions/api.py deleted file mode 100644 index dec26af61f..0000000000 --- a/examples/aws-python/functions/src/functions/api.py +++ /dev/null @@ -1,23 +0,0 @@ -from sst import Resource -from functions.shared import foo -from core.db import get_user -from core.ping import ping - -def handler(event, context): - print("Function invoked from Python") - - # Share code within the same workspace package - print(foo()) - - # Share code between workspace packages - res = ping() - print(get_user("1234")) - print("Ping result:", res) - - # Use the SST SDK to access resources - print(f"Resource.MyLinkableValue.foo: {Resource.MyLinkableValue.foo}") - - return { - "statusCode": 200, - "body": f"{Resource.MyLinkableValue.foo} from Python!", - } diff --git a/examples/aws-python/functions/src/functions/shared.py b/examples/aws-python/functions/src/functions/shared.py deleted file mode 100644 index 1f022956c6..0000000000 --- a/examples/aws-python/functions/src/functions/shared.py +++ /dev/null @@ -1,2 +0,0 @@ -def foo(): - return "bar" diff --git a/examples/aws-python/pyproject.toml b/examples/aws-python/pyproject.toml deleted file mode 100644 index 177fb56105..0000000000 --- a/examples/aws-python/pyproject.toml +++ /dev/null @@ -1,16 +0,0 @@ -[project] -name = "aws-python" -version = "0.1.0" -description = "A SST app" -authors = [{ name = "Nick Wall", email = "mail@walln.dev" }] -dependencies = [] - -# It is recommended to specify your python version to match your Lambda runtime otherwise you may -# encounter issues with dependencies. -requires-python = "==3.11.*" - -[tool.uv.workspace] -members = ["functions", "core"] - -[tool.uv.sources] -sst-sdk = { git = "https://github.com/anomalyco/sst.git", subdirectory = "sdk/python", branch = "dev" } diff --git a/examples/aws-python/sst.config.ts b/examples/aws-python/sst.config.ts deleted file mode 100644 index fc3f7c2cc0..0000000000 --- a/examples/aws-python/sst.config.ts +++ /dev/null @@ -1,102 +0,0 @@ -/// - -/** - * ## AWS Lambda Python - * - * SST uses [uv](https://docs.astral.sh/uv/) to manage your Python runtime, make - * sure you have it [installed](https://docs.astral.sh/uv/getting-started/installation/). - * - * Any [uv workspace](https://docs.astral.sh/uv/concepts/projects/workspaces/#workspace-sources) - * package can be built and deployed as a Lambda function using SST. Drop-in mode - * is currently not supported. - * - * :::note - * Each function is packaged with only the dependencies from its own `pyproject.toml` - * and any workspace packages it depends on. - * ::: - * - * In this example we deploy a handler from the `functions/` directory. It depends - * on shared code from another uv workspace in the `core/` directory. - * - * ```txt - * ├── sst.config.ts - * ├── pyproject.toml - * ├── core - * │ ├── pyproject.toml - * │ └── src - * │ └── core - * │ └── __init__.py - * └── functions - * ├── pyproject.toml - * └── src - * └── functions - * ├── __init__.py - * └── api.py - * ``` - * - * The `handler` is the path to the handler file and the name of the handler function - * in it. - * - * ```ts title="sst.config.ts" {2} - * new sst.aws.Function("PythonFunction", { - * handler: "functions/src/functions/api.handler", - * runtime: "python3.11", - * link: [linkableValue], - * url: true, - * }); - * ``` - * - * SST will traverse up from the handler path and look for the nearest - * `pyproject.toml`. And will throw an error if it can't find one. - * - * To access linked resources, you can use the SST SDK. - * - * ```py title="functions/src/functions/api.py" {1} - * from sst import Resource - * - * def handler(event, context): - * print(Resource.MyLinkableValue.foo) - * ``` - * - * Where the `sst-sdk` package can be added to your `pyproject.toml`. - * - * ```toml title="functions/pyproject.toml" - * [project] - * dependencies = ["sst-sdk"] - * - * [tool.uv.sources] - * sst-sdk = { git = "https://github.com/anomalyco/sst.git", subdirectory = "sdk/python", branch = "dev" } - * ``` - * - * You also want to set the Python version in your `pyproject.toml` to the same - * version as the one in Lambda. - * - * ```toml title="functions/pyproject.toml" - * requires-python = "==3.11.*" - * ``` - * - * This makes sure that your functions work the same in `sst dev` as `sst deploy`. - */ -export default $config({ - app(input) { - return { - name: "aws-python", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const linkableValue = new sst.Linkable("MyLinkableValue", { - properties: { - foo: "Hello World", - }, - }); - - new sst.aws.Function("PythonFunction", { - handler: "functions/src/functions/api.handler", - runtime: "python3.11", - link: [linkableValue], - url: true, - }); - }, -}); diff --git a/examples/aws-python/tsconfig.json b/examples/aws-python/tsconfig.json deleted file mode 100644 index 9e26dfeeb6..0000000000 --- a/examples/aws-python/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/examples/aws-queue/package.json b/examples/aws-queue/package.json deleted file mode 100644 index def9afd4f2..0000000000 --- a/examples/aws-queue/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-queue", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "@types/aws-lambda": "^8.10.149", - "sst": "file:../../sdk/js" - }, - "dependencies": { - "@aws-sdk/client-sqs": "^3.515.0" - } -} diff --git a/examples/aws-queue/publisher.ts b/examples/aws-queue/publisher.ts deleted file mode 100644 index 3d71dac18d..0000000000 --- a/examples/aws-queue/publisher.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from "sst"; -import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs"; -const client = new SQSClient(); - -export const handler = async (event) => { - // send a message - await client.send( - new SendMessageCommand({ - QueueUrl: Resource.MyQueue.url, - MessageBody: "Hello from the subscriber", - }) - ); - - return { - statusCode: 200, - body: JSON.stringify({ status: "sent" }, null, 2), - }; -}; diff --git a/examples/aws-queue/sst.config.ts b/examples/aws-queue/sst.config.ts deleted file mode 100644 index 8e9cb97906..0000000000 --- a/examples/aws-queue/sst.config.ts +++ /dev/null @@ -1,102 +0,0 @@ -/// - -/** - * ## Subscribe to queues - * - * Create an SQS queue, subscribe to it, and publish to it from a function. - * - * ```ts title="sst.config.ts" - * const queue = new sst.aws.Queue("MyQueue"); - * queue.subscribe("subscriber.handler"); - * - * const app = new sst.aws.Function("MyApp", { - * handler: "publisher.handler", - * link: [queue], - * url: true, - * }); - * - * return { - * app: app.url, - * queue: queue.url, - * }; - * ``` - * - * The subscriber will read messages from the queue in batches. This array of messages exists on the `Records` property of the `SQSEvent`. - * - * ```ts title="subscriber.ts" - * import type { SQSEvent, SQSHandler } from "aws-lambda"; - * - * export const handler: SQSHandler = async (event: SQSEvent) => { - * for (const record of event.Records){ - * // Message bodies are always strings - * console.log(record.body) - * } - * return; - * }; - * ``` - * - * By default, all messages in the batch become visible in the queue again if an error occurs. This can lead to unnecessary extra processing and messages being processed more than once. The solution is to enable [partial batch responsese](https://docs.aws.amazon.com/lambda/latest/dg/services-sqs-errorhandling.html#services-sqs-batchfailurereporting) and return which specific messages within the batch should be made visible again in the queue. - * - * Update the queue subscriber. - * - * ```ts title="sst.config.ts" - * queue.subscribe("subscriber.handler", { - * batch: { - * partialResponses: true, - * } - * }); - * ``` - * - * Then update the handler to return the failed items. - * - * ```ts title="subscriber.ts" - * import type { SQSEvent, SQSHandler } from "aws-lambda"; - * - * export const handler: SQSHandler = async (event: SQSEvent) => { - * const batchItemFailures = [] - * for (const record of event.Records){ - * try { - * console.log(record.body) - * if (Math.random() < 0.1){ - * throw new Error("An error occurred") - * } - * } - * catch (e) { - * batchItemFailures.push({ itemIdentifier: record.messageId }); - * } - * } - * - * // Failed items will be made visible in the queue again - * return { batchItemFailures }; - * }; - * ``` - * - */ -export default $config({ - app(input) { - return { - name: "aws-queue", - home: "aws", - removal: input.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const queue = new sst.aws.Queue("MyQueue"); - queue.subscribe("subscriber.handler", { - batch: { - partialResponses: true, - } - }); - - const app = new sst.aws.Function("MyApp", { - handler: "publisher.handler", - link: [queue], - url: true, - }); - - return { - app: app.url, - queue: queue.url, - }; - }, -}); diff --git a/examples/aws-queue/subscriber.ts b/examples/aws-queue/subscriber.ts deleted file mode 100644 index 7fbec8d5c1..0000000000 --- a/examples/aws-queue/subscriber.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { SQSEvent, SQSHandler } from "aws-lambda"; - -export const handler: SQSHandler = async (event: SQSEvent) => { - const batchItemFailures = [] - for (const record of event.Records){ - try { - console.log(record.body) - if (Math.random() < 0.1){ - throw new Error("An error occurred") - } - } - catch (e) { - batchItemFailures.push({ itemIdentifier: record.messageId }); - } - } - - // Failed items will be made visible in the queue again - return { batchItemFailures }; -}; diff --git a/examples/aws-quota-increase/package.json b/examples/aws-quota-increase/package.json deleted file mode 100644 index ddfcda6b92..0000000000 --- a/examples/aws-quota-increase/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-quota-increase", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-quota-increase/sst.config.ts b/examples/aws-quota-increase/sst.config.ts deleted file mode 100644 index 6ce0343ca3..0000000000 --- a/examples/aws-quota-increase/sst.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// - -/** - * ## AWS Quota Increase - * - * Use the Pulumi AWS provider to request an increase to an AWS service quota. - * In this example, we increase the Lambda concurrent executions quota. - * - * You can find service and quota codes in the - * [AWS Service Quotas console](https://console.aws.amazon.com/servicequotas) or by running - * `aws service-quotas list-service-quotas --service-code `. - */ -export default $config({ - app(input) { - return { - name: "aws-quota-increase", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - new aws.servicequotas.ServiceQuota("LambdaConcurrentExecutions", { - serviceCode: "lambda", - quotaCode: "L-B99A9384", - value: 2000, - }); - }, -}); diff --git a/examples/aws-rails/.dockerignore b/examples/aws-rails/.dockerignore deleted file mode 100644 index 00ce171646..0000000000 --- a/examples/aws-rails/.dockerignore +++ /dev/null @@ -1,52 +0,0 @@ -# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. - -# Ignore git directory. -/.git/ -/.gitignore - -# Ignore bundler config. -/.bundle - -# Ignore all environment files (except templates). -/.env* -!/.env*.erb - -# Ignore all default key files. -/config/master.key -/config/credentials/*.key - -# Ignore all logfiles and tempfiles. -/log/* -/tmp/* -!/log/.keep -!/tmp/.keep - -# Ignore pidfiles, but keep the directory. -/tmp/pids/* -!/tmp/pids/.keep - -# Ignore storage (uploaded files in development and any SQLite databases). -/storage/* -!/storage/.keep -/tmp/storage/* -!/tmp/storage/.keep - -# Ignore assets. -/node_modules/ -/app/assets/builds/* -!/app/assets/builds/.keep -/public/assets - -# Ignore CI service files. -/.github - -# Ignore development files -/.devcontainer - -# Ignore Docker-related files -/.dockerignore -/Dockerfile* - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-rails/.gitattributes b/examples/aws-rails/.gitattributes deleted file mode 100644 index 8dc4323435..0000000000 --- a/examples/aws-rails/.gitattributes +++ /dev/null @@ -1,9 +0,0 @@ -# See https://git-scm.com/docs/gitattributes for more about git attribute files. - -# Mark the database schema as having been generated. -db/schema.rb linguist-generated - -# Mark any vendored files as having been vendored. -vendor/* linguist-vendored -config/credentials/*.yml.enc diff=rails_credentials -config/credentials.yml.enc diff=rails_credentials diff --git a/examples/aws-rails/.github/dependabot.yml b/examples/aws-rails/.github/dependabot.yml deleted file mode 100644 index f0527e6be1..0000000000 --- a/examples/aws-rails/.github/dependabot.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: 2 -updates: -- package-ecosystem: bundler - directory: "/" - schedule: - interval: daily - open-pull-requests-limit: 10 -- package-ecosystem: github-actions - directory: "/" - schedule: - interval: daily - open-pull-requests-limit: 10 diff --git a/examples/aws-rails/.github/workflows/ci.yml b/examples/aws-rails/.github/workflows/ci.yml deleted file mode 100644 index 00af91f692..0000000000 --- a/examples/aws-rails/.github/workflows/ci.yml +++ /dev/null @@ -1,90 +0,0 @@ -name: CI - -on: - pull_request: - push: - branches: [ main ] - -jobs: - scan_ruby: - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: .ruby-version - bundler-cache: true - - - name: Scan for common Rails security vulnerabilities using static analysis - run: bin/brakeman --no-pager - - scan_js: - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: .ruby-version - bundler-cache: true - - - name: Scan for security vulnerabilities in JavaScript dependencies - run: bin/importmap audit - - lint: - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: .ruby-version - bundler-cache: true - - - name: Lint code for consistent style - run: bin/rubocop -f github - - test: - runs-on: ubuntu-latest - - # services: - # redis: - # image: redis - # ports: - # - 6379:6379 - # options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 - steps: - - name: Install packages - run: sudo apt-get update && sudo apt-get install --no-install-recommends -y google-chrome-stable curl libjemalloc2 libvips sqlite3 - - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: .ruby-version - bundler-cache: true - - - name: Run tests - env: - RAILS_ENV: test - # REDIS_URL: redis://localhost:6379/0 - run: bin/rails db:test:prepare test test:system - - - name: Keep screenshots from failed system tests - uses: actions/upload-artifact@v4 - if: failure() - with: - name: screenshots - path: ${{ github.workspace }}/tmp/screenshots - if-no-files-found: ignore diff --git a/examples/aws-rails/.gitignore b/examples/aws-rails/.gitignore deleted file mode 100644 index 4aaf1022e5..0000000000 --- a/examples/aws-rails/.gitignore +++ /dev/null @@ -1,35 +0,0 @@ -# See https://help.github.com/articles/ignoring-files for more about ignoring files. -# -# Temporary files generated by your text editor or operating system -# belong in git's global ignore instead: -# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` - -# Ignore bundler config. -/.bundle - -# Ignore all environment files (except templates). -/.env* -!/.env*.erb - -# Ignore all logfiles and tempfiles. -/log/* -/tmp/* -!/log/.keep -!/tmp/.keep - -# Ignore pidfiles, but keep the directory. -/tmp/pids/* -!/tmp/pids/ -!/tmp/pids/.keep - -# Ignore storage (uploaded files in development and any SQLite databases). -/storage/* -!/storage/.keep -/tmp/storage/* -!/tmp/storage/ -!/tmp/storage/.keep - -/public/assets - -# Ignore master key for decrypting credentials and more. -/config/master.key diff --git a/examples/aws-rails/.rubocop.yml b/examples/aws-rails/.rubocop.yml deleted file mode 100644 index f9d86d4a54..0000000000 --- a/examples/aws-rails/.rubocop.yml +++ /dev/null @@ -1,8 +0,0 @@ -# Omakase Ruby styling for Rails -inherit_gem: { rubocop-rails-omakase: rubocop.yml } - -# Overwrite or add rules to create your own house style -# -# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` -# Layout/SpaceInsideArrayLiteralBrackets: -# Enabled: false diff --git a/examples/aws-rails/.ruby-version b/examples/aws-rails/.ruby-version deleted file mode 100644 index 6d5369b963..0000000000 --- a/examples/aws-rails/.ruby-version +++ /dev/null @@ -1 +0,0 @@ -ruby-3.3.4 diff --git a/examples/aws-rails/Dockerfile b/examples/aws-rails/Dockerfile deleted file mode 100644 index 2cb400ed0c..0000000000 --- a/examples/aws-rails/Dockerfile +++ /dev/null @@ -1,69 +0,0 @@ -# syntax = docker/dockerfile:1 - -# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: -# docker build -t my-app . -# docker run -d -p 80:80 -p 443:443 --name my-app -e RAILS_MASTER_KEY= my-app - -# Make sure RUBY_VERSION matches the Ruby version in .ruby-version -ARG RUBY_VERSION=3.3.4 -FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base - -# Rails app lives here -WORKDIR /rails - -# Install base packages -RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y curl libjemalloc2 libvips sqlite3 && \ - rm -rf /var/lib/apt/lists /var/cache/apt/archives - -# Set production environment -ENV RAILS_ENV="production" \ - BUNDLE_DEPLOYMENT="1" \ - BUNDLE_PATH="/usr/local/bundle" \ - BUNDLE_WITHOUT="development" - -# Throw-away build stage to reduce size of final image -FROM base AS build - -# Install packages needed to build gems -RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y build-essential git pkg-config && \ - rm -rf /var/lib/apt/lists /var/cache/apt/archives - -# Install application gems -COPY Gemfile Gemfile.lock ./ -RUN bundle install && \ - rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ - bundle exec bootsnap precompile --gemfile - -# Copy application code -COPY . . - -# Precompile bootsnap code for faster boot times -RUN bundle exec bootsnap precompile app/ lib/ - -# Precompiling assets for production without requiring secret RAILS_MASTER_KEY -RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile - - - - -# Final stage for app image -FROM base - -# Copy built artifacts: gems, application -COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" -COPY --from=build /rails /rails - -# Run and own only the runtime files as a non-root user for security -RUN groupadd --system --gid 1000 rails && \ - useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \ - chown -R rails:rails db log storage tmp -USER 1000:1000 - -# Entrypoint prepares the database. -ENTRYPOINT ["/rails/bin/docker-entrypoint"] - -# Start the server by default, this can be overwritten at runtime -EXPOSE 3000 -CMD ["./bin/rails", "server"] diff --git a/examples/aws-rails/Gemfile b/examples/aws-rails/Gemfile deleted file mode 100644 index 6f0b5c34d8..0000000000 --- a/examples/aws-rails/Gemfile +++ /dev/null @@ -1,59 +0,0 @@ -source "https://rubygems.org" - -# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" -gem "rails", "~> 7.2.1" -# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] -gem "sprockets-rails" -# Use sqlite3 as the database for Active Record -gem "sqlite3", ">= 1.4" -# Use the Puma web server [https://github.com/puma/puma] -gem "puma", ">= 5.0" -# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] -gem "importmap-rails" -# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] -gem "turbo-rails" -# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] -gem "stimulus-rails" -# Build JSON APIs with ease [https://github.com/rails/jbuilder] -gem "jbuilder" -# Use Redis adapter to run Action Cable in production -# gem "redis", ">= 4.0.1" - -# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] -# gem "kredis" - -# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] -# gem "bcrypt", "~> 3.1.7" - -# Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem "tzinfo-data", platforms: %i[ windows jruby ] - -# Reduces boot times through caching; required in config/boot.rb -gem "bootsnap", require: false - -# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] -# gem "image_processing", "~> 1.2" - -group :development, :test do - # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem - gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" - - # Static analysis for security vulnerabilities [https://brakemanscanner.org/] - gem "brakeman", require: false - - # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] - gem "rubocop-rails-omakase", require: false -end - -group :development do - # Use console on exceptions pages [https://github.com/rails/web-console] - gem "web-console" -end - -group :test do - # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] - gem "capybara" - gem "selenium-webdriver" -end - -gem "aws-sdk-s3", "~> 1.166" diff --git a/examples/aws-rails/Gemfile.lock b/examples/aws-rails/Gemfile.lock deleted file mode 100644 index b1e77a3e8c..0000000000 --- a/examples/aws-rails/Gemfile.lock +++ /dev/null @@ -1,344 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - actioncable (7.2.1) - actionpack (= 7.2.1) - activesupport (= 7.2.1) - nio4r (~> 2.0) - websocket-driver (>= 0.6.1) - zeitwerk (~> 2.6) - actionmailbox (7.2.1) - actionpack (= 7.2.1) - activejob (= 7.2.1) - activerecord (= 7.2.1) - activestorage (= 7.2.1) - activesupport (= 7.2.1) - mail (>= 2.8.0) - actionmailer (7.2.1) - actionpack (= 7.2.1) - actionview (= 7.2.1) - activejob (= 7.2.1) - activesupport (= 7.2.1) - mail (>= 2.8.0) - rails-dom-testing (~> 2.2) - actionpack (7.2.1) - actionview (= 7.2.1) - activesupport (= 7.2.1) - nokogiri (>= 1.8.5) - racc - rack (>= 2.2.4, < 3.2) - rack-session (>= 1.0.1) - rack-test (>= 0.6.3) - rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) - useragent (~> 0.16) - actiontext (7.2.1) - actionpack (= 7.2.1) - activerecord (= 7.2.1) - activestorage (= 7.2.1) - activesupport (= 7.2.1) - globalid (>= 0.6.0) - nokogiri (>= 1.8.5) - actionview (7.2.1) - activesupport (= 7.2.1) - builder (~> 3.1) - erubi (~> 1.11) - rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) - activejob (7.2.1) - activesupport (= 7.2.1) - globalid (>= 0.3.6) - activemodel (7.2.1) - activesupport (= 7.2.1) - activerecord (7.2.1) - activemodel (= 7.2.1) - activesupport (= 7.2.1) - timeout (>= 0.4.0) - activestorage (7.2.1) - actionpack (= 7.2.1) - activejob (= 7.2.1) - activerecord (= 7.2.1) - activesupport (= 7.2.1) - marcel (~> 1.0) - activesupport (7.2.1) - base64 - bigdecimal - concurrent-ruby (~> 1.0, >= 1.3.1) - connection_pool (>= 2.2.5) - drb - i18n (>= 1.6, < 2) - logger (>= 1.4.2) - minitest (>= 5.1) - securerandom (>= 0.3) - tzinfo (~> 2.0, >= 2.0.5) - addressable (2.8.7) - public_suffix (>= 2.0.2, < 7.0) - ast (2.4.2) - aws-eventstream (1.3.0) - aws-partitions (1.978.0) - aws-sdk-core (3.209.0) - aws-eventstream (~> 1, >= 1.3.0) - aws-partitions (~> 1, >= 1.651.0) - aws-sigv4 (~> 1.9) - jmespath (~> 1, >= 1.6.1) - aws-sdk-kms (1.94.0) - aws-sdk-core (~> 3, >= 3.207.0) - aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.166.0) - aws-sdk-core (~> 3, >= 3.207.0) - aws-sdk-kms (~> 1) - aws-sigv4 (~> 1.5) - aws-sigv4 (1.10.0) - aws-eventstream (~> 1, >= 1.0.2) - base64 (0.2.0) - bigdecimal (3.1.8) - bindex (0.8.1) - bootsnap (1.18.4) - msgpack (~> 1.2) - brakeman (6.2.1) - racc - builder (3.3.0) - capybara (3.40.0) - addressable - matrix - mini_mime (>= 0.1.3) - nokogiri (~> 1.11) - rack (>= 1.6.0) - rack-test (>= 0.6.3) - regexp_parser (>= 1.5, < 3.0) - xpath (~> 3.2) - concurrent-ruby (1.3.4) - connection_pool (2.4.1) - crass (1.0.6) - date (3.3.4) - debug (1.9.2) - irb (~> 1.10) - reline (>= 0.3.8) - drb (2.2.1) - erubi (1.13.0) - globalid (1.2.1) - activesupport (>= 6.1) - i18n (1.14.6) - concurrent-ruby (~> 1.0) - importmap-rails (2.0.1) - actionpack (>= 6.0.0) - activesupport (>= 6.0.0) - railties (>= 6.0.0) - io-console (0.7.2) - irb (1.14.0) - rdoc (>= 4.0.0) - reline (>= 0.4.2) - jbuilder (2.13.0) - actionview (>= 5.0.0) - activesupport (>= 5.0.0) - jmespath (1.6.2) - json (2.7.2) - language_server-protocol (3.17.0.3) - logger (1.6.1) - loofah (2.22.0) - crass (~> 1.0.2) - nokogiri (>= 1.12.0) - mail (2.8.1) - mini_mime (>= 0.1.1) - net-imap - net-pop - net-smtp - marcel (1.0.4) - matrix (0.4.2) - mini_mime (1.1.5) - minitest (5.25.1) - msgpack (1.7.2) - net-imap (0.4.16) - date - net-protocol - net-pop (0.1.2) - net-protocol - net-protocol (0.2.2) - timeout - net-smtp (0.5.0) - net-protocol - nio4r (2.7.3) - nokogiri (1.16.7-aarch64-linux) - racc (~> 1.4) - nokogiri (1.16.7-arm-linux) - racc (~> 1.4) - nokogiri (1.16.7-arm64-darwin) - racc (~> 1.4) - nokogiri (1.16.7-x86-linux) - racc (~> 1.4) - nokogiri (1.16.7-x86_64-darwin) - racc (~> 1.4) - nokogiri (1.16.7-x86_64-linux) - racc (~> 1.4) - parallel (1.26.3) - parser (3.3.5.0) - ast (~> 2.4.1) - racc - psych (5.1.2) - stringio - public_suffix (6.0.1) - puma (6.4.3) - nio4r (~> 2.0) - racc (1.8.1) - rack (3.1.7) - rack-session (2.0.0) - rack (>= 3.0.0) - rack-test (2.1.0) - rack (>= 1.3) - rackup (2.1.0) - rack (>= 3) - webrick (~> 1.8) - rails (7.2.1) - actioncable (= 7.2.1) - actionmailbox (= 7.2.1) - actionmailer (= 7.2.1) - actionpack (= 7.2.1) - actiontext (= 7.2.1) - actionview (= 7.2.1) - activejob (= 7.2.1) - activemodel (= 7.2.1) - activerecord (= 7.2.1) - activestorage (= 7.2.1) - activesupport (= 7.2.1) - bundler (>= 1.15.0) - railties (= 7.2.1) - rails-dom-testing (2.2.0) - activesupport (>= 5.0.0) - minitest - nokogiri (>= 1.6) - rails-html-sanitizer (1.6.0) - loofah (~> 2.21) - nokogiri (~> 1.14) - railties (7.2.1) - actionpack (= 7.2.1) - activesupport (= 7.2.1) - irb (~> 1.13) - rackup (>= 1.0.0) - rake (>= 12.2) - thor (~> 1.0, >= 1.2.2) - zeitwerk (~> 2.6) - rainbow (3.1.1) - rake (13.2.1) - rdoc (6.7.0) - psych (>= 4.0.0) - regexp_parser (2.9.2) - reline (0.5.10) - io-console (~> 0.5) - rexml (3.3.7) - rubocop (1.66.1) - json (~> 2.3) - language_server-protocol (>= 3.17.0) - parallel (~> 1.10) - parser (>= 3.3.0.2) - rainbow (>= 2.2.2, < 4.0) - regexp_parser (>= 2.4, < 3.0) - rubocop-ast (>= 1.32.2, < 2.0) - ruby-progressbar (~> 1.7) - unicode-display_width (>= 2.4.0, < 3.0) - rubocop-ast (1.32.3) - parser (>= 3.3.1.0) - rubocop-minitest (0.36.0) - rubocop (>= 1.61, < 2.0) - rubocop-ast (>= 1.31.1, < 2.0) - rubocop-performance (1.22.1) - rubocop (>= 1.48.1, < 2.0) - rubocop-ast (>= 1.31.1, < 2.0) - rubocop-rails (2.26.2) - activesupport (>= 4.2.0) - rack (>= 1.1) - rubocop (>= 1.52.0, < 2.0) - rubocop-ast (>= 1.31.1, < 2.0) - rubocop-rails-omakase (1.0.0) - rubocop - rubocop-minitest - rubocop-performance - rubocop-rails - ruby-progressbar (1.13.0) - rubyzip (2.3.2) - securerandom (0.3.1) - selenium-webdriver (4.25.0) - base64 (~> 0.2) - logger (~> 1.4) - rexml (~> 3.2, >= 3.2.5) - rubyzip (>= 1.2.2, < 3.0) - websocket (~> 1.0) - sprockets (4.2.1) - concurrent-ruby (~> 1.0) - rack (>= 2.2.4, < 4) - sprockets-rails (3.5.2) - actionpack (>= 6.1) - activesupport (>= 6.1) - sprockets (>= 3.0.0) - sqlite3 (2.0.4-aarch64-linux-gnu) - sqlite3 (2.0.4-aarch64-linux-musl) - sqlite3 (2.0.4-arm-linux-gnu) - sqlite3 (2.0.4-arm-linux-musl) - sqlite3 (2.0.4-arm64-darwin) - sqlite3 (2.0.4-x86-linux-gnu) - sqlite3 (2.0.4-x86-linux-musl) - sqlite3 (2.0.4-x86_64-darwin) - sqlite3 (2.0.4-x86_64-linux-gnu) - sqlite3 (2.0.4-x86_64-linux-musl) - stimulus-rails (1.3.4) - railties (>= 6.0.0) - stringio (3.1.1) - thor (1.3.2) - timeout (0.4.1) - turbo-rails (2.0.10) - actionpack (>= 6.0.0) - railties (>= 6.0.0) - tzinfo (2.0.6) - concurrent-ruby (~> 1.0) - unicode-display_width (2.6.0) - useragent (0.16.10) - web-console (4.2.1) - actionview (>= 6.0.0) - activemodel (>= 6.0.0) - bindex (>= 0.4.0) - railties (>= 6.0.0) - webrick (1.8.2) - websocket (1.2.11) - websocket-driver (0.7.6) - websocket-extensions (>= 0.1.0) - websocket-extensions (0.1.5) - xpath (3.2.0) - nokogiri (~> 1.8) - zeitwerk (2.6.18) - -PLATFORMS - aarch64-linux - aarch64-linux-gnu - aarch64-linux-musl - arm-linux - arm-linux-gnu - arm-linux-musl - arm64-darwin - x86-linux - x86-linux-gnu - x86-linux-musl - x86_64-darwin - x86_64-linux - x86_64-linux-gnu - x86_64-linux-musl - -DEPENDENCIES - aws-sdk-s3 (~> 1.166) - bootsnap - brakeman - capybara - debug - importmap-rails - jbuilder - puma (>= 5.0) - rails (~> 7.2.1) - rubocop-rails-omakase - selenium-webdriver - sprockets-rails - sqlite3 (>= 1.4) - stimulus-rails - turbo-rails - tzinfo-data - web-console - -BUNDLED WITH - 2.5.11 diff --git a/examples/aws-rails/Rakefile b/examples/aws-rails/Rakefile deleted file mode 100644 index 9a5ea7383a..0000000000 --- a/examples/aws-rails/Rakefile +++ /dev/null @@ -1,6 +0,0 @@ -# Add your own tasks in files placed in lib/tasks ending in .rake, -# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. - -require_relative "config/application" - -Rails.application.load_tasks diff --git a/examples/aws-rails/app/assets/config/manifest.js b/examples/aws-rails/app/assets/config/manifest.js deleted file mode 100644 index ddd546a0be..0000000000 --- a/examples/aws-rails/app/assets/config/manifest.js +++ /dev/null @@ -1,4 +0,0 @@ -//= link_tree ../images -//= link_directory ../stylesheets .css -//= link_tree ../../javascript .js -//= link_tree ../../../vendor/javascript .js diff --git a/examples/aws-rails/app/assets/stylesheets/application.css b/examples/aws-rails/app/assets/stylesheets/application.css deleted file mode 100644 index 288b9ab718..0000000000 --- a/examples/aws-rails/app/assets/stylesheets/application.css +++ /dev/null @@ -1,15 +0,0 @@ -/* - * This is a manifest file that'll be compiled into application.css, which will include all the files - * listed below. - * - * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's - * vendor/assets/stylesheets directory can be referenced here using a relative path. - * - * You're free to add application-wide styles to this file and they'll appear at the bottom of the - * compiled file so the styles you add here take precedence over styles defined in any other CSS - * files in this directory. Styles in this file should be added after the last require_* statement. - * It is generally better to create a new file per style scope. - * - *= require_tree . - *= require_self - */ diff --git a/examples/aws-rails/app/channels/application_cable/channel.rb b/examples/aws-rails/app/channels/application_cable/channel.rb deleted file mode 100644 index d672697283..0000000000 --- a/examples/aws-rails/app/channels/application_cable/channel.rb +++ /dev/null @@ -1,4 +0,0 @@ -module ApplicationCable - class Channel < ActionCable::Channel::Base - end -end diff --git a/examples/aws-rails/app/channels/application_cable/connection.rb b/examples/aws-rails/app/channels/application_cable/connection.rb deleted file mode 100644 index 0ff5442f47..0000000000 --- a/examples/aws-rails/app/channels/application_cable/connection.rb +++ /dev/null @@ -1,4 +0,0 @@ -module ApplicationCable - class Connection < ActionCable::Connection::Base - end -end diff --git a/examples/aws-rails/app/controllers/application_controller.rb b/examples/aws-rails/app/controllers/application_controller.rb deleted file mode 100644 index 0d95db22b4..0000000000 --- a/examples/aws-rails/app/controllers/application_controller.rb +++ /dev/null @@ -1,4 +0,0 @@ -class ApplicationController < ActionController::Base - # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. - allow_browser versions: :modern -end diff --git a/examples/aws-rails/app/controllers/concerns/.keep b/examples/aws-rails/app/controllers/concerns/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/app/controllers/uploads_controller.rb b/examples/aws-rails/app/controllers/uploads_controller.rb deleted file mode 100644 index ed99b774d6..0000000000 --- a/examples/aws-rails/app/controllers/uploads_controller.rb +++ /dev/null @@ -1,16 +0,0 @@ -class UploadsController < ApplicationController - skip_before_action :verify_authenticity_token - - def new - end - - def create - blob = ActiveStorage::Blob.create_and_upload!( - io: params[:file].tempfile, - filename: params[:file].original_filename, - content_type: params[:file].content_type - ) - url = "https://#{ActiveStorage::Blob.service.bucket.name}.s3.amazonaws.com/#{blob.key}" - redirect_to root_path(uploaded_url: url) - end -end diff --git a/examples/aws-rails/app/helpers/application_helper.rb b/examples/aws-rails/app/helpers/application_helper.rb deleted file mode 100644 index de6be7945c..0000000000 --- a/examples/aws-rails/app/helpers/application_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module ApplicationHelper -end diff --git a/examples/aws-rails/app/helpers/uploads_helper.rb b/examples/aws-rails/app/helpers/uploads_helper.rb deleted file mode 100644 index f4f8250f5e..0000000000 --- a/examples/aws-rails/app/helpers/uploads_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module UploadsHelper -end diff --git a/examples/aws-rails/app/javascript/application.js b/examples/aws-rails/app/javascript/application.js deleted file mode 100644 index 0d7b49404c..0000000000 --- a/examples/aws-rails/app/javascript/application.js +++ /dev/null @@ -1,3 +0,0 @@ -// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails -import "@hotwired/turbo-rails" -import "controllers" diff --git a/examples/aws-rails/app/javascript/controllers/application.js b/examples/aws-rails/app/javascript/controllers/application.js deleted file mode 100644 index 1213e85c7a..0000000000 --- a/examples/aws-rails/app/javascript/controllers/application.js +++ /dev/null @@ -1,9 +0,0 @@ -import { Application } from "@hotwired/stimulus" - -const application = Application.start() - -// Configure Stimulus development experience -application.debug = false -window.Stimulus = application - -export { application } diff --git a/examples/aws-rails/app/javascript/controllers/hello_controller.js b/examples/aws-rails/app/javascript/controllers/hello_controller.js deleted file mode 100644 index 5975c0789d..0000000000 --- a/examples/aws-rails/app/javascript/controllers/hello_controller.js +++ /dev/null @@ -1,7 +0,0 @@ -import { Controller } from "@hotwired/stimulus" - -export default class extends Controller { - connect() { - this.element.textContent = "Hello World!" - } -} diff --git a/examples/aws-rails/app/javascript/controllers/index.js b/examples/aws-rails/app/javascript/controllers/index.js deleted file mode 100644 index 1156bf8362..0000000000 --- a/examples/aws-rails/app/javascript/controllers/index.js +++ /dev/null @@ -1,4 +0,0 @@ -// Import and register all your controllers from the importmap via controllers/**/*_controller -import { application } from "controllers/application" -import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" -eagerLoadControllersFrom("controllers", application) diff --git a/examples/aws-rails/app/jobs/application_job.rb b/examples/aws-rails/app/jobs/application_job.rb deleted file mode 100644 index d394c3d106..0000000000 --- a/examples/aws-rails/app/jobs/application_job.rb +++ /dev/null @@ -1,7 +0,0 @@ -class ApplicationJob < ActiveJob::Base - # Automatically retry jobs that encountered a deadlock - # retry_on ActiveRecord::Deadlocked - - # Most jobs are safe to ignore if the underlying records are no longer available - # discard_on ActiveJob::DeserializationError -end diff --git a/examples/aws-rails/app/mailers/application_mailer.rb b/examples/aws-rails/app/mailers/application_mailer.rb deleted file mode 100644 index 3c34c8148f..0000000000 --- a/examples/aws-rails/app/mailers/application_mailer.rb +++ /dev/null @@ -1,4 +0,0 @@ -class ApplicationMailer < ActionMailer::Base - default from: "from@example.com" - layout "mailer" -end diff --git a/examples/aws-rails/app/models/application_record.rb b/examples/aws-rails/app/models/application_record.rb deleted file mode 100644 index b63caeb8a5..0000000000 --- a/examples/aws-rails/app/models/application_record.rb +++ /dev/null @@ -1,3 +0,0 @@ -class ApplicationRecord < ActiveRecord::Base - primary_abstract_class -end diff --git a/examples/aws-rails/app/models/concerns/.keep b/examples/aws-rails/app/models/concerns/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/app/views/layouts/application.html.erb b/examples/aws-rails/app/views/layouts/application.html.erb deleted file mode 100644 index bcf1d45a7d..0000000000 --- a/examples/aws-rails/app/views/layouts/application.html.erb +++ /dev/null @@ -1,23 +0,0 @@ - - - - <%= content_for(:title) || "Aws Rails" %> - - - <%= csrf_meta_tags %> - <%= csp_meta_tag %> - - <%= yield :head %> - - - - - - <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> - <%= javascript_importmap_tags %> - - - - <%= yield %> - - diff --git a/examples/aws-rails/app/views/layouts/mailer.html.erb b/examples/aws-rails/app/views/layouts/mailer.html.erb deleted file mode 100644 index 3aac9002ed..0000000000 --- a/examples/aws-rails/app/views/layouts/mailer.html.erb +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - <%= yield %> - - diff --git a/examples/aws-rails/app/views/layouts/mailer.text.erb b/examples/aws-rails/app/views/layouts/mailer.text.erb deleted file mode 100644 index 37f0bddbd7..0000000000 --- a/examples/aws-rails/app/views/layouts/mailer.text.erb +++ /dev/null @@ -1 +0,0 @@ -<%= yield %> diff --git a/examples/aws-rails/app/views/pwa/manifest.json.erb b/examples/aws-rails/app/views/pwa/manifest.json.erb deleted file mode 100644 index 107dff4398..0000000000 --- a/examples/aws-rails/app/views/pwa/manifest.json.erb +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "AwsRails", - "icons": [ - { - "src": "/icon.png", - "type": "image/png", - "sizes": "512x512" - }, - { - "src": "/icon.png", - "type": "image/png", - "sizes": "512x512", - "purpose": "maskable" - } - ], - "start_url": "/", - "display": "standalone", - "scope": "/", - "description": "AwsRails.", - "theme_color": "red", - "background_color": "red" -} diff --git a/examples/aws-rails/app/views/pwa/service-worker.js b/examples/aws-rails/app/views/pwa/service-worker.js deleted file mode 100644 index b3a13fb7bb..0000000000 --- a/examples/aws-rails/app/views/pwa/service-worker.js +++ /dev/null @@ -1,26 +0,0 @@ -// Add a service worker for processing Web Push notifications: -// -// self.addEventListener("push", async (event) => { -// const { title, options } = await event.data.json() -// event.waitUntil(self.registration.showNotification(title, options)) -// }) -// -// self.addEventListener("notificationclick", function(event) { -// event.notification.close() -// event.waitUntil( -// clients.matchAll({ type: "window" }).then((clientList) => { -// for (let i = 0; i < clientList.length; i++) { -// let client = clientList[i] -// let clientPath = (new URL(client.url)).pathname -// -// if (clientPath == event.notification.data.path && "focus" in client) { -// return client.focus() -// } -// } -// -// if (clients.openWindow) { -// return clients.openWindow(event.notification.data.path) -// } -// }) -// ) -// }) diff --git a/examples/aws-rails/app/views/uploads/create.html.erb b/examples/aws-rails/app/views/uploads/create.html.erb deleted file mode 100644 index 40f4a011c9..0000000000 --- a/examples/aws-rails/app/views/uploads/create.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Uploads#create

-

Find me in app/views/uploads/create.html.erb

diff --git a/examples/aws-rails/app/views/uploads/new.html.erb b/examples/aws-rails/app/views/uploads/new.html.erb deleted file mode 100644 index ff92b3994d..0000000000 --- a/examples/aws-rails/app/views/uploads/new.html.erb +++ /dev/null @@ -1,15 +0,0 @@ -

Upload an Image

- -<%= form_with(url: upload_path, local: true, multipart: true) do |form| %> -
- <%= form.label :file %> - <%= form.file_field :file %> -
- - <%= form.submit 'Upload Image' %> -<% end %> - -<% if params[:uploaded_url].present? %> -

Your file has been uploaded! You can access it here:

- <%= link_to params[:uploaded_url], params[:uploaded_url], target: '_blank' %> -<% end %> \ No newline at end of file diff --git a/examples/aws-rails/bin/brakeman b/examples/aws-rails/bin/brakeman deleted file mode 100755 index ace1c9ba08..0000000000 --- a/examples/aws-rails/bin/brakeman +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby -require "rubygems" -require "bundler/setup" - -ARGV.unshift("--ensure-latest") - -load Gem.bin_path("brakeman", "brakeman") diff --git a/examples/aws-rails/bin/bundle b/examples/aws-rails/bin/bundle deleted file mode 100755 index 50da5fdf9e..0000000000 --- a/examples/aws-rails/bin/bundle +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# -# This file was generated by Bundler. -# -# The application 'bundle' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require "rubygems" - -m = Module.new do - module_function - - def invoked_as_script? - File.expand_path($0) == File.expand_path(__FILE__) - end - - def env_var_version - ENV["BUNDLER_VERSION"] - end - - def cli_arg_version - return unless invoked_as_script? # don't want to hijack other binstubs - return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` - bundler_version = nil - update_index = nil - ARGV.each_with_index do |a, i| - if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) - bundler_version = a - end - next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ - bundler_version = $1 - update_index = i - end - bundler_version - end - - def gemfile - gemfile = ENV["BUNDLE_GEMFILE"] - return gemfile if gemfile && !gemfile.empty? - - File.expand_path("../Gemfile", __dir__) - end - - def lockfile - lockfile = - case File.basename(gemfile) - when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") - else "#{gemfile}.lock" - end - File.expand_path(lockfile) - end - - def lockfile_version - return unless File.file?(lockfile) - lockfile_contents = File.read(lockfile) - return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ - Regexp.last_match(1) - end - - def bundler_requirement - @bundler_requirement ||= - env_var_version || - cli_arg_version || - bundler_requirement_for(lockfile_version) - end - - def bundler_requirement_for(version) - return "#{Gem::Requirement.default}.a" unless version - - bundler_gem_version = Gem::Version.new(version) - - bundler_gem_version.approximate_recommendation - end - - def load_bundler! - ENV["BUNDLE_GEMFILE"] ||= gemfile - - activate_bundler - end - - def activate_bundler - gem_error = activation_error_handling do - gem "bundler", bundler_requirement - end - return if gem_error.nil? - require_error = activation_error_handling do - require "bundler/version" - end - return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) - warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" - exit 42 - end - - def activation_error_handling - yield - nil - rescue StandardError, LoadError => e - e - end -end - -m.load_bundler! - -if m.invoked_as_script? - load Gem.bin_path("bundler", "bundle") -end diff --git a/examples/aws-rails/bin/docker-entrypoint b/examples/aws-rails/bin/docker-entrypoint deleted file mode 100755 index 840d093a9a..0000000000 --- a/examples/aws-rails/bin/docker-entrypoint +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -e - -# Enable jemalloc for reduced memory usage and latency. -if [ -z "${LD_PRELOAD+x}" ] && [ -f /usr/lib/*/libjemalloc.so.2 ]; then - export LD_PRELOAD="$(echo /usr/lib/*/libjemalloc.so.2)" -fi - -# If running the rails server then create or migrate existing database -if [ "${1}" == "./bin/rails" ] && [ "${2}" == "server" ]; then - ./bin/rails db:prepare -fi - -exec "${@}" diff --git a/examples/aws-rails/bin/importmap b/examples/aws-rails/bin/importmap deleted file mode 100755 index 36502ab16c..0000000000 --- a/examples/aws-rails/bin/importmap +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby - -require_relative "../config/application" -require "importmap/commands" diff --git a/examples/aws-rails/bin/rails b/examples/aws-rails/bin/rails deleted file mode 100755 index efc0377492..0000000000 --- a/examples/aws-rails/bin/rails +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby -APP_PATH = File.expand_path("../config/application", __dir__) -require_relative "../config/boot" -require "rails/commands" diff --git a/examples/aws-rails/bin/rake b/examples/aws-rails/bin/rake deleted file mode 100755 index 4fbf10b960..0000000000 --- a/examples/aws-rails/bin/rake +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby -require_relative "../config/boot" -require "rake" -Rake.application.run diff --git a/examples/aws-rails/bin/rubocop b/examples/aws-rails/bin/rubocop deleted file mode 100755 index 40330c0ff1..0000000000 --- a/examples/aws-rails/bin/rubocop +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env ruby -require "rubygems" -require "bundler/setup" - -# explicit rubocop config increases performance slightly while avoiding config confusion. -ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) - -load Gem.bin_path("rubocop", "rubocop") diff --git a/examples/aws-rails/bin/setup b/examples/aws-rails/bin/setup deleted file mode 100755 index ee2b54d365..0000000000 --- a/examples/aws-rails/bin/setup +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env ruby -require "fileutils" - -APP_ROOT = File.expand_path("..", __dir__) -APP_NAME = "aws-rails" - -def system!(*args) - system(*args, exception: true) -end - -FileUtils.chdir APP_ROOT do - # This script is a way to set up or update your development environment automatically. - # This script is idempotent, so that you can run it at any time and get an expectable outcome. - # Add necessary setup steps to this file. - - puts "== Installing dependencies ==" - system! "gem install bundler --conservative" - system("bundle check") || system!("bundle install") - - # puts "\n== Copying sample files ==" - # unless File.exist?("config/database.yml") - # FileUtils.cp "config/database.yml.sample", "config/database.yml" - # end - - puts "\n== Preparing database ==" - system! "bin/rails db:prepare" - - puts "\n== Removing old logs and tempfiles ==" - system! "bin/rails log:clear tmp:clear" - - puts "\n== Restarting application server ==" - system! "bin/rails restart" - - # puts "\n== Configuring puma-dev ==" - # system "ln -nfs #{APP_ROOT} ~/.puma-dev/#{APP_NAME}" - # system "curl -Is https://#{APP_NAME}.test/up | head -n 1" -end diff --git a/examples/aws-rails/config.ru b/examples/aws-rails/config.ru deleted file mode 100644 index 4a3c09a688..0000000000 --- a/examples/aws-rails/config.ru +++ /dev/null @@ -1,6 +0,0 @@ -# This file is used by Rack-based servers to start the application. - -require_relative "config/environment" - -run Rails.application -Rails.application.load_server diff --git a/examples/aws-rails/config/application.rb b/examples/aws-rails/config/application.rb deleted file mode 100644 index 2cfa3ae1b8..0000000000 --- a/examples/aws-rails/config/application.rb +++ /dev/null @@ -1,27 +0,0 @@ -require_relative "boot" - -require "rails/all" - -# Require the gems listed in Gemfile, including any gems -# you've limited to :test, :development, or :production. -Bundler.require(*Rails.groups) - -module AwsRails - class Application < Rails::Application - # Initialize configuration defaults for originally generated Rails version. - config.load_defaults 7.2 - - # Please, add to the `ignore` list any other `lib` subdirectories that do - # not contain `.rb` files, or that should not be reloaded or eager loaded. - # Common ones are `templates`, `generators`, or `middleware`, for example. - config.autoload_lib(ignore: %w[assets tasks]) - - # Configuration for the application, engines, and railties goes here. - # - # These settings can be overridden in specific environments using the files - # in config/environments, which are processed later. - # - # config.time_zone = "Central Time (US & Canada)" - # config.eager_load_paths << Rails.root.join("extras") - end -end diff --git a/examples/aws-rails/config/boot.rb b/examples/aws-rails/config/boot.rb deleted file mode 100644 index 988a5ddc46..0000000000 --- a/examples/aws-rails/config/boot.rb +++ /dev/null @@ -1,4 +0,0 @@ -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) - -require "bundler/setup" # Set up gems listed in the Gemfile. -require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/examples/aws-rails/config/cable.yml b/examples/aws-rails/config/cable.yml deleted file mode 100644 index 054e1be48a..0000000000 --- a/examples/aws-rails/config/cable.yml +++ /dev/null @@ -1,10 +0,0 @@ -development: - adapter: async - -test: - adapter: test - -production: - adapter: redis - url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> - channel_prefix: aws_rails_production diff --git a/examples/aws-rails/config/credentials.yml.enc b/examples/aws-rails/config/credentials.yml.enc deleted file mode 100644 index d4211c0f89..0000000000 --- a/examples/aws-rails/config/credentials.yml.enc +++ /dev/null @@ -1 +0,0 @@ -vEY6y3HLNkBS+aarod5P3ix27Cd3nK+QXtCvgMCUsEh1EmWcwsCRYJk/hBzwZyKtjHjTIUTJ7oeF2NkzKbYeAPOTBazpjAg7GC5oVAy1GLYVTZM+h0c58AWMLCjww8v1/i4Ju4AgcigPyNSlary4KnCjJO6HGsBXGHCH9FxHIasacQYz6ZvblHWQ1qEshmdfY3OWStRjyNCJS3a6KzTrFDwpMwP1s6ZyJxGCUj4ldqTI8s/EUyWdRcNg+CRyaXA/ElwgF78uvQe8RSHtC0ited59VtgaUIXRyKnrJ3Tz1kNYFICmERrny5rrOUFpnEbaujGdPj4xLhiMGQtuafzW1c32dZgFehchE7fIuR2jP+nDpIbglJ3z5MXnLNPanIkai4Xq6X2UVlZwCXhFUOE2cEc3eVUm--KhoSxVW3jXtFnuv8--AoRt1fW/zNvGsMnm7tOOZQ== \ No newline at end of file diff --git a/examples/aws-rails/config/database.yml b/examples/aws-rails/config/database.yml deleted file mode 100644 index c480dcb827..0000000000 --- a/examples/aws-rails/config/database.yml +++ /dev/null @@ -1,31 +0,0 @@ -# SQLite. Versions 3.8.0 and up are supported. -# gem install sqlite3 -# -# Ensure the SQLite 3 gem is defined in your Gemfile -# gem "sqlite3" -# -default: &default - adapter: sqlite3 - pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - timeout: 5000 - -development: - <<: *default - database: storage/development.sqlite3 - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: storage/test.sqlite3 - -# SQLite3 write its data on the local filesystem, as such it requires -# persistent disks. If you are deploying to a managed service, you should -# make sure it provides disk persistence, as many don't. -# -# Similarly, if you deploy your application as a Docker container, you must -# ensure the database is located in a persisted volume. -production: - <<: *default - database: /tmp/production.sqlite3 diff --git a/examples/aws-rails/config/environment.rb b/examples/aws-rails/config/environment.rb deleted file mode 100644 index cac5315775..0000000000 --- a/examples/aws-rails/config/environment.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Load the Rails application. -require_relative "application" - -# Initialize the Rails application. -Rails.application.initialize! diff --git a/examples/aws-rails/config/environments/development.rb b/examples/aws-rails/config/environments/development.rb deleted file mode 100644 index fc5d7282e3..0000000000 --- a/examples/aws-rails/config/environments/development.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "active_support/core_ext/integer/time" - -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # In the development environment your application's code is reloaded any time - # it changes. This slows down response time but is perfect for development - # since you don't have to restart the web server when you make code changes. - config.enable_reloading = true - - # Do not eager load code on boot. - config.eager_load = false - - # Show full error reports. - config.consider_all_requests_local = true - - # Enable server timing. - config.server_timing = true - - # Enable/disable caching. By default caching is disabled. - # Run rails dev:cache to toggle caching. - if Rails.root.join("tmp/caching-dev.txt").exist? - config.action_controller.perform_caching = true - config.action_controller.enable_fragment_cache_logging = true - - config.cache_store = :memory_store - config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } - else - config.action_controller.perform_caching = false - - config.cache_store = :null_store - end - - # Store uploaded files on the local file system (see config/storage.yml for options). - config.active_storage.service = :amazon - - # Don't care if the mailer can't send. - config.action_mailer.raise_delivery_errors = false - - # Disable caching for Action Mailer templates even if Action Controller - # caching is enabled. - config.action_mailer.perform_caching = false - - config.action_mailer.default_url_options = { host: "localhost", port: 3000 } - - # Print deprecation notices to the Rails logger. - config.active_support.deprecation = :log - - # Raise exceptions for disallowed deprecations. - config.active_support.disallowed_deprecation = :raise - - # Tell Active Support which deprecation messages to disallow. - config.active_support.disallowed_deprecation_warnings = [] - - # Raise an error on page load if there are pending migrations. - config.active_record.migration_error = :page_load - - # Highlight code that triggered database queries in logs. - config.active_record.verbose_query_logs = true - - # Highlight code that enqueued background job in logs. - config.active_job.verbose_enqueue_logs = true - - # Suppress logger output for asset requests. - config.assets.quiet = true - - # Raises error for missing translations. - # config.i18n.raise_on_missing_translations = true - - # Annotate rendered view with file names. - config.action_view.annotate_rendered_view_with_filenames = true - - # Uncomment if you wish to allow Action Cable access from any origin. - # config.action_cable.disable_request_forgery_protection = true - - # Raise error when a before_action's only/except options reference missing actions. - config.action_controller.raise_on_missing_callback_actions = true - - # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. - # config.generators.apply_rubocop_autocorrect_after_generate! -end diff --git a/examples/aws-rails/config/environments/production.rb b/examples/aws-rails/config/environments/production.rb deleted file mode 100644 index ff26add9ba..0000000000 --- a/examples/aws-rails/config/environments/production.rb +++ /dev/null @@ -1,102 +0,0 @@ -require "active_support/core_ext/integer/time" - -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # Code is not reloaded between requests. - config.enable_reloading = false - - # Eager load code on boot. This eager loads most of Rails and - # your application in memory, allowing both threaded web servers - # and those relying on copy on write to perform better. - # Rake tasks automatically ignore this option for performance. - config.eager_load = true - - # Full error reports are disabled and caching is turned on. - config.consider_all_requests_local = false - config.action_controller.perform_caching = true - - # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment - # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). - # config.require_master_key = true - - # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. - # config.public_file_server.enabled = false - - # Compress CSS using a preprocessor. - # config.assets.css_compressor = :sass - - # Do not fall back to assets pipeline if a precompiled asset is missed. - config.assets.compile = false - - # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.asset_host = "http://assets.example.com" - - # Specifies the header that your server uses for sending files. - # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache - # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX - - # Store uploaded files on the local file system (see config/storage.yml for options). - config.active_storage.service = :amazon - - # Mount Action Cable outside main process or domain. - # config.action_cable.mount_path = nil - # config.action_cable.url = "wss://example.com/cable" - # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] - - # Assume all access to the app is happening through a SSL-terminating reverse proxy. - # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. - # config.assume_ssl = true - - # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. - # config.force_ssl = true - - # Skip http-to-https redirect for the default health check endpoint. - # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } - - # Log to STDOUT by default - config.logger = ActiveSupport::Logger.new(STDOUT) - .tap { |logger| logger.formatter = ::Logger::Formatter.new } - .then { |logger| ActiveSupport::TaggedLogging.new(logger) } - - # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] - - # "info" includes generic and useful information about system operation, but avoids logging too much - # information to avoid inadvertent exposure of personally identifiable information (PII). If you - # want to log everything, set the level to "debug". - config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") - - # Use a different cache store in production. - # config.cache_store = :mem_cache_store - - # Use a real queuing backend for Active Job (and separate queues per environment). - # config.active_job.queue_adapter = :resque - # config.active_job.queue_name_prefix = "aws_rails_production" - - # Disable caching for Action Mailer templates even if Action Controller - # caching is enabled. - config.action_mailer.perform_caching = false - - # Ignore bad email addresses and do not raise email delivery errors. - # Set this to true and configure the email server for immediate delivery to raise delivery errors. - # config.action_mailer.raise_delivery_errors = false - - # Enable locale fallbacks for I18n (makes lookups for any locale fall back to - # the I18n.default_locale when a translation cannot be found). - config.i18n.fallbacks = true - - # Don't log any deprecations. - config.active_support.report_deprecations = false - - # Do not dump schema after migrations. - config.active_record.dump_schema_after_migration = false - - # Enable DNS rebinding protection and other `Host` header attacks. - # config.hosts = [ - # "example.com", # Allow requests from example.com - # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` - # ] - # Skip DNS rebinding protection for the default health check endpoint. - # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } -end diff --git a/examples/aws-rails/config/environments/test.rb b/examples/aws-rails/config/environments/test.rb deleted file mode 100644 index 0c616a1bf5..0000000000 --- a/examples/aws-rails/config/environments/test.rb +++ /dev/null @@ -1,67 +0,0 @@ -require "active_support/core_ext/integer/time" - -# The test environment is used exclusively to run your application's -# test suite. You never need to work with it otherwise. Remember that -# your test database is "scratch space" for the test suite and is wiped -# and recreated between test runs. Don't rely on the data there! - -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # While tests run files are not watched, reloading is not necessary. - config.enable_reloading = false - - # Eager loading loads your entire application. When running a single test locally, - # this is usually not necessary, and can slow down your test suite. However, it's - # recommended that you enable it in continuous integration systems to ensure eager - # loading is working properly before deploying your code. - config.eager_load = ENV["CI"].present? - - # Configure public file server for tests with Cache-Control for performance. - config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{1.hour.to_i}" } - - # Show full error reports and disable caching. - config.consider_all_requests_local = true - config.action_controller.perform_caching = false - config.cache_store = :null_store - - # Render exception templates for rescuable exceptions and raise for other exceptions. - config.action_dispatch.show_exceptions = :rescuable - - # Disable request forgery protection in test environment. - config.action_controller.allow_forgery_protection = false - - # Store uploaded files on the local file system in a temporary directory. - config.active_storage.service = :test - - # Disable caching for Action Mailer templates even if Action Controller - # caching is enabled. - config.action_mailer.perform_caching = false - - # Tell Action Mailer not to deliver emails to the real world. - # The :test delivery method accumulates sent emails in the - # ActionMailer::Base.deliveries array. - config.action_mailer.delivery_method = :test - - # Unlike controllers, the mailer instance doesn't have any context about the - # incoming request so you'll need to provide the :host parameter yourself. - config.action_mailer.default_url_options = { host: "www.example.com" } - - # Print deprecation notices to the stderr. - config.active_support.deprecation = :stderr - - # Raise exceptions for disallowed deprecations. - config.active_support.disallowed_deprecation = :raise - - # Tell Active Support which deprecation messages to disallow. - config.active_support.disallowed_deprecation_warnings = [] - - # Raises error for missing translations. - # config.i18n.raise_on_missing_translations = true - - # Annotate rendered view with file names. - # config.action_view.annotate_rendered_view_with_filenames = true - - # Raise error when a before_action's only/except options reference missing actions. - config.action_controller.raise_on_missing_callback_actions = true -end diff --git a/examples/aws-rails/config/importmap.rb b/examples/aws-rails/config/importmap.rb deleted file mode 100644 index 909dfc542d..0000000000 --- a/examples/aws-rails/config/importmap.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Pin npm packages by running ./bin/importmap - -pin "application" -pin "@hotwired/turbo-rails", to: "turbo.min.js" -pin "@hotwired/stimulus", to: "stimulus.min.js" -pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" -pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/examples/aws-rails/config/initializers/assets.rb b/examples/aws-rails/config/initializers/assets.rb deleted file mode 100644 index bd5bcd2b6a..0000000000 --- a/examples/aws-rails/config/initializers/assets.rb +++ /dev/null @@ -1,12 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = "1.0" - -# Add additional assets to the asset load path. -# Rails.application.config.assets.paths << Emoji.images_path - -# Precompile additional assets. -# application.js, application.css, and all non-JS/CSS in the app/assets -# folder are already added. -# Rails.application.config.assets.precompile += %w[ admin.js admin.css ] diff --git a/examples/aws-rails/config/initializers/content_security_policy.rb b/examples/aws-rails/config/initializers/content_security_policy.rb deleted file mode 100644 index b3076b38fe..0000000000 --- a/examples/aws-rails/config/initializers/content_security_policy.rb +++ /dev/null @@ -1,25 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Define an application-wide content security policy. -# See the Securing Rails Applications Guide for more information: -# https://guides.rubyonrails.org/security.html#content-security-policy-header - -# Rails.application.configure do -# config.content_security_policy do |policy| -# policy.default_src :self, :https -# policy.font_src :self, :https, :data -# policy.img_src :self, :https, :data -# policy.object_src :none -# policy.script_src :self, :https -# policy.style_src :self, :https -# # Specify URI for violation reports -# # policy.report_uri "/csp-violation-report-endpoint" -# end -# -# # Generate session nonces for permitted importmap, inline scripts, and inline styles. -# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } -# config.content_security_policy_nonce_directives = %w(script-src style-src) -# -# # Report violations without enforcing the policy. -# # config.content_security_policy_report_only = true -# end diff --git a/examples/aws-rails/config/initializers/filter_parameter_logging.rb b/examples/aws-rails/config/initializers/filter_parameter_logging.rb deleted file mode 100644 index c010b83ddd..0000000000 --- a/examples/aws-rails/config/initializers/filter_parameter_logging.rb +++ /dev/null @@ -1,8 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. -# Use this to limit dissemination of sensitive information. -# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. -Rails.application.config.filter_parameters += [ - :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn -] diff --git a/examples/aws-rails/config/initializers/inflections.rb b/examples/aws-rails/config/initializers/inflections.rb deleted file mode 100644 index 3860f659ea..0000000000 --- a/examples/aws-rails/config/initializers/inflections.rb +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Add new inflection rules using the following format. Inflections -# are locale specific, and you may define rules for as many different -# locales as you wish. All of these examples are active by default: -# ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.plural /^(ox)$/i, "\\1en" -# inflect.singular /^(ox)en/i, "\\1" -# inflect.irregular "person", "people" -# inflect.uncountable %w( fish sheep ) -# end - -# These inflection rules are supported but not enabled by default: -# ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.acronym "RESTful" -# end diff --git a/examples/aws-rails/config/initializers/permissions_policy.rb b/examples/aws-rails/config/initializers/permissions_policy.rb deleted file mode 100644 index 7db3b9577e..0000000000 --- a/examples/aws-rails/config/initializers/permissions_policy.rb +++ /dev/null @@ -1,13 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Define an application-wide HTTP permissions policy. For further -# information see: https://developers.google.com/web/updates/2018/06/feature-policy - -# Rails.application.config.permissions_policy do |policy| -# policy.camera :none -# policy.gyroscope :none -# policy.microphone :none -# policy.usb :none -# policy.fullscreen :self -# policy.payment :self, "https://secure.example.com" -# end diff --git a/examples/aws-rails/config/locales/en.yml b/examples/aws-rails/config/locales/en.yml deleted file mode 100644 index 6c349ae5e3..0000000000 --- a/examples/aws-rails/config/locales/en.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Files in the config/locales directory are used for internationalization and -# are automatically loaded by Rails. If you want to use locales other than -# English, add the necessary files in this directory. -# -# To use the locales, use `I18n.t`: -# -# I18n.t "hello" -# -# In views, this is aliased to just `t`: -# -# <%= t("hello") %> -# -# To use a different locale, set it with `I18n.locale`: -# -# I18n.locale = :es -# -# This would use the information in config/locales/es.yml. -# -# To learn more about the API, please read the Rails Internationalization guide -# at https://guides.rubyonrails.org/i18n.html. -# -# Be aware that YAML interprets the following case-insensitive strings as -# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings -# must be quoted to be interpreted as strings. For example: -# -# en: -# "yes": yup -# enabled: "ON" - -en: - hello: "Hello world" diff --git a/examples/aws-rails/config/puma.rb b/examples/aws-rails/config/puma.rb deleted file mode 100644 index 03c166f4cf..0000000000 --- a/examples/aws-rails/config/puma.rb +++ /dev/null @@ -1,34 +0,0 @@ -# This configuration file will be evaluated by Puma. The top-level methods that -# are invoked here are part of Puma's configuration DSL. For more information -# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. - -# Puma starts a configurable number of processes (workers) and each process -# serves each request in a thread from an internal thread pool. -# -# The ideal number of threads per worker depends both on how much time the -# application spends waiting for IO operations and on how much you wish to -# to prioritize throughput over latency. -# -# As a rule of thumb, increasing the number of threads will increase how much -# traffic a given process can handle (throughput), but due to CRuby's -# Global VM Lock (GVL) it has diminishing returns and will degrade the -# response time (latency) of the application. -# -# The default is set to 3 threads as it's deemed a decent compromise between -# throughput and latency for the average Rails application. -# -# Any libraries that use a connection pool or another resource pool should -# be configured to provide at least as many connections as the number of -# threads. This includes Active Record's `pool` parameter in `database.yml`. -threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) -threads threads_count, threads_count - -# Specifies the `port` that Puma will listen on to receive requests; default is 3000. -port ENV.fetch("PORT", 3000) - -# Allow puma to be restarted by `bin/rails restart` command. -plugin :tmp_restart - -# Specify the PID file. Defaults to tmp/pids/server.pid in development. -# In other environments, only set the PID file if requested. -pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/examples/aws-rails/config/routes.rb b/examples/aws-rails/config/routes.rb deleted file mode 100644 index 0a9237b608..0000000000 --- a/examples/aws-rails/config/routes.rb +++ /dev/null @@ -1,16 +0,0 @@ -Rails.application.routes.draw do - # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html - root 'uploads#new' - post 'upload', to: 'uploads#create' - - # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. - # Can be used by load balancers and uptime monitors to verify that the app is live. - get "up" => "rails/health#show", as: :rails_health_check - - # Render dynamic PWA files from app/views/pwa/* - get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker - get "manifest" => "rails/pwa#manifest", as: :pwa_manifest - - # Defines the root path route ("/") - # root "posts#index" -end diff --git a/examples/aws-rails/config/storage.yml b/examples/aws-rails/config/storage.yml deleted file mode 100644 index 823aa5f7ff..0000000000 --- a/examples/aws-rails/config/storage.yml +++ /dev/null @@ -1,34 +0,0 @@ -test: - service: Disk - root: <%= Rails.root.join("tmp/storage") %> - -local: - service: Disk - root: <%= Rails.root.join("storage") %> - -# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) -amazon: - service: S3 - # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> - # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> - # region: us-east-1 - bucket: <%= JSON.parse(ENV["SST_RESOURCE_MyBucket"])["name"] %> - -# Remember not to checkin your GCS keyfile to a repository -# google: -# service: GCS -# project: your_project -# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> -# bucket: your_own_bucket-<%= Rails.env %> - -# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) -# microsoft: -# service: AzureStorage -# storage_account_name: your_account_name -# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> -# container: your_container_name-<%= Rails.env %> - -# mirror: -# service: Mirror -# primary: local -# mirrors: [ amazon, google, microsoft ] diff --git a/examples/aws-rails/db/migrate/20240925124201_create_active_storage_tables.active_storage.rb b/examples/aws-rails/db/migrate/20240925124201_create_active_storage_tables.active_storage.rb deleted file mode 100644 index 6bd8bd082a..0000000000 --- a/examples/aws-rails/db/migrate/20240925124201_create_active_storage_tables.active_storage.rb +++ /dev/null @@ -1,57 +0,0 @@ -# This migration comes from active_storage (originally 20170806125915) -class CreateActiveStorageTables < ActiveRecord::Migration[7.0] - def change - # Use Active Record's configured type for primary and foreign keys - primary_key_type, foreign_key_type = primary_and_foreign_key_types - - create_table :active_storage_blobs, id: primary_key_type do |t| - t.string :key, null: false - t.string :filename, null: false - t.string :content_type - t.text :metadata - t.string :service_name, null: false - t.bigint :byte_size, null: false - t.string :checksum - - if connection.supports_datetime_with_precision? - t.datetime :created_at, precision: 6, null: false - else - t.datetime :created_at, null: false - end - - t.index [ :key ], unique: true - end - - create_table :active_storage_attachments, id: primary_key_type do |t| - t.string :name, null: false - t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type - t.references :blob, null: false, type: foreign_key_type - - if connection.supports_datetime_with_precision? - t.datetime :created_at, precision: 6, null: false - else - t.datetime :created_at, null: false - end - - t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true - t.foreign_key :active_storage_blobs, column: :blob_id - end - - create_table :active_storage_variant_records, id: primary_key_type do |t| - t.belongs_to :blob, null: false, index: false, type: foreign_key_type - t.string :variation_digest, null: false - - t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true - t.foreign_key :active_storage_blobs, column: :blob_id - end - end - - private - def primary_and_foreign_key_types - config = Rails.configuration.generators - setting = config.options[config.orm][:primary_key_type] - primary_key_type = setting || :primary_key - foreign_key_type = setting || :bigint - [ primary_key_type, foreign_key_type ] - end -end diff --git a/examples/aws-rails/db/schema.rb b/examples/aws-rails/db/schema.rb deleted file mode 100644 index 19ba58775c..0000000000 --- a/examples/aws-rails/db/schema.rb +++ /dev/null @@ -1,44 +0,0 @@ -# This file is auto-generated from the current state of the database. Instead -# of editing this file, please use the migrations feature of Active Record to -# incrementally modify your database, and then regenerate this schema definition. -# -# This file is the source Rails uses to define your schema when running `bin/rails -# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to -# be faster and is potentially less error prone than running all of your -# migrations from scratch. Old migrations may fail to apply correctly if those -# migrations use external dependencies or application code. -# -# It's strongly recommended that you check this file into your version control system. - -ActiveRecord::Schema[7.2].define(version: 2024_09_25_124201) do - create_table "active_storage_attachments", force: :cascade do |t| - t.string "name", null: false - t.string "record_type", null: false - t.bigint "record_id", null: false - t.bigint "blob_id", null: false - t.datetime "created_at", null: false - t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" - t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true - end - - create_table "active_storage_blobs", force: :cascade do |t| - t.string "key", null: false - t.string "filename", null: false - t.string "content_type" - t.text "metadata" - t.string "service_name", null: false - t.bigint "byte_size", null: false - t.string "checksum" - t.datetime "created_at", null: false - t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true - end - - create_table "active_storage_variant_records", force: :cascade do |t| - t.bigint "blob_id", null: false - t.string "variation_digest", null: false - t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true - end - - add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" - add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" -end diff --git a/examples/aws-rails/db/seeds.rb b/examples/aws-rails/db/seeds.rb deleted file mode 100644 index 4fbd6ed970..0000000000 --- a/examples/aws-rails/db/seeds.rb +++ /dev/null @@ -1,9 +0,0 @@ -# This file should ensure the existence of records required to run the application in every environment (production, -# development, test). The code here should be idempotent so that it can be executed at any point in every environment. -# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). -# -# Example: -# -# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| -# MovieGenre.find_or_create_by!(name: genre_name) -# end diff --git a/examples/aws-rails/lib/assets/.keep b/examples/aws-rails/lib/assets/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/lib/sst.rb b/examples/aws-rails/lib/sst.rb deleted file mode 100644 index 6b5cda9152..0000000000 --- a/examples/aws-rails/lib/sst.rb +++ /dev/null @@ -1,32 +0,0 @@ -require 'json' -module SST - class << self - private - - def parse_resource(resource_name) - env_var = "SST_RESOURCE_#{resource_name}" - parse_json(ENV[env_var]) - end - - def parse_json(json_string) - return nil if json_string.nil? - JSON.parse(json_string) - rescue JSON::ParserError - json_string # Return the original string if it's not valid JSON - end - - end - - def MyService - @MyService ||= parse_resource('MyService') - end - - def MyVpc - @MyVpc ||= parse_resource('MyVpc') - end - - def MyBucket - @MyBucket ||= parse_resource('MyBucket') - end - -end diff --git a/examples/aws-rails/lib/tasks/.keep b/examples/aws-rails/lib/tasks/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/log/.keep b/examples/aws-rails/log/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/public/404.html b/examples/aws-rails/public/404.html deleted file mode 100644 index 2be3af26fc..0000000000 --- a/examples/aws-rails/public/404.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - The page you were looking for doesn't exist (404) - - - - - - -
-
-

The page you were looking for doesn't exist.

-

You may have mistyped the address or the page may have moved.

-
-

If you are the application owner check the logs for more information.

-
- - diff --git a/examples/aws-rails/public/406-unsupported-browser.html b/examples/aws-rails/public/406-unsupported-browser.html deleted file mode 100644 index 7cf1e168e6..0000000000 --- a/examples/aws-rails/public/406-unsupported-browser.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - Your browser is not supported (406) - - - - - - -
-
-

Your browser is not supported.

-

Please upgrade your browser to continue.

-
-
- - diff --git a/examples/aws-rails/public/422.html b/examples/aws-rails/public/422.html deleted file mode 100644 index c08eac0d1d..0000000000 --- a/examples/aws-rails/public/422.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - The change you wanted was rejected (422) - - - - - - -
-
-

The change you wanted was rejected.

-

Maybe you tried to change something you didn't have access to.

-
-

If you are the application owner check the logs for more information.

-
- - diff --git a/examples/aws-rails/public/500.html b/examples/aws-rails/public/500.html deleted file mode 100644 index 78a030af22..0000000000 --- a/examples/aws-rails/public/500.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - We're sorry, but something went wrong (500) - - - - - - -
-
-

We're sorry, but something went wrong.

-
-

If you are the application owner check the logs for more information.

-
- - diff --git a/examples/aws-rails/public/icon.png b/examples/aws-rails/public/icon.png deleted file mode 100644 index f3b5abcbde..0000000000 Binary files a/examples/aws-rails/public/icon.png and /dev/null differ diff --git a/examples/aws-rails/public/icon.svg b/examples/aws-rails/public/icon.svg deleted file mode 100644 index 78307ccd4b..0000000000 --- a/examples/aws-rails/public/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/examples/aws-rails/public/robots.txt b/examples/aws-rails/public/robots.txt deleted file mode 100644 index c19f78ab68..0000000000 --- a/examples/aws-rails/public/robots.txt +++ /dev/null @@ -1 +0,0 @@ -# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/examples/aws-rails/sst.config.ts b/examples/aws-rails/sst.config.ts deleted file mode 100644 index 9e2658ee3f..0000000000 --- a/examples/aws-rails/sst.config.ts +++ /dev/null @@ -1,41 +0,0 @@ -/// - -/** - * ## Rails container - * - * Deploy a Ruby on Rails app in a container with a linked public S3 bucket. - */ -export default $config({ - app(input) { - return { - name: "aws-rails", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - const vpc = new sst.aws.Vpc("MyVpc"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - environment: { - RAILS_MASTER_KEY: (await import("fs")).readFileSync( - "config/master.key", - "utf8" - ), - }, - dev: { - command: "bin/rails server", - }, - link: [bucket], - }); - return { vpc: vpc.id }; - }, -}); diff --git a/examples/aws-rails/storage/.keep b/examples/aws-rails/storage/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/application_system_test_case.rb b/examples/aws-rails/test/application_system_test_case.rb deleted file mode 100644 index cee29fd214..0000000000 --- a/examples/aws-rails/test/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] -end diff --git a/examples/aws-rails/test/channels/application_cable/connection_test.rb b/examples/aws-rails/test/channels/application_cable/connection_test.rb deleted file mode 100644 index 6340bf9c04..0000000000 --- a/examples/aws-rails/test/channels/application_cable/connection_test.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "test_helper" - -module ApplicationCable - class ConnectionTest < ActionCable::Connection::TestCase - # test "connects with cookies" do - # cookies.signed[:user_id] = 42 - # - # connect - # - # assert_equal connection.user_id, "42" - # end - end -end diff --git a/examples/aws-rails/test/controllers/.keep b/examples/aws-rails/test/controllers/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/controllers/uploads_controller_test.rb b/examples/aws-rails/test/controllers/uploads_controller_test.rb deleted file mode 100644 index c46b10c54e..0000000000 --- a/examples/aws-rails/test/controllers/uploads_controller_test.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "test_helper" - -class UploadsControllerTest < ActionDispatch::IntegrationTest - test "should get new" do - get uploads_new_url - assert_response :success - end - - test "should get create" do - get uploads_create_url - assert_response :success - end -end diff --git a/examples/aws-rails/test/fixtures/files/.keep b/examples/aws-rails/test/fixtures/files/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/helpers/.keep b/examples/aws-rails/test/helpers/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/integration/.keep b/examples/aws-rails/test/integration/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/mailers/.keep b/examples/aws-rails/test/mailers/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/models/.keep b/examples/aws-rails/test/models/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/system/.keep b/examples/aws-rails/test/system/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/test/test_helper.rb b/examples/aws-rails/test/test_helper.rb deleted file mode 100644 index 0c22470ec1..0000000000 --- a/examples/aws-rails/test/test_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ -ENV["RAILS_ENV"] ||= "test" -require_relative "../config/environment" -require "rails/test_help" - -module ActiveSupport - class TestCase - # Run tests in parallel with specified workers - parallelize(workers: :number_of_processors) - - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - fixtures :all - - # Add more helper methods to be used by all tests here... - end -end diff --git a/examples/aws-rails/vendor/.keep b/examples/aws-rails/vendor/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rails/vendor/javascript/.keep b/examples/aws-rails/vendor/javascript/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/aws-rds-instance-mysql-public/.gitignore b/examples/aws-rds-instance-mysql-public/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-rds-instance-mysql-public/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-rds-instance-mysql-public/package.json b/examples/aws-rds-instance-mysql-public/package.json deleted file mode 100644 index 041968a701..0000000000 --- a/examples/aws-rds-instance-mysql-public/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-rds-instance-mysql-public-example", - "version": "1.0.0", - "description": "", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sst": "file:../../sdk/js" - }, - "devDependencies": { - } -} diff --git a/examples/aws-rds-instance-mysql-public/sst.config.ts b/examples/aws-rds-instance-mysql-public/sst.config.ts deleted file mode 100644 index 1fa876189a..0000000000 --- a/examples/aws-rds-instance-mysql-public/sst.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// - -/** - * ## AWS RDS MySQL public - * - * Create a publicly accessible MySQL RDS instance with a security group that - * allows external connections. - */ -export default $config({ - app(input) { - return { - name: "aws-rds-instance-mysql-public", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const MYSQL_PORT = 3306; - const ALL_IPS = '0.0.0.0/0'; - const publicSecurityGroup = new aws.ec2.SecurityGroup( - 'MyPublicSecurityGroup', - { - ingress: [ - { - // Expose to public connection. Remove if not needed - protocol: 'tcp', - fromPort: MYSQL_PORT, - toPort: MYSQL_PORT, - cidrBlocks: [ALL_IPS], - }, - ], - }, - ); - - const identifier = 'my-db-instance'; - - const database = new aws.rds.Instance( - 'MyDbInstanceMySQL', - { - identifier, - engine: 'mysql', - // free-tier - instanceClass: 'db.t3.micro', - allocatedStorage: 20, // free-tier 20GB - // credentials - username: 'dev-user', - password: 'dev-password', - dbName: 'dev-database', - // settings - tags: { Name: identifier }, - skipFinalSnapshot: true, - - // allow public access - vpcSecurityGroupIds: [publicSecurityGroup.id], - publiclyAccessible: true, - }, - ); - - return { - Database: database.address - }; - }, -}); diff --git a/examples/aws-rds-instance-mysql-public/tsconfig.json b/examples/aws-rds-instance-mysql-public/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-rds-instance-mysql-public/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-react-router/.dockerignore b/examples/aws-react-router/.dockerignore deleted file mode 100644 index 9b8d514712..0000000000 --- a/examples/aws-react-router/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -.react-router -build -node_modules -README.md \ No newline at end of file diff --git a/examples/aws-react-router/.gitignore b/examples/aws-react-router/.gitignore deleted file mode 100644 index 5913deaa94..0000000000 --- a/examples/aws-react-router/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.DS_Store -/node_modules/ - -# React Router -/.react-router/ -/build/ - -# sst -.sst diff --git a/examples/aws-react-router/Dockerfile b/examples/aws-react-router/Dockerfile deleted file mode 100644 index 207bf937e3..0000000000 --- a/examples/aws-react-router/Dockerfile +++ /dev/null @@ -1,22 +0,0 @@ -FROM node:20-alpine AS development-dependencies-env -COPY . /app -WORKDIR /app -RUN npm ci - -FROM node:20-alpine AS production-dependencies-env -COPY ./package.json package-lock.json /app/ -WORKDIR /app -RUN npm ci --omit=dev - -FROM node:20-alpine AS build-env -COPY . /app/ -COPY --from=development-dependencies-env /app/node_modules /app/node_modules -WORKDIR /app -RUN npm run build - -FROM node:20-alpine -COPY ./package.json package-lock.json /app/ -COPY --from=production-dependencies-env /app/node_modules /app/node_modules -COPY --from=build-env /app/build /app/build -WORKDIR /app -CMD ["npm", "run", "start"] \ No newline at end of file diff --git a/examples/aws-react-router/app/app.css b/examples/aws-react-router/app/app.css deleted file mode 100644 index 99345d8218..0000000000 --- a/examples/aws-react-router/app/app.css +++ /dev/null @@ -1,15 +0,0 @@ -@import "tailwindcss"; - -@theme { - --font-sans: "Inter", ui-sans-serif, system-ui, sans-serif, - "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; -} - -html, -body { - @apply bg-white dark:bg-gray-950; - - @media (prefers-color-scheme: dark) { - color-scheme: dark; - } -} diff --git a/examples/aws-react-router/app/root.tsx b/examples/aws-react-router/app/root.tsx deleted file mode 100644 index 9fc663618c..0000000000 --- a/examples/aws-react-router/app/root.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { - isRouteErrorResponse, - Links, - Meta, - Outlet, - Scripts, - ScrollRestoration, -} from "react-router"; - -import type { Route } from "./+types/root"; -import "./app.css"; - -export const links: Route.LinksFunction = () => [ - { rel: "preconnect", href: "https://fonts.googleapis.com" }, - { - rel: "preconnect", - href: "https://fonts.gstatic.com", - crossOrigin: "anonymous", - }, - { - rel: "stylesheet", - href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap", - }, -]; - -export function Layout({ children }: { children: React.ReactNode }) { - return ( - - - - - - - - - {children} - - - - - ); -} - -export default function App() { - return ; -} - -export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { - let message = "Oops!"; - let details = "An unexpected error occurred."; - let stack: string | undefined; - - if (isRouteErrorResponse(error)) { - message = error.status === 404 ? "404" : "Error"; - details = - error.status === 404 - ? "The requested page could not be found." - : error.statusText || details; - } else if (import.meta.env.DEV && error && error instanceof Error) { - details = error.message; - stack = error.stack; - } - - return ( -
-

{message}

-

{details}

- {stack && ( -
-          {stack}
-        
- )} -
- ); -} diff --git a/examples/aws-react-router/app/routes.ts b/examples/aws-react-router/app/routes.ts deleted file mode 100644 index 102b402587..0000000000 --- a/examples/aws-react-router/app/routes.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { type RouteConfig, index } from "@react-router/dev/routes"; - -export default [index("routes/home.tsx")] satisfies RouteConfig; diff --git a/examples/aws-react-router/app/routes/home.tsx b/examples/aws-react-router/app/routes/home.tsx deleted file mode 100644 index c61efecfa8..0000000000 --- a/examples/aws-react-router/app/routes/home.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; -import type { Route } from "./+types/home"; -import { Welcome } from "../welcome/welcome"; - -export function meta({}: Route.MetaArgs) { - return [ - { title: "New React Router App" }, - { name: "description", content: "Welcome to React Router!" }, - ]; -} - -export async function loader() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return { url }; -} - -export default function Home({ loaderData }: Route.ComponentProps) { - const { url } = loaderData; - return ( -
-
-

- Welcome to React Router! -

-
{ - e.preventDefault(); - - const file = (e.target as HTMLFormElement).file.files?.[0]!; - - const image = await fetch(url, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }} - > - - -
-
-
- ); -} diff --git a/examples/aws-react-router/app/welcome/logo-dark.svg b/examples/aws-react-router/app/welcome/logo-dark.svg deleted file mode 100644 index dd82028944..0000000000 --- a/examples/aws-react-router/app/welcome/logo-dark.svg +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/aws-react-router/app/welcome/logo-light.svg b/examples/aws-react-router/app/welcome/logo-light.svg deleted file mode 100644 index 73284929d3..0000000000 --- a/examples/aws-react-router/app/welcome/logo-light.svg +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/aws-react-router/app/welcome/welcome.tsx b/examples/aws-react-router/app/welcome/welcome.tsx deleted file mode 100644 index 8ac6e1d30b..0000000000 --- a/examples/aws-react-router/app/welcome/welcome.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import logoDark from "./logo-dark.svg"; -import logoLight from "./logo-light.svg"; - -export function Welcome() { - return ( -
-
-
-
- React Router - React Router -
-
-
- -
-
-
- ); -} - -const resources = [ - { - href: "https://reactrouter.com/docs", - text: "React Router Docs", - icon: ( - - - - ), - }, - { - href: "https://rmx.as/discord", - text: "Join Discord", - icon: ( - - - - ), - }, -]; diff --git a/examples/aws-react-router/package.json b/examples/aws-react-router/package.json deleted file mode 100644 index eb7861a131..0000000000 --- a/examples/aws-react-router/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "aws-react-router", - "private": true, - "type": "module", - "scripts": { - "build": "react-router build", - "dev": "react-router dev", - "start": "react-router-serve ./build/server/index.js", - "typecheck": "react-router typegen && tsc" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.796.0", - "@aws-sdk/s3-request-presigner": "^3.796.0", - "@react-router/node": "^7.5.2", - "@react-router/serve": "^7.5.2", - "isbot": "^5.1.17", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "react-router": "^7.5.2", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@react-router/dev": "^7.5.2", - "@tailwindcss/vite": "^4.0.0", - "@types/node": "^20", - "@types/react": "^19.0.1", - "@types/react-dom": "^19.0.1", - "react-router-devtools": "^1.1.0", - "tailwindcss": "^4.0.0", - "typescript": "^5.7.2", - "vite": "^5.4.11", - "vite-tsconfig-paths": "^5.1.4" - } -} diff --git a/examples/aws-react-router/public/favicon.ico b/examples/aws-react-router/public/favicon.ico deleted file mode 100644 index 5dbdfcddcb..0000000000 Binary files a/examples/aws-react-router/public/favicon.ico and /dev/null differ diff --git a/examples/aws-react-router/react-router.config.ts b/examples/aws-react-router/react-router.config.ts deleted file mode 100644 index 6ff16f9177..0000000000 --- a/examples/aws-react-router/react-router.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Config } from "@react-router/dev/config"; - -export default { - // Config options... - // Server-side render by default, to enable SPA mode set this to `false` - ssr: true, -} satisfies Config; diff --git a/examples/aws-react-router/sst.config.ts b/examples/aws-react-router/sst.config.ts deleted file mode 100644 index 97ecb1054f..0000000000 --- a/examples/aws-react-router/sst.config.ts +++ /dev/null @@ -1,21 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-react-router", - removal: input?.stage === "production" ? "retain" : "remove", - protect: ["production"].includes(input?.stage), - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - - new sst.aws.React("MyWeb", { - link: [bucket], - }); - }, -}); diff --git a/examples/aws-react-router/tsconfig.json b/examples/aws-react-router/tsconfig.json deleted file mode 100644 index 65fa16a18d..0000000000 --- a/examples/aws-react-router/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "include": [ - "**/*", - "**/.server/**/*", - "**/.client/**/*", - ".react-router/types/**/*" - ], - "compilerOptions": { - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "types": ["node", "vite/client"], - "target": "ES2022", - "module": "ES2022", - "moduleResolution": "bundler", - "jsx": "react-jsx", - "rootDirs": [".", "./.react-router/types"], - "baseUrl": ".", - "paths": { - "~/*": ["./app/*"] - }, - "esModuleInterop": true, - "verbatimModuleSyntax": true, - "noEmit": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "strict": true - },"exclude":["sst.config.ts"] -} diff --git a/examples/aws-react-router/vite.config.ts b/examples/aws-react-router/vite.config.ts deleted file mode 100644 index 4a88d5871c..0000000000 --- a/examples/aws-react-router/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { reactRouter } from "@react-router/dev/vite"; -import tailwindcss from "@tailwindcss/vite"; -import { defineConfig } from "vite"; -import tsconfigPaths from "vite-tsconfig-paths"; - -export default defineConfig({ - plugins: [tailwindcss(), reactRouter(), tsconfigPaths()], -}); diff --git a/examples/aws-realtime-nextjs/.gitignore b/examples/aws-realtime-nextjs/.gitignore deleted file mode 100644 index 69d7f97469..0000000000 --- a/examples/aws-realtime-nextjs/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# sst -.sst - -# open-next -.open-next diff --git a/examples/aws-realtime-nextjs/app/favicon.ico b/examples/aws-realtime-nextjs/app/favicon.ico deleted file mode 100644 index 718d6fea48..0000000000 Binary files a/examples/aws-realtime-nextjs/app/favicon.ico and /dev/null differ diff --git a/examples/aws-realtime-nextjs/app/globals.css b/examples/aws-realtime-nextjs/app/globals.css deleted file mode 100644 index f4bd77c0cc..0000000000 --- a/examples/aws-realtime-nextjs/app/globals.css +++ /dev/null @@ -1,107 +0,0 @@ -:root { - --max-width: 1100px; - --border-radius: 12px; - --font-mono: ui-monospace, Menlo, Monaco, "Cascadia Mono", "Segoe UI Mono", - "Roboto Mono", "Oxygen Mono", "Ubuntu Monospace", "Source Code Pro", - "Fira Mono", "Droid Sans Mono", "Courier New", monospace; - - --foreground-rgb: 0, 0, 0; - --background-start-rgb: 214, 219, 220; - --background-end-rgb: 255, 255, 255; - - --primary-glow: conic-gradient( - from 180deg at 50% 50%, - #16abff33 0deg, - #0885ff33 55deg, - #54d6ff33 120deg, - #0071ff33 160deg, - transparent 360deg - ); - --secondary-glow: radial-gradient( - rgba(255, 255, 255, 1), - rgba(255, 255, 255, 0) - ); - - --tile-start-rgb: 239, 245, 249; - --tile-end-rgb: 228, 232, 233; - --tile-border: conic-gradient( - #00000080, - #00000040, - #00000030, - #00000020, - #00000010, - #00000010, - #00000080 - ); - - --callout-rgb: 238, 240, 241; - --callout-border-rgb: 172, 175, 176; - --card-rgb: 180, 185, 188; - --card-border-rgb: 131, 134, 135; -} - -@media (prefers-color-scheme: dark) { - :root { - --foreground-rgb: 255, 255, 255; - --background-start-rgb: 0, 0, 0; - --background-end-rgb: 0, 0, 0; - - --primary-glow: radial-gradient(rgba(1, 65, 255, 0.4), rgba(1, 65, 255, 0)); - --secondary-glow: linear-gradient( - to bottom right, - rgba(1, 65, 255, 0), - rgba(1, 65, 255, 0), - rgba(1, 65, 255, 0.3) - ); - - --tile-start-rgb: 2, 13, 46; - --tile-end-rgb: 2, 5, 19; - --tile-border: conic-gradient( - #ffffff80, - #ffffff40, - #ffffff30, - #ffffff20, - #ffffff10, - #ffffff10, - #ffffff80 - ); - - --callout-rgb: 20, 20, 20; - --callout-border-rgb: 108, 108, 108; - --card-rgb: 100, 100, 100; - --card-border-rgb: 200, 200, 200; - } -} - -* { - box-sizing: border-box; - padding: 0; - margin: 0; -} - -html, -body { - max-width: 100vw; - overflow-x: hidden; -} - -body { - color: rgb(var(--foreground-rgb)); - background: linear-gradient( - to bottom, - transparent, - rgb(var(--background-end-rgb)) - ) - rgb(var(--background-start-rgb)); -} - -a { - color: inherit; - text-decoration: none; -} - -@media (prefers-color-scheme: dark) { - html { - color-scheme: dark; - } -} diff --git a/examples/aws-realtime-nextjs/app/layout.tsx b/examples/aws-realtime-nextjs/app/layout.tsx deleted file mode 100644 index 3314e4780a..0000000000 --- a/examples/aws-realtime-nextjs/app/layout.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import type { Metadata } from "next"; -import { Inter } from "next/font/google"; -import "./globals.css"; - -const inter = Inter({ subsets: ["latin"] }); - -export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - {children} - - ); -} diff --git a/examples/aws-realtime-nextjs/app/page.module.css b/examples/aws-realtime-nextjs/app/page.module.css deleted file mode 100644 index 5c4b1e6a2c..0000000000 --- a/examples/aws-realtime-nextjs/app/page.module.css +++ /dev/null @@ -1,230 +0,0 @@ -.main { - display: flex; - flex-direction: column; - justify-content: space-between; - align-items: center; - padding: 6rem; - min-height: 100vh; -} - -.description { - display: inherit; - justify-content: inherit; - align-items: inherit; - font-size: 0.85rem; - max-width: var(--max-width); - width: 100%; - z-index: 2; - font-family: var(--font-mono); -} - -.description a { - display: flex; - justify-content: center; - align-items: center; - gap: 0.5rem; -} - -.description p { - position: relative; - margin: 0; - padding: 1rem; - background-color: rgba(var(--callout-rgb), 0.5); - border: 1px solid rgba(var(--callout-border-rgb), 0.3); - border-radius: var(--border-radius); -} - -.code { - font-weight: 700; - font-family: var(--font-mono); -} - -.grid { - display: grid; - grid-template-columns: repeat(4, minmax(25%, auto)); - max-width: 100%; - width: var(--max-width); -} - -.card { - padding: 1rem 1.2rem; - border-radius: var(--border-radius); - background: rgba(var(--card-rgb), 0); - border: 1px solid rgba(var(--card-border-rgb), 0); - transition: background 200ms, border 200ms; -} - -.card span { - display: inline-block; - transition: transform 200ms; -} - -.card h2 { - font-weight: 600; - margin-bottom: 0.7rem; -} - -.card p { - margin: 0; - opacity: 0.6; - font-size: 0.9rem; - line-height: 1.5; - max-width: 30ch; - text-wrap: balance; -} - -.center { - display: flex; - justify-content: center; - align-items: center; - position: relative; - padding: 4rem 0; -} - -.center::before { - background: var(--secondary-glow); - border-radius: 50%; - width: 480px; - height: 360px; - margin-left: -400px; -} - -.center::after { - background: var(--primary-glow); - width: 240px; - height: 180px; - z-index: -1; -} - -.center::before, -.center::after { - content: ""; - left: 50%; - position: absolute; - filter: blur(45px); - transform: translateZ(0); -} - -.logo { - position: relative; -} -/* Enable hover only on non-touch devices */ -@media (hover: hover) and (pointer: fine) { - .card:hover { - background: rgba(var(--card-rgb), 0.1); - border: 1px solid rgba(var(--card-border-rgb), 0.15); - } - - .card:hover span { - transform: translateX(4px); - } -} - -@media (prefers-reduced-motion) { - .card:hover span { - transform: none; - } -} - -/* Mobile */ -@media (max-width: 700px) { - .content { - padding: 4rem; - } - - .grid { - grid-template-columns: 1fr; - margin-bottom: 120px; - max-width: 320px; - text-align: center; - } - - .card { - padding: 1rem 2.5rem; - } - - .card h2 { - margin-bottom: 0.5rem; - } - - .center { - padding: 8rem 0 6rem; - } - - .center::before { - transform: none; - height: 300px; - } - - .description { - font-size: 0.8rem; - } - - .description a { - padding: 1rem; - } - - .description p, - .description div { - display: flex; - justify-content: center; - position: fixed; - width: 100%; - } - - .description p { - align-items: center; - inset: 0 0 auto; - padding: 2rem 1rem 1.4rem; - border-radius: 0; - border: none; - border-bottom: 1px solid rgba(var(--callout-border-rgb), 0.25); - background: linear-gradient( - to bottom, - rgba(var(--background-start-rgb), 1), - rgba(var(--callout-rgb), 0.5) - ); - background-clip: padding-box; - backdrop-filter: blur(24px); - } - - .description div { - align-items: flex-end; - pointer-events: none; - inset: auto 0 0; - padding: 2rem; - height: 200px; - background: linear-gradient( - to bottom, - transparent 0%, - rgb(var(--background-end-rgb)) 40% - ); - z-index: 1; - } -} - -/* Tablet and Smaller Desktop */ -@media (min-width: 701px) and (max-width: 1120px) { - .grid { - grid-template-columns: repeat(2, 50%); - } -} - -@media (prefers-color-scheme: dark) { - .vercelLogo { - filter: invert(1); - } - - .logo { - filter: invert(1) drop-shadow(0 0 0.3rem #ffffff70); - } -} - -@keyframes rotate { - from { - transform: rotate(360deg); - } - to { - transform: rotate(0deg); - } -} diff --git a/examples/aws-realtime-nextjs/app/page.tsx b/examples/aws-realtime-nextjs/app/page.tsx deleted file mode 100644 index 34bd2ddd90..0000000000 --- a/examples/aws-realtime-nextjs/app/page.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { Resource } from "sst"; -import Image from "next/image"; -import Chat from "@/components/chat"; -import styles from "./page.module.css"; - -const topic = "sst-chat"; - -export default function Home() { - return ( -
- -
- Next.js Logo -
- -
- -
- -
- ); -} diff --git a/examples/aws-realtime-nextjs/authorizer.ts b/examples/aws-realtime-nextjs/authorizer.ts deleted file mode 100644 index f415e08b67..0000000000 --- a/examples/aws-realtime-nextjs/authorizer.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from "sst"; -import { realtime } from "sst/aws/realtime"; - -export const handler = realtime.authorizer(async (token) => { - const prefix = `${Resource.App.name}/${Resource.App.stage}`; - - const isValid = token === "PLACEHOLDER_TOKEN"; - - return isValid - ? { - publish: [`${prefix}/*`], - subscribe: [`${prefix}/*`], - } - : { - publish: [], - subscribe: [], - }; -}); diff --git a/examples/aws-realtime-nextjs/components/chat.module.css b/examples/aws-realtime-nextjs/components/chat.module.css deleted file mode 100644 index f5c6e5b1b7..0000000000 --- a/examples/aws-realtime-nextjs/components/chat.module.css +++ /dev/null @@ -1,50 +0,0 @@ -.chat { - gap: 1rem; - width: 30rem; - display: flex; - padding: 1rem; - flex-direction: column; - border-radius: var(--border-radius); - background-color: rgba(var(--callout-rgb), 0.5); - border: 1px solid rgba(var(--callout-border-rgb), 0.3); -} - -.messages { - padding-bottom: 0.125rem; - border-bottom: 1px solid rgba(var(--callout-border-rgb), 0.3); -} -.messages > div { - line-height: 1.1; - padding-bottom: 0.625rem; -} - -.form { - display: flex; - gap: 0.625rem; -} -.form input { - flex: 1; - font-size: 0.875rem; - padding: 0.5rem 0.75rem; - border-radius: calc(1rem - var(--border-radius)); - border: 1px solid rgba(var(--callout-border-rgb), 1); -} -.form button { - font-weight: 500; - font-size: 0.875rem; - padding: 0.5rem 0.75rem; - border-radius: calc(1rem - var(--border-radius)); - background: linear-gradient( - to bottom right, - rgba(var(--tile-start-rgb), 1), - rgba(var(--tile-end-rgb), 1) - ); - border: 1px solid rgba(var(--callout-border-rgb), 1); -} -.form button:active:enabled { - background: linear-gradient( - to top left, - rgba(var(--tile-start-rgb), 1), - rgba(var(--tile-end-rgb), 1) - ); -} diff --git a/examples/aws-realtime-nextjs/components/chat.tsx b/examples/aws-realtime-nextjs/components/chat.tsx deleted file mode 100644 index 299f4596a6..0000000000 --- a/examples/aws-realtime-nextjs/components/chat.tsx +++ /dev/null @@ -1,83 +0,0 @@ -"use client"; - -import mqtt from "mqtt"; -import { useState, useEffect } from "react"; -import styles from "./chat.module.css"; - -function createConnection(endpoint: string, authorizer: string) { - return mqtt.connect(`wss://${endpoint}/mqtt?x-amz-customauthorizer-name=${authorizer}`, { - protocolVersion: 5, - manualConnect: true, - username: "", // Must be empty for the authorizer - password: "PLACEHOLDER_TOKEN", // Passed as the token to the authorizer - clientId: `client_${window.crypto.randomUUID()}`, - }); -} - -export default function Chat( - { topic, endpoint, authorizer }: { topic: string, endpoint: string, authorizer: string } -) { - const [messages, setMessages] = useState([]); - const [connection, setConnection] = useState(null); - - useEffect(() => { - const connection = createConnection(endpoint, authorizer); - - connection.on("connect", async () => { - try { - await connection.subscribeAsync(topic, { qos: 1 }); - setConnection(connection); - } catch (e) { } - }); - connection.on("message", (_fullTopic, payload) => { - const message = new TextDecoder("utf8").decode(new Uint8Array(payload)); - setMessages((prev) => [...prev, message]); - }); - connection.on("error", console.error); - - connection.connect(); - - return () => { - connection.end(); - setConnection(null); - }; - }, [topic, endpoint, authorizer]); - - return ( -
- {connection && messages.length > 0 && -
- {messages.map((msg, i) => ( -
{JSON.parse(msg).message}
- ))} -
- } -
{ - e.preventDefault(); - - const input = (e.target as HTMLFormElement).message; - - connection!.publish( - topic, - JSON.stringify({ message: input.value }), - { qos: 1 } - ); - input.value = ""; - }} - > - - -
-
- ); -} diff --git a/examples/aws-realtime-nextjs/next.config.mjs b/examples/aws-realtime-nextjs/next.config.mjs deleted file mode 100644 index 4678774e6d..0000000000 --- a/examples/aws-realtime-nextjs/next.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = {}; - -export default nextConfig; diff --git a/examples/aws-realtime-nextjs/package.json b/examples/aws-realtime-nextjs/package.json deleted file mode 100644 index 3cce662c8b..0000000000 --- a/examples/aws-realtime-nextjs/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "aws-realtime-nextjs", - "version": "0.1.0", - "private": true, - "scripts": { - "build": "next build", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "mqtt": "^5.10.1", - "next": "14.2.3", - "react": "^18", - "react-dom": "^18", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/node": "^20", - "@types/react": "^18", - "@types/react-dom": "^18", - "typescript": "^5" - } -} diff --git a/examples/aws-realtime-nextjs/public/next.svg b/examples/aws-realtime-nextjs/public/next.svg deleted file mode 100644 index 5174b28c56..0000000000 --- a/examples/aws-realtime-nextjs/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-realtime-nextjs/public/vercel.svg b/examples/aws-realtime-nextjs/public/vercel.svg deleted file mode 100644 index d2f8422273..0000000000 --- a/examples/aws-realtime-nextjs/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-realtime-nextjs/sst.config.ts b/examples/aws-realtime-nextjs/sst.config.ts deleted file mode 100644 index f65031cdd1..0000000000 --- a/examples/aws-realtime-nextjs/sst.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-realtime-nextjs", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const realtime = new sst.aws.Realtime("MyRealtime", { - authorizer: "authorizer.handler", - }); - - new sst.aws.Nextjs("MyWeb", { - link: [realtime], - }); - }, -}); diff --git a/examples/aws-realtime-nextjs/tsconfig.json b/examples/aws-realtime-nextjs/tsconfig.json deleted file mode 100644 index 56433afeb2..0000000000 --- a/examples/aws-realtime-nextjs/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-realtime/authorizer.ts b/examples/aws-realtime/authorizer.ts deleted file mode 100644 index 27f8b1266d..0000000000 --- a/examples/aws-realtime/authorizer.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { RealtimeAuthHandler } from "sst"; - -export const handler = RealtimeAuthHandler(async () => { - return { - subscribe: [process.env.SST_TOPIC], - publish: [process.env.SST_TOPIC], - }; -}); diff --git a/examples/aws-realtime/package.json b/examples/aws-realtime/package.json deleted file mode 100644 index 5d2271a4b7..0000000000 --- a/examples/aws-realtime/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-realtime", - "workspaces": [ - "web" - ], - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "sst": "file:../../sdk/js" - }, - "dependencies": { - "@aws-sdk/client-iot-data-plane": "^3.569.0" - } -} diff --git a/examples/aws-realtime/publisher.ts b/examples/aws-realtime/publisher.ts deleted file mode 100644 index 0651e2f725..0000000000 --- a/examples/aws-realtime/publisher.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - IoTDataPlaneClient, - PublishCommand, -} from "@aws-sdk/client-iot-data-plane"; -const data = new IoTDataPlaneClient({}); - -export const handler = async () => { - await data.send( - new PublishCommand({ - payload: Buffer.from( - JSON.stringify({ message: "A greeting from Lambda" }) - ), - topic: process.env.SST_TOPIC, - }) - ); - return { - statusCode: 200, - body: "Sent", - }; -}; diff --git a/examples/aws-realtime/sst.config.ts b/examples/aws-realtime/sst.config.ts deleted file mode 100644 index 2a511b418f..0000000000 --- a/examples/aws-realtime/sst.config.ts +++ /dev/null @@ -1,51 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-realtime", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const topic = `${$app.name}/${$app.stage}/chat`; - const realtime = new sst.aws.Realtime("MyRealtime", { - authorizer: { - handler: "authorizer.handler", - environment: { - SST_TOPIC: topic, - }, - }, - }); - realtime.subscribe("subscriber.handler", { - filter: topic, - }); - - new sst.aws.StaticSite("Web", { - path: "web", - build: { - command: "npm run build", - output: "dist", - }, - environment: { - VITE_REALTIME_ENDPOINT: realtime.endpoint, - VITE_TOPIC: topic, - VITE_AUTHORIZER: realtime.authorizer, - }, - }); - - const publisher = new sst.aws.Function("MyApp", { - handler: "publisher.handler", - environment: { - SST_TOPIC: topic, - }, - url: true, - link: [realtime], - }); - - return { - publisher: publisher.url, - }; - }, -}); diff --git a/examples/aws-realtime/subscriber.ts b/examples/aws-realtime/subscriber.ts deleted file mode 100644 index a33af0f71e..0000000000 --- a/examples/aws-realtime/subscriber.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const handler = async (event: any) => { - console.log(event); -}; diff --git a/examples/aws-realtime/tsconfig.json b/examples/aws-realtime/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-realtime/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-realtime/web/.gitignore b/examples/aws-realtime/web/.gitignore deleted file mode 100644 index a547bf36d8..0000000000 --- a/examples/aws-realtime/web/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr -*.local - -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? diff --git a/examples/aws-realtime/web/index.html b/examples/aws-realtime/web/index.html deleted file mode 100644 index 44a933506f..0000000000 --- a/examples/aws-realtime/web/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Vite + TS - - -
- - - diff --git a/examples/aws-realtime/web/package.json b/examples/aws-realtime/web/package.json deleted file mode 100644 index 9cb15e316e..0000000000 --- a/examples/aws-realtime/web/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "web", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "sst dev vite", - "build": "tsc && vite build", - "preview": "vite preview" - }, - "dependencies": { - "@paralleldrive/cuid2": "^2.2.2", - "aws-iot-device-sdk-v2": "1.13.1", - "events": "^3.3.0" - }, - "devDependencies": { - "typescript": "^5.2.2", - "vite": "^5.2.0" - } -} diff --git a/examples/aws-realtime/web/public/vite.svg b/examples/aws-realtime/web/public/vite.svg deleted file mode 100644 index e7b8dfb1b2..0000000000 --- a/examples/aws-realtime/web/public/vite.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-realtime/web/src/main.ts b/examples/aws-realtime/web/src/main.ts deleted file mode 100644 index 3a546f7575..0000000000 --- a/examples/aws-realtime/web/src/main.ts +++ /dev/null @@ -1,73 +0,0 @@ -import "./style.css"; -import { iot, mqtt } from "aws-iot-device-sdk-v2"; -import { createId } from "@paralleldrive/cuid2"; - -const endpoint = import.meta.env.VITE_REALTIME_ENDPOINT; -const topic = import.meta.env.VITE_TOPIC; -const authorizer = import.meta.env.VITE_AUTHORIZER; - -const messages: string[] = []; - -// Setup MQTT connection -let connection: mqtt.MqttClientConnection; -async function createConnection() { - const config = iot.AwsIotMqttConnectionConfigBuilder.new_with_websockets() - .with_clean_session(true) - .with_client_id("client_" + createId()) - .with_endpoint(endpoint) - .with_custom_authorizer("", authorizer, "", "PLACEHOLDER_TOKEN") - .with_keep_alive_seconds(1200) - .build(); - const client = new mqtt.MqttClient(); - connection = client.new_connection(config); - connection.on("connect", async () => { - console.log("WS connected"); - await connection.subscribe(topic, mqtt.QoS.AtLeastOnce); - console.log("WS subscribed to chat"); - }); - connection.on("interrupt", (e) => { - console.log("interrupted, restarting", e, JSON.stringify(e)); - createConnection(); - }); - connection.on("error", (e) => { - console.log("connection error", e); - }); - connection.on("resume", console.log); - connection.on("message", (_fullTopic, payload) => { - const message = new TextDecoder("utf8").decode(new Uint8Array(payload)); - addMessage(message); - }); - connection.on("disconnect", console.log); - await connection.connect(); -} -createConnection(); - -const addMessage = (message: string) => { - messages.push(message); - document.querySelector("#messages")!.innerHTML = messages - .map((m) => `
${m}
`) - .join(""); -}; - -document.querySelector("#app")!.innerHTML = ` -
-

Realtime Demo

-
-
- -
-
-`; - -const input = document.querySelector("#message")!; -input.addEventListener("keypress", (event: KeyboardEvent) => { - const message = input.value.trim(); - if (event.key === "Enter" && message.length > 0) { - connection.publish( - topic, - JSON.stringify({ message }), - mqtt.QoS.AtLeastOnce - ); - input.value = ""; - } -}); diff --git a/examples/aws-realtime/web/src/style.css b/examples/aws-realtime/web/src/style.css deleted file mode 100644 index f9c7350248..0000000000 --- a/examples/aws-realtime/web/src/style.css +++ /dev/null @@ -1,96 +0,0 @@ -:root { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - line-height: 1.5; - font-weight: 400; - - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; - - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; -} -a:hover { - color: #535bf2; -} - -body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; -} - -h1 { - font-size: 3.2em; - line-height: 1.1; -} - -#app { - max-width: 1280px; - margin: 0 auto; - padding: 2rem; - text-align: center; -} - -.logo { - height: 6em; - padding: 1.5em; - will-change: filter; - transition: filter 300ms; -} -.logo:hover { - filter: drop-shadow(0 0 2em #646cffaa); -} -.logo.vanilla:hover { - filter: drop-shadow(0 0 2em #3178c6aa); -} - -.card { - padding: 2em; -} - -.read-the-docs { - color: #888; -} - -button { - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; -} -button:hover { - border-color: #646cff; -} -button:focus, -button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; -} - -@media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } -} diff --git a/examples/aws-realtime/web/src/typescript.svg b/examples/aws-realtime/web/src/typescript.svg deleted file mode 100644 index d91c910cc3..0000000000 --- a/examples/aws-realtime/web/src/typescript.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-realtime/web/src/vite-env.d.ts b/examples/aws-realtime/web/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/aws-realtime/web/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/aws-realtime/web/tsconfig.json b/examples/aws-realtime/web/tsconfig.json deleted file mode 100644 index 75abdef265..0000000000 --- a/examples/aws-realtime/web/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "useDefineForClassFields": true, - "module": "ESNext", - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true - }, - "include": ["src"] -} diff --git a/examples/aws-redis-local/index.ts b/examples/aws-redis-local/index.ts deleted file mode 100644 index cebc9ce47b..0000000000 --- a/examples/aws-redis-local/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Redis, Cluster } from "ioredis"; -import { Resource } from "sst"; - -const client = - Resource.MyRedis.host === "localhost" - ? new Redis({ - host: Resource.MyRedis.host, - port: Resource.MyRedis.port, - }) - : new Cluster( - [{ - host: Resource.MyRedis.host, - port: Resource.MyRedis.port, - }], - { - redisOptions: { - tls: { checkServerIdentity: () => undefined }, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - }, - ); - -export async function handler() { - await client.set("foo", `bar-${Date.now()}`); - return { - statusCode: 200, - body: JSON.stringify({ - foo: await client.get("foo"), - }), - }; -} diff --git a/examples/aws-redis-local/package.json b/examples/aws-redis-local/package.json deleted file mode 100644 index 128e5439f7..0000000000 --- a/examples/aws-redis-local/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "aws-redis-local", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-redis-local/sst.config.ts b/examples/aws-redis-local/sst.config.ts deleted file mode 100644 index b32f069188..0000000000 --- a/examples/aws-redis-local/sst.config.ts +++ /dev/null @@ -1,89 +0,0 @@ -/// - -/** - * ## AWS Redis local - * - * In this example, we connect to a local Docker Redis instance for dev. While on deploy, we use - * Redis ElastiCache. - * - * We use the [`docker run`](https://docs.docker.com/reference/cli/docker/container/run/) CLI - * to start a local Redis server. You don't have to use Docker, you can run it locally any way - * you want. - * - * ```bash - * docker run \ - * --rm \ - * -p 6379:6379 \ - * -v $(pwd)/.sst/storage/redis:/data \ - * redis:latest - * ``` - * - * The data is persisted to the `.sst/storage` directory. So if you restart the dev server, - * the data will still be there. - * - * We then configure the `dev` property of the `Redis` component with the settings for the - * local Redis server. - * - * ```ts title="sst.config.ts" - * dev: { - * host: "localhost", - * port: 6379 - * } - * ``` - * - * By providing the `dev` prop for Redis, SST will use the local Redis server and - * not deploy a new Redis ElastiCache cluster when running `sst dev`. - * - * It also allows us to access Redis through a Resource `link`. - * - * ```ts title="index.ts" - * const client = Resource.MyRedis.host === "localhost" - * ? new Redis({ - * host: Resource.MyRedis.host, - * port: Resource.MyRedis.port, - * }) - * : new Cluster( - * [{ - * host: Resource.MyRedis.host, - * port: Resource.MyRedis.port, - * }], - * { - * redisOptions: { - * tls: { checkServerIdentity: () => undefined }, - * username: Resource.MyRedis.username, - * password: Resource.MyRedis.password, - * }, - * }, - * ); - * ``` - * - * The local Redis server is running in `standalone` mode, whereas on deploy it'll be in - * `cluster` mode. So our Lambda function needs to connect using the right config. - */ -export default $config({ - app(input) { - return { - name: "aws-redis-local", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "managed" }); - - const redis = new sst.aws.Redis("MyRedis", { - dev: { - host: "localhost", - port: 6379, - }, - vpc, - }); - - new sst.aws.Function("MyApp", { - vpc, - url: true, - link: [redis], - handler: "index.handler", - }); - }, -}); diff --git a/examples/aws-redis-local/tsconfig.json b/examples/aws-redis-local/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-redis-local/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-redis/index.ts b/examples/aws-redis/index.ts deleted file mode 100644 index 07da57201f..0000000000 --- a/examples/aws-redis/index.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { Cluster } from "ioredis"; -import { Resource } from "sst"; - -const client = new Cluster( - [ - { - host: Resource.MyRedis.host, - port: Resource.MyRedis.port, - }, - ], - { - redisOptions: { - tls: { - checkServerIdentity: () => undefined, - }, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -export async function handler() { - await client.set("foo", `bar-${Date.now()}`); - return { - statusCode: 200, - body: JSON.stringify({ - foo: await client.get("foo"), - }), - }; -} diff --git a/examples/aws-redis/package.json b/examples/aws-redis/package.json deleted file mode 100644 index b888afbfcc..0000000000 --- a/examples/aws-redis/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-redis", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-redis/sst.config.ts b/examples/aws-redis/sst.config.ts deleted file mode 100644 index ac7a05e258..0000000000 --- a/examples/aws-redis/sst.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // NAT Gateways are required for Lambda functions - const vpc = new sst.aws.Vpc("MyVpc", { nat: "managed" }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - new sst.aws.Function("MyApp", { - handler: "index.handler", - url: true, - vpc, - link: [redis], - }); - }, -}); diff --git a/examples/aws-remix-container/.dockerignore b/examples/aws-remix-container/.dockerignore deleted file mode 100644 index d0a41b0f28..0000000000 --- a/examples/aws-remix-container/.dockerignore +++ /dev/null @@ -1,7 +0,0 @@ -.git -.next -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-remix-container/.eslintrc.cjs b/examples/aws-remix-container/.eslintrc.cjs deleted file mode 100644 index 4f6f59eee1..0000000000 --- a/examples/aws-remix-container/.eslintrc.cjs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * This is intended to be a basic starting point for linting in your app. - * It relies on recommended configs out of the box for simplicity, but you can - * and should modify this configuration to best suit your team's needs. - */ - -/** @type {import('eslint').Linter.Config} */ -module.exports = { - root: true, - parserOptions: { - ecmaVersion: "latest", - sourceType: "module", - ecmaFeatures: { - jsx: true, - }, - }, - env: { - browser: true, - commonjs: true, - es6: true, - }, - ignorePatterns: ["!**/.server", "!**/.client"], - - // Base config - extends: ["eslint:recommended"], - - overrides: [ - // React - { - files: ["**/*.{js,jsx,ts,tsx}"], - plugins: ["react", "jsx-a11y"], - extends: [ - "plugin:react/recommended", - "plugin:react/jsx-runtime", - "plugin:react-hooks/recommended", - "plugin:jsx-a11y/recommended", - ], - settings: { - react: { - version: "detect", - }, - formComponents: ["Form"], - linkComponents: [ - { name: "Link", linkAttribute: "to" }, - { name: "NavLink", linkAttribute: "to" }, - ], - "import/resolver": { - typescript: {}, - }, - }, - }, - - // Typescript - { - files: ["**/*.{ts,tsx}"], - plugins: ["@typescript-eslint", "import"], - parser: "@typescript-eslint/parser", - settings: { - "import/internal-regex": "^~/", - "import/resolver": { - node: { - extensions: [".ts", ".tsx"], - }, - typescript: { - alwaysTryTypes: true, - }, - }, - }, - extends: [ - "plugin:@typescript-eslint/recommended", - "plugin:import/recommended", - "plugin:import/typescript", - ], - }, - - // Node - { - files: [".eslintrc.cjs"], - env: { - node: true, - }, - }, - ], -}; diff --git a/examples/aws-remix-container/.gitignore b/examples/aws-remix-container/.gitignore deleted file mode 100644 index 6a1b35d13a..0000000000 --- a/examples/aws-remix-container/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules - -/.cache -/build -.env - -# sst -.sst diff --git a/examples/aws-remix-container/Dockerfile b/examples/aws-remix-container/Dockerfile deleted file mode 100644 index c910cea1b6..0000000000 --- a/examples/aws-remix-container/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -# Based on https://github.com/remix-run/blues-stack/blob/main/Dockerfile - -FROM node:lts-alpine as base -ENV NODE_ENV production - -# Stage 1: Install all node_modules, including dev dependencies -FROM base as deps -WORKDIR /myapp -ADD package.json ./ -RUN npm install --include=dev - -# Stage 2: Setup production node_modules -FROM base as production-deps -WORKDIR /myapp -COPY --from=deps /myapp/node_modules /myapp/node_modules -ADD package.json ./ -RUN npm prune --omit=dev - -# Stage 3: Build the app -FROM base as build -WORKDIR /myapp -COPY --from=deps /myapp/node_modules /myapp/node_modules -ADD . . -RUN npm run build - -# Stage 4: Build the production image -FROM base -WORKDIR /myapp -COPY --from=production-deps /myapp/node_modules /myapp/node_modules -COPY --from=build /myapp/build /myapp/build -COPY --from=build /myapp/public /myapp/public -ADD . . - -CMD ["npm", "start"] diff --git a/examples/aws-remix-container/app/entry.client.tsx b/examples/aws-remix-container/app/entry.client.tsx deleted file mode 100644 index 94d5dc0de0..0000000000 --- a/examples/aws-remix-container/app/entry.client.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/** - * By default, Remix will handle hydrating your app on the client for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.client - */ - -import { RemixBrowser } from "@remix-run/react"; -import { startTransition, StrictMode } from "react"; -import { hydrateRoot } from "react-dom/client"; - -startTransition(() => { - hydrateRoot( - document, - - - - ); -}); diff --git a/examples/aws-remix-container/app/entry.server.tsx b/examples/aws-remix-container/app/entry.server.tsx deleted file mode 100644 index 45db3229c6..0000000000 --- a/examples/aws-remix-container/app/entry.server.tsx +++ /dev/null @@ -1,140 +0,0 @@ -/** - * By default, Remix will handle generating the HTTP Response for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.server - */ - -import { PassThrough } from "node:stream"; - -import type { AppLoadContext, EntryContext } from "@remix-run/node"; -import { createReadableStreamFromReadable } from "@remix-run/node"; -import { RemixServer } from "@remix-run/react"; -import { isbot } from "isbot"; -import { renderToPipeableStream } from "react-dom/server"; - -const ABORT_DELAY = 5_000; - -export default function handleRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext, - // This is ignored so we can keep it in the template for visibility. Feel - // free to delete this parameter in your app if you're not using it! - // eslint-disable-next-line @typescript-eslint/no-unused-vars - loadContext: AppLoadContext -) { - return isbot(request.headers.get("user-agent") || "") - ? handleBotRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ) - : handleBrowserRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ); -} - -function handleBotRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onAllReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} - -function handleBrowserRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onShellReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} diff --git a/examples/aws-remix-container/app/root.tsx b/examples/aws-remix-container/app/root.tsx deleted file mode 100644 index 61c8b983d2..0000000000 --- a/examples/aws-remix-container/app/root.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { - Links, - Meta, - Outlet, - Scripts, - ScrollRestoration, -} from "@remix-run/react"; -import type { LinksFunction } from "@remix-run/node"; - -import "./tailwind.css"; - -export const links: LinksFunction = () => [ - { rel: "preconnect", href: "https://fonts.googleapis.com" }, - { - rel: "preconnect", - href: "https://fonts.gstatic.com", - crossOrigin: "anonymous", - }, - { - rel: "stylesheet", - href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap", - }, -]; - -export function Layout({ children }: { children: React.ReactNode }) { - return ( - - - - - - - - - {children} - - - - - ); -} - -export default function App() { - return ; -} diff --git a/examples/aws-remix-container/app/routes/_index.tsx b/examples/aws-remix-container/app/routes/_index.tsx deleted file mode 100644 index 38db41f396..0000000000 --- a/examples/aws-remix-container/app/routes/_index.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import { Resource } from "sst"; -import { useLoaderData } from "@remix-run/react"; -import type { MetaFunction } from "@remix-run/node"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -export const meta: MetaFunction = () => { - return [ - { title: "New Remix App" }, - { name: "description", content: "Welcome to Remix!" }, - ]; -}; - -export async function loader() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return { url }; -} - -export default function Index() { - const data = useLoaderData(); - return ( -
-
-

- Welcome to Remix -

-
{ - e.preventDefault(); - - const file = (e.target as HTMLFormElement).file.files?.[0]!; - - const image = await fetch(data.url, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }} - > - - -
-
-
- ); -} diff --git a/examples/aws-remix-container/app/tailwind.css b/examples/aws-remix-container/app/tailwind.css deleted file mode 100644 index 303fe158fc..0000000000 --- a/examples/aws-remix-container/app/tailwind.css +++ /dev/null @@ -1,12 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -html, -body { - @apply bg-white dark:bg-gray-950; - - @media (prefers-color-scheme: dark) { - color-scheme: dark; - } -} diff --git a/examples/aws-remix-container/package.json b/examples/aws-remix-container/package.json deleted file mode 100644 index 8fdad703fa..0000000000 --- a/examples/aws-remix-container/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "aws-remix-container", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "remix vite:build", - "dev": "remix vite:dev", - "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .", - "start": "remix-serve ./build/server/index.js", - "typecheck": "tsc" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "@remix-run/node": "^2.15.0", - "@remix-run/react": "^2.15.0", - "@remix-run/serve": "^2.15.0", - "isbot": "^4.1.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@remix-run/dev": "^2.15.0", - "@types/react": "^18.2.20", - "@types/react-dom": "^18.2.7", - "@typescript-eslint/eslint-plugin": "^6.7.4", - "@typescript-eslint/parser": "^6.7.4", - "autoprefixer": "^10.4.19", - "eslint": "^8.38.0", - "eslint-import-resolver-typescript": "^3.6.1", - "eslint-plugin-import": "^2.28.1", - "eslint-plugin-jsx-a11y": "^6.7.1", - "eslint-plugin-react": "^7.33.2", - "eslint-plugin-react-hooks": "^4.6.0", - "postcss": "^8.4.38", - "tailwindcss": "^3.4.4", - "typescript": "^5.1.6", - "vite": "^5.1.0", - "vite-tsconfig-paths": "^4.2.1" - }, - "engines": { - "node": ">=20.0.0" - }, - "overrides": { - "valibot": "^0.41.0" - } -} diff --git a/examples/aws-remix-container/postcss.config.js b/examples/aws-remix-container/postcss.config.js deleted file mode 100644 index 2aa7205d4b..0000000000 --- a/examples/aws-remix-container/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -}; diff --git a/examples/aws-remix-container/public/favicon.ico b/examples/aws-remix-container/public/favicon.ico deleted file mode 100644 index 8830cf6821..0000000000 Binary files a/examples/aws-remix-container/public/favicon.ico and /dev/null differ diff --git a/examples/aws-remix-container/public/logo-dark.png b/examples/aws-remix-container/public/logo-dark.png deleted file mode 100644 index b24c7aee3a..0000000000 Binary files a/examples/aws-remix-container/public/logo-dark.png and /dev/null differ diff --git a/examples/aws-remix-container/public/logo-light.png b/examples/aws-remix-container/public/logo-light.png deleted file mode 100644 index 4490ae7930..0000000000 Binary files a/examples/aws-remix-container/public/logo-light.png and /dev/null differ diff --git a/examples/aws-remix-container/sst.config.ts b/examples/aws-remix-container/sst.config.ts deleted file mode 100644 index 9f55a2d505..0000000000 --- a/examples/aws-remix-container/sst.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-remix-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-remix-container/tailwind.config.ts b/examples/aws-remix-container/tailwind.config.ts deleted file mode 100644 index 5f06ad4ba5..0000000000 --- a/examples/aws-remix-container/tailwind.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { Config } from "tailwindcss"; - -export default { - content: ["./app/**/{**,.client,.server}/**/*.{js,jsx,ts,tsx}"], - theme: { - extend: { - fontFamily: { - sans: [ - "Inter", - "ui-sans-serif", - "system-ui", - "sans-serif", - "Apple Color Emoji", - "Segoe UI Emoji", - "Segoe UI Symbol", - "Noto Color Emoji", - ], - }, - }, - }, - plugins: [], -} satisfies Config; diff --git a/examples/aws-remix-container/tsconfig.json b/examples/aws-remix-container/tsconfig.json deleted file mode 100644 index 9d87dd378f..0000000000 --- a/examples/aws-remix-container/tsconfig.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "include": [ - "**/*.ts", - "**/*.tsx", - "**/.server/**/*.ts", - "**/.server/**/*.tsx", - "**/.client/**/*.ts", - "**/.client/**/*.tsx" - ], - "compilerOptions": { - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "types": ["@remix-run/node", "vite/client"], - "isolatedModules": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "resolveJsonModule": true, - "target": "ES2022", - "strict": true, - "allowJs": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./app/*"] - }, - - // Vite takes care of building everything, not tsc. - "noEmit": true - } -} diff --git a/examples/aws-remix-container/vite.config.ts b/examples/aws-remix-container/vite.config.ts deleted file mode 100644 index e4e8cefc3b..0000000000 --- a/examples/aws-remix-container/vite.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { vitePlugin as remix } from "@remix-run/dev"; -import { defineConfig } from "vite"; -import tsconfigPaths from "vite-tsconfig-paths"; - -declare module "@remix-run/node" { - interface Future { - v3_singleFetch: true; - } -} - -export default defineConfig({ - plugins: [ - remix({ - future: { - v3_fetcherPersist: true, - v3_relativeSplatPath: true, - v3_throwAbortReason: true, - v3_singleFetch: true, - v3_lazyRouteDiscovery: true, - }, - }), - tsconfigPaths(), - ], -}); diff --git a/examples/aws-remix-redis/.dockerignore b/examples/aws-remix-redis/.dockerignore deleted file mode 100644 index 25316b7aa8..0000000000 --- a/examples/aws-remix-redis/.dockerignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules -.cache -build -public/build - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-remix-redis/.eslintrc.cjs b/examples/aws-remix-redis/.eslintrc.cjs deleted file mode 100644 index 4f6f59eee1..0000000000 --- a/examples/aws-remix-redis/.eslintrc.cjs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * This is intended to be a basic starting point for linting in your app. - * It relies on recommended configs out of the box for simplicity, but you can - * and should modify this configuration to best suit your team's needs. - */ - -/** @type {import('eslint').Linter.Config} */ -module.exports = { - root: true, - parserOptions: { - ecmaVersion: "latest", - sourceType: "module", - ecmaFeatures: { - jsx: true, - }, - }, - env: { - browser: true, - commonjs: true, - es6: true, - }, - ignorePatterns: ["!**/.server", "!**/.client"], - - // Base config - extends: ["eslint:recommended"], - - overrides: [ - // React - { - files: ["**/*.{js,jsx,ts,tsx}"], - plugins: ["react", "jsx-a11y"], - extends: [ - "plugin:react/recommended", - "plugin:react/jsx-runtime", - "plugin:react-hooks/recommended", - "plugin:jsx-a11y/recommended", - ], - settings: { - react: { - version: "detect", - }, - formComponents: ["Form"], - linkComponents: [ - { name: "Link", linkAttribute: "to" }, - { name: "NavLink", linkAttribute: "to" }, - ], - "import/resolver": { - typescript: {}, - }, - }, - }, - - // Typescript - { - files: ["**/*.{ts,tsx}"], - plugins: ["@typescript-eslint", "import"], - parser: "@typescript-eslint/parser", - settings: { - "import/internal-regex": "^~/", - "import/resolver": { - node: { - extensions: [".ts", ".tsx"], - }, - typescript: { - alwaysTryTypes: true, - }, - }, - }, - extends: [ - "plugin:@typescript-eslint/recommended", - "plugin:import/recommended", - "plugin:import/typescript", - ], - }, - - // Node - { - files: [".eslintrc.cjs"], - env: { - node: true, - }, - }, - ], -}; diff --git a/examples/aws-remix-redis/.gitignore b/examples/aws-remix-redis/.gitignore deleted file mode 100644 index 6a1b35d13a..0000000000 --- a/examples/aws-remix-redis/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules - -/.cache -/build -.env - -# sst -.sst diff --git a/examples/aws-remix-redis/Dockerfile b/examples/aws-remix-redis/Dockerfile deleted file mode 100644 index 026c033291..0000000000 --- a/examples/aws-remix-redis/Dockerfile +++ /dev/null @@ -1,45 +0,0 @@ -# base node image -FROM node:18-bullseye-slim as base - -# set for base and all layer that inherit from it -ENV NODE_ENV production - -# Install all node_modules, including dev dependencies -FROM base as deps - -WORKDIR /myapp - -ADD package.json ./ -RUN npm install --include=dev - -# Setup production node_modules -FROM base as production-deps - -WORKDIR /myapp - -COPY --from=deps /myapp/node_modules /myapp/node_modules -ADD package.json ./ -RUN npm prune --omit=dev - -# Build the app -FROM base as build - -WORKDIR /myapp - -COPY --from=deps /myapp/node_modules /myapp/node_modules - -ADD . . -RUN npm run build - -# Finally, build the production image with minimal footprint -FROM base - -WORKDIR /myapp - -COPY --from=production-deps /myapp/node_modules /myapp/node_modules - -COPY --from=build /myapp/build /myapp/build -COPY --from=build /myapp/public /myapp/public -ADD . . - -CMD ["npm", "start"] diff --git a/examples/aws-remix-redis/app/entry.client.tsx b/examples/aws-remix-redis/app/entry.client.tsx deleted file mode 100644 index 94d5dc0de0..0000000000 --- a/examples/aws-remix-redis/app/entry.client.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/** - * By default, Remix will handle hydrating your app on the client for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.client - */ - -import { RemixBrowser } from "@remix-run/react"; -import { startTransition, StrictMode } from "react"; -import { hydrateRoot } from "react-dom/client"; - -startTransition(() => { - hydrateRoot( - document, - - - - ); -}); diff --git a/examples/aws-remix-redis/app/entry.server.tsx b/examples/aws-remix-redis/app/entry.server.tsx deleted file mode 100644 index 45db3229c6..0000000000 --- a/examples/aws-remix-redis/app/entry.server.tsx +++ /dev/null @@ -1,140 +0,0 @@ -/** - * By default, Remix will handle generating the HTTP Response for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.server - */ - -import { PassThrough } from "node:stream"; - -import type { AppLoadContext, EntryContext } from "@remix-run/node"; -import { createReadableStreamFromReadable } from "@remix-run/node"; -import { RemixServer } from "@remix-run/react"; -import { isbot } from "isbot"; -import { renderToPipeableStream } from "react-dom/server"; - -const ABORT_DELAY = 5_000; - -export default function handleRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext, - // This is ignored so we can keep it in the template for visibility. Feel - // free to delete this parameter in your app if you're not using it! - // eslint-disable-next-line @typescript-eslint/no-unused-vars - loadContext: AppLoadContext -) { - return isbot(request.headers.get("user-agent") || "") - ? handleBotRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ) - : handleBrowserRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ); -} - -function handleBotRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onAllReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} - -function handleBrowserRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onShellReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} diff --git a/examples/aws-remix-redis/app/root.tsx b/examples/aws-remix-redis/app/root.tsx deleted file mode 100644 index 61c8b983d2..0000000000 --- a/examples/aws-remix-redis/app/root.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { - Links, - Meta, - Outlet, - Scripts, - ScrollRestoration, -} from "@remix-run/react"; -import type { LinksFunction } from "@remix-run/node"; - -import "./tailwind.css"; - -export const links: LinksFunction = () => [ - { rel: "preconnect", href: "https://fonts.googleapis.com" }, - { - rel: "preconnect", - href: "https://fonts.gstatic.com", - crossOrigin: "anonymous", - }, - { - rel: "stylesheet", - href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap", - }, -]; - -export function Layout({ children }: { children: React.ReactNode }) { - return ( - - - - - - - - - {children} - - - - - ); -} - -export default function App() { - return ; -} diff --git a/examples/aws-remix-redis/app/routes/_index.tsx b/examples/aws-remix-redis/app/routes/_index.tsx deleted file mode 100644 index b5be858188..0000000000 --- a/examples/aws-remix-redis/app/routes/_index.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; -import { json } from "@remix-run/node"; -import type { MetaFunction } from "@remix-run/node"; -import { useLoaderData } from "@remix-run/react"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -export const meta: MetaFunction = () => { - return [ - { title: "New Remix App" }, - { name: "description", content: "Welcome to Remix!" }, - ]; -}; - -export async function loader() { - const counter = await redis.incr("counter"); - - return json({ counter }); -} - -export default function Index() { - const data = useLoaderData(); - return ( -

- Hit counter: {data.counter} -

- ); -} diff --git a/examples/aws-remix-redis/app/tailwind.css b/examples/aws-remix-redis/app/tailwind.css deleted file mode 100644 index 303fe158fc..0000000000 --- a/examples/aws-remix-redis/app/tailwind.css +++ /dev/null @@ -1,12 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -html, -body { - @apply bg-white dark:bg-gray-950; - - @media (prefers-color-scheme: dark) { - color-scheme: dark; - } -} diff --git a/examples/aws-remix-redis/package.json b/examples/aws-remix-redis/package.json deleted file mode 100644 index 22a6d322b2..0000000000 --- a/examples/aws-remix-redis/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "aws-remix-redis", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "remix vite:build", - "dev": "remix vite:dev", - "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .", - "start": "remix-serve ./build/server/index.js", - "typecheck": "tsc" - }, - "dependencies": { - "@remix-run/node": "^2.12.1", - "@remix-run/react": "^2.12.1", - "@remix-run/serve": "^2.12.1", - "ioredis": "^5.4.1", - "isbot": "^4.1.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@remix-run/dev": "^2.12.1", - "@types/react": "^18.2.20", - "@types/react-dom": "^18.2.7", - "@typescript-eslint/eslint-plugin": "^6.7.4", - "@typescript-eslint/parser": "^6.7.4", - "autoprefixer": "^10.4.19", - "eslint": "^8.38.0", - "eslint-import-resolver-typescript": "^3.6.1", - "eslint-plugin-import": "^2.28.1", - "eslint-plugin-jsx-a11y": "^6.7.1", - "eslint-plugin-react": "^7.33.2", - "eslint-plugin-react-hooks": "^4.6.0", - "postcss": "^8.4.38", - "tailwindcss": "^3.4.4", - "typescript": "^5.1.6", - "vite": "^5.1.0", - "vite-tsconfig-paths": "^4.2.1" - }, - "engines": { - "node": ">=20.0.0" - } -} diff --git a/examples/aws-remix-redis/postcss.config.js b/examples/aws-remix-redis/postcss.config.js deleted file mode 100644 index 2aa7205d4b..0000000000 --- a/examples/aws-remix-redis/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -}; diff --git a/examples/aws-remix-redis/public/favicon.ico b/examples/aws-remix-redis/public/favicon.ico deleted file mode 100644 index 8830cf6821..0000000000 Binary files a/examples/aws-remix-redis/public/favicon.ico and /dev/null differ diff --git a/examples/aws-remix-redis/public/logo-dark.png b/examples/aws-remix-redis/public/logo-dark.png deleted file mode 100644 index b24c7aee3a..0000000000 Binary files a/examples/aws-remix-redis/public/logo-dark.png and /dev/null differ diff --git a/examples/aws-remix-redis/public/logo-light.png b/examples/aws-remix-redis/public/logo-light.png deleted file mode 100644 index 4490ae7930..0000000000 Binary files a/examples/aws-remix-redis/public/logo-light.png and /dev/null differ diff --git a/examples/aws-remix-redis/sst.config.ts b/examples/aws-remix-redis/sst.config.ts deleted file mode 100644 index 8abd9c423f..0000000000 --- a/examples/aws-remix-redis/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## AWS Remix container with Redis - * - * Creates a hit counter app with Remix and Redis. - * - * This deploys Remix as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "npm run dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:5173` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it by adding the `Dockerfile` that's included in this example and - * running `npx sst deploy --stage production`. - */ -export default $config({ - app(input) { - return { - name: "aws-remix-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-remix-redis/tailwind.config.ts b/examples/aws-remix-redis/tailwind.config.ts deleted file mode 100644 index 14d0f00ce6..0000000000 --- a/examples/aws-remix-redis/tailwind.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { Config } from "tailwindcss"; - -export default { - content: ["./app/**/{**,.client,.server}/**/*.{js,jsx,ts,tsx}"], - theme: { - extend: { - fontFamily: { - sans: [ - '"Inter"', - "ui-sans-serif", - "system-ui", - "sans-serif", - '"Apple Color Emoji"', - '"Segoe UI Emoji"', - '"Segoe UI Symbol"', - '"Noto Color Emoji"', - ], - }, - }, - }, - plugins: [], -} satisfies Config; diff --git a/examples/aws-remix-redis/tsconfig.json b/examples/aws-remix-redis/tsconfig.json deleted file mode 100644 index 9d87dd378f..0000000000 --- a/examples/aws-remix-redis/tsconfig.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "include": [ - "**/*.ts", - "**/*.tsx", - "**/.server/**/*.ts", - "**/.server/**/*.tsx", - "**/.client/**/*.ts", - "**/.client/**/*.tsx" - ], - "compilerOptions": { - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "types": ["@remix-run/node", "vite/client"], - "isolatedModules": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "resolveJsonModule": true, - "target": "ES2022", - "strict": true, - "allowJs": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./app/*"] - }, - - // Vite takes care of building everything, not tsc. - "noEmit": true - } -} diff --git a/examples/aws-remix-redis/vite.config.ts b/examples/aws-remix-redis/vite.config.ts deleted file mode 100644 index 54066fb7ad..0000000000 --- a/examples/aws-remix-redis/vite.config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { vitePlugin as remix } from "@remix-run/dev"; -import { defineConfig } from "vite"; -import tsconfigPaths from "vite-tsconfig-paths"; - -export default defineConfig({ - plugins: [ - remix({ - future: { - v3_fetcherPersist: true, - v3_relativeSplatPath: true, - v3_throwAbortReason: true, - }, - }), - tsconfigPaths(), - ], -}); diff --git a/examples/aws-remix-stream/.eslintrc.cjs b/examples/aws-remix-stream/.eslintrc.cjs deleted file mode 100644 index 4f6f59eee1..0000000000 --- a/examples/aws-remix-stream/.eslintrc.cjs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * This is intended to be a basic starting point for linting in your app. - * It relies on recommended configs out of the box for simplicity, but you can - * and should modify this configuration to best suit your team's needs. - */ - -/** @type {import('eslint').Linter.Config} */ -module.exports = { - root: true, - parserOptions: { - ecmaVersion: "latest", - sourceType: "module", - ecmaFeatures: { - jsx: true, - }, - }, - env: { - browser: true, - commonjs: true, - es6: true, - }, - ignorePatterns: ["!**/.server", "!**/.client"], - - // Base config - extends: ["eslint:recommended"], - - overrides: [ - // React - { - files: ["**/*.{js,jsx,ts,tsx}"], - plugins: ["react", "jsx-a11y"], - extends: [ - "plugin:react/recommended", - "plugin:react/jsx-runtime", - "plugin:react-hooks/recommended", - "plugin:jsx-a11y/recommended", - ], - settings: { - react: { - version: "detect", - }, - formComponents: ["Form"], - linkComponents: [ - { name: "Link", linkAttribute: "to" }, - { name: "NavLink", linkAttribute: "to" }, - ], - "import/resolver": { - typescript: {}, - }, - }, - }, - - // Typescript - { - files: ["**/*.{ts,tsx}"], - plugins: ["@typescript-eslint", "import"], - parser: "@typescript-eslint/parser", - settings: { - "import/internal-regex": "^~/", - "import/resolver": { - node: { - extensions: [".ts", ".tsx"], - }, - typescript: { - alwaysTryTypes: true, - }, - }, - }, - extends: [ - "plugin:@typescript-eslint/recommended", - "plugin:import/recommended", - "plugin:import/typescript", - ], - }, - - // Node - { - files: [".eslintrc.cjs"], - env: { - node: true, - }, - }, - ], -}; diff --git a/examples/aws-remix-stream/.gitignore b/examples/aws-remix-stream/.gitignore deleted file mode 100644 index 6a1b35d13a..0000000000 --- a/examples/aws-remix-stream/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules - -/.cache -/build -.env - -# sst -.sst diff --git a/examples/aws-remix-stream/app/entry.client.tsx b/examples/aws-remix-stream/app/entry.client.tsx deleted file mode 100644 index 94d5dc0de0..0000000000 --- a/examples/aws-remix-stream/app/entry.client.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/** - * By default, Remix will handle hydrating your app on the client for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.client - */ - -import { RemixBrowser } from "@remix-run/react"; -import { startTransition, StrictMode } from "react"; -import { hydrateRoot } from "react-dom/client"; - -startTransition(() => { - hydrateRoot( - document, - - - - ); -}); diff --git a/examples/aws-remix-stream/app/entry.server.tsx b/examples/aws-remix-stream/app/entry.server.tsx deleted file mode 100644 index 45db3229c6..0000000000 --- a/examples/aws-remix-stream/app/entry.server.tsx +++ /dev/null @@ -1,140 +0,0 @@ -/** - * By default, Remix will handle generating the HTTP Response for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.server - */ - -import { PassThrough } from "node:stream"; - -import type { AppLoadContext, EntryContext } from "@remix-run/node"; -import { createReadableStreamFromReadable } from "@remix-run/node"; -import { RemixServer } from "@remix-run/react"; -import { isbot } from "isbot"; -import { renderToPipeableStream } from "react-dom/server"; - -const ABORT_DELAY = 5_000; - -export default function handleRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext, - // This is ignored so we can keep it in the template for visibility. Feel - // free to delete this parameter in your app if you're not using it! - // eslint-disable-next-line @typescript-eslint/no-unused-vars - loadContext: AppLoadContext -) { - return isbot(request.headers.get("user-agent") || "") - ? handleBotRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ) - : handleBrowserRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ); -} - -function handleBotRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onAllReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} - -function handleBrowserRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onShellReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} diff --git a/examples/aws-remix-stream/app/root.tsx b/examples/aws-remix-stream/app/root.tsx deleted file mode 100644 index e82f26fd17..0000000000 --- a/examples/aws-remix-stream/app/root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Links, - Meta, - Outlet, - Scripts, - ScrollRestoration, -} from "@remix-run/react"; - -export function Layout({ children }: { children: React.ReactNode }) { - return ( - - - - - - - - - {children} - - - - - ); -} - -export default function App() { - return ; -} diff --git a/examples/aws-remix-stream/app/routes/_index.tsx b/examples/aws-remix-stream/app/routes/_index.tsx deleted file mode 100644 index df765aae81..0000000000 --- a/examples/aws-remix-stream/app/routes/_index.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import { Suspense } from "react"; -import { Await, useLoaderData } from "@remix-run/react"; -import { defer, LoaderFunction } from "@remix-run/node"; -import styles from "~/styles/index.css?url"; - -export const links = () => [ - { rel: "stylesheet", href: styles }, -]; - -interface Character { - name: string; - image: string; - description?: string; -} - -interface LoaderData { - spongebob: Character; - friends: Character[]; -} - -export const loader: LoaderFunction = async () => { - const spongebob = { - name: "SpongeBob SquarePants", - description: "SpongeBob SquarePants is the main character of the popular animated TV series. He's a cheerful sea sponge who lives in a pineapple house in the underwater city of Bikini Bottom. SpongeBob works as a fry cook at the Krusty Krab and loves jellyfishing with his best friend Patrick Star.", - image: "spongebob.png", - }; - const friendsPromise = new Promise((resolve) => { - setTimeout(() => { - resolve( - [ - { name: "Patrick Star", image: "patrick.png" }, - { name: "Sandy Cheeks", image: "sandy.png" }, - { name: "Squidward Tentacles", image: "squidward.png" }, - { name: "Mr. Krabs", image: "mr-krabs.png" }, - ] - ); - }, 3000); - }); - - return defer({ - spongebob, - friends: friendsPromise, - }); -}; - -export default function Index() { - const { spongebob, friends } = useLoaderData(); - - return ( -
-
-

{spongebob.name}

-
-
-

{spongebob.description}

-
- {spongebob.name} -
-
- -
-

Friends from Bikini Bottom

- Loading...
}> - - {(friends) => ( -
- {friends.map((friend) => ( -
- {friend.name} -

{friend.name}

-
- ))} -
- )} -
- - - - ); -} diff --git a/examples/aws-remix-stream/app/styles/index.css b/examples/aws-remix-stream/app/styles/index.css deleted file mode 100644 index 8e562771e4..0000000000 --- a/examples/aws-remix-stream/app/styles/index.css +++ /dev/null @@ -1,41 +0,0 @@ -body { - font-family: Arial, sans-serif; - margin: 0; - padding: 0; - background-color: #f0f8ff; -} -.container { - max-width: 800px; - margin: 0 auto; - padding: 20px; -} -.bio-section { - background-color: #fff; - padding: 20px; - margin-bottom: 20px; - border-radius: 10px; -} -.bio-content { - display: flex; - align-items: center; -} -.bio-text { - flex: 1; - padding-right: 20px; -} -.character-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); - gap: 20px; -} -.character-card { - background-color: #fff; - padding: 10px; - border-radius: 5px; - text-align: center; -} -img { - max-width: 100%; - height: auto; - border-radius: 5px; -} diff --git a/examples/aws-remix-stream/package.json b/examples/aws-remix-stream/package.json deleted file mode 100644 index b3f71965b1..0000000000 --- a/examples/aws-remix-stream/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "aws-remix-stream", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "remix vite:build", - "dev": "remix vite:dev", - "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .", - "start": "remix-serve ./build/server/index.js", - "typecheck": "tsc" - }, - "dependencies": { - "@remix-run/node": "^2.12.1", - "@remix-run/react": "^2.12.1", - "@remix-run/serve": "^2.12.1", - "isbot": "^4.1.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@remix-run/dev": "^2.12.1", - "@types/react": "^18.2.20", - "@types/react-dom": "^18.2.7", - "@typescript-eslint/eslint-plugin": "^6.7.4", - "@typescript-eslint/parser": "^6.7.4", - "eslint": "^8.38.0", - "eslint-import-resolver-typescript": "^3.6.1", - "eslint-plugin-import": "^2.28.1", - "eslint-plugin-jsx-a11y": "^6.7.1", - "eslint-plugin-react": "^7.33.2", - "eslint-plugin-react-hooks": "^4.6.0", - "typescript": "^5.1.6", - "vite": "^5.1.0", - "vite-tsconfig-paths": "^4.2.1" - }, - "engines": { - "node": ">=18.0.0" - } -} diff --git a/examples/aws-remix-stream/public/favicon.ico b/examples/aws-remix-stream/public/favicon.ico deleted file mode 100644 index 8830cf6821..0000000000 Binary files a/examples/aws-remix-stream/public/favicon.ico and /dev/null differ diff --git a/examples/aws-remix-stream/public/mr-krabs.png b/examples/aws-remix-stream/public/mr-krabs.png deleted file mode 100644 index e94ea64054..0000000000 Binary files a/examples/aws-remix-stream/public/mr-krabs.png and /dev/null differ diff --git a/examples/aws-remix-stream/public/patrick.png b/examples/aws-remix-stream/public/patrick.png deleted file mode 100644 index 030eaaf8a3..0000000000 Binary files a/examples/aws-remix-stream/public/patrick.png and /dev/null differ diff --git a/examples/aws-remix-stream/public/sandy.png b/examples/aws-remix-stream/public/sandy.png deleted file mode 100644 index eb7a9cc324..0000000000 Binary files a/examples/aws-remix-stream/public/sandy.png and /dev/null differ diff --git a/examples/aws-remix-stream/public/spongebob.png b/examples/aws-remix-stream/public/spongebob.png deleted file mode 100644 index 18f7df537e..0000000000 Binary files a/examples/aws-remix-stream/public/spongebob.png and /dev/null differ diff --git a/examples/aws-remix-stream/public/squidward.png b/examples/aws-remix-stream/public/squidward.png deleted file mode 100644 index 4af85e000b..0000000000 Binary files a/examples/aws-remix-stream/public/squidward.png and /dev/null differ diff --git a/examples/aws-remix-stream/sst.config.ts b/examples/aws-remix-stream/sst.config.ts deleted file mode 100644 index 23d914db47..0000000000 --- a/examples/aws-remix-stream/sst.config.ts +++ /dev/null @@ -1,52 +0,0 @@ -/// - -/** - * ## AWS Remix streaming - * - * Follows the [Remix Streaming](https://remix.run/docs/en/main/guides/streaming) guide to create - * an app that streams data. - * - * Uses the `defer` utility to stream data through the `loader` function. - * - * ```tsx title="app/routes/_index.tsx" - * return defer({ - * spongebob, - * friends: friendsPromise, - * }); - * ``` - * - * Then uses the the `Suspense` and `Await` components to render the data. - * - * ```tsx title="app/routes/_index.tsx" - * Loading...}> - * - * { /* ... *\/ } - * - * - * ``` - * - * You should see the _friends_ section load after a 3 second delay. - * - * :::note - * Safari handles streaming differently than other browsers. - * ::: - * - * Safari uses a [different heuristic](https://bugs.webkit.org/show_bug.cgi?id=252413) to - * determine when to stream data. You need to render _enough_ initial HTML to trigger streaming. - * This is typically only a problem for demo apps. - * - * Streaming works out of the box with the `Remix` component. - * - */ -export default $config({ - app(input) { - return { - name: "aws-remix-stream", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.Remix("MyWeb"); - }, -}); diff --git a/examples/aws-remix-stream/tsconfig.json b/examples/aws-remix-stream/tsconfig.json deleted file mode 100644 index 9d87dd378f..0000000000 --- a/examples/aws-remix-stream/tsconfig.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "include": [ - "**/*.ts", - "**/*.tsx", - "**/.server/**/*.ts", - "**/.server/**/*.tsx", - "**/.client/**/*.ts", - "**/.client/**/*.tsx" - ], - "compilerOptions": { - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "types": ["@remix-run/node", "vite/client"], - "isolatedModules": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "resolveJsonModule": true, - "target": "ES2022", - "strict": true, - "allowJs": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./app/*"] - }, - - // Vite takes care of building everything, not tsc. - "noEmit": true - } -} diff --git a/examples/aws-remix-stream/vite.config.ts b/examples/aws-remix-stream/vite.config.ts deleted file mode 100644 index 2b6aff9872..0000000000 --- a/examples/aws-remix-stream/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { vitePlugin as remix } from "@remix-run/dev"; -import { installGlobals } from "@remix-run/node"; -import { defineConfig } from "vite"; -import tsconfigPaths from "vite-tsconfig-paths"; - -installGlobals(); - -export default defineConfig({ - plugins: [remix(), tsconfigPaths()], -}); diff --git a/examples/aws-remix/.eslintrc.cjs b/examples/aws-remix/.eslintrc.cjs deleted file mode 100644 index 4f6f59eee1..0000000000 --- a/examples/aws-remix/.eslintrc.cjs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * This is intended to be a basic starting point for linting in your app. - * It relies on recommended configs out of the box for simplicity, but you can - * and should modify this configuration to best suit your team's needs. - */ - -/** @type {import('eslint').Linter.Config} */ -module.exports = { - root: true, - parserOptions: { - ecmaVersion: "latest", - sourceType: "module", - ecmaFeatures: { - jsx: true, - }, - }, - env: { - browser: true, - commonjs: true, - es6: true, - }, - ignorePatterns: ["!**/.server", "!**/.client"], - - // Base config - extends: ["eslint:recommended"], - - overrides: [ - // React - { - files: ["**/*.{js,jsx,ts,tsx}"], - plugins: ["react", "jsx-a11y"], - extends: [ - "plugin:react/recommended", - "plugin:react/jsx-runtime", - "plugin:react-hooks/recommended", - "plugin:jsx-a11y/recommended", - ], - settings: { - react: { - version: "detect", - }, - formComponents: ["Form"], - linkComponents: [ - { name: "Link", linkAttribute: "to" }, - { name: "NavLink", linkAttribute: "to" }, - ], - "import/resolver": { - typescript: {}, - }, - }, - }, - - // Typescript - { - files: ["**/*.{ts,tsx}"], - plugins: ["@typescript-eslint", "import"], - parser: "@typescript-eslint/parser", - settings: { - "import/internal-regex": "^~/", - "import/resolver": { - node: { - extensions: [".ts", ".tsx"], - }, - typescript: { - alwaysTryTypes: true, - }, - }, - }, - extends: [ - "plugin:@typescript-eslint/recommended", - "plugin:import/recommended", - "plugin:import/typescript", - ], - }, - - // Node - { - files: [".eslintrc.cjs"], - env: { - node: true, - }, - }, - ], -}; diff --git a/examples/aws-remix/.gitignore b/examples/aws-remix/.gitignore deleted file mode 100644 index 6a1b35d13a..0000000000 --- a/examples/aws-remix/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules - -/.cache -/build -.env - -# sst -.sst diff --git a/examples/aws-remix/app/entry.client.tsx b/examples/aws-remix/app/entry.client.tsx deleted file mode 100644 index 94d5dc0de0..0000000000 --- a/examples/aws-remix/app/entry.client.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/** - * By default, Remix will handle hydrating your app on the client for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.client - */ - -import { RemixBrowser } from "@remix-run/react"; -import { startTransition, StrictMode } from "react"; -import { hydrateRoot } from "react-dom/client"; - -startTransition(() => { - hydrateRoot( - document, - - - - ); -}); diff --git a/examples/aws-remix/app/entry.server.tsx b/examples/aws-remix/app/entry.server.tsx deleted file mode 100644 index 45db3229c6..0000000000 --- a/examples/aws-remix/app/entry.server.tsx +++ /dev/null @@ -1,140 +0,0 @@ -/** - * By default, Remix will handle generating the HTTP Response for you. - * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ - * For more information, see https://remix.run/file-conventions/entry.server - */ - -import { PassThrough } from "node:stream"; - -import type { AppLoadContext, EntryContext } from "@remix-run/node"; -import { createReadableStreamFromReadable } from "@remix-run/node"; -import { RemixServer } from "@remix-run/react"; -import { isbot } from "isbot"; -import { renderToPipeableStream } from "react-dom/server"; - -const ABORT_DELAY = 5_000; - -export default function handleRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext, - // This is ignored so we can keep it in the template for visibility. Feel - // free to delete this parameter in your app if you're not using it! - // eslint-disable-next-line @typescript-eslint/no-unused-vars - loadContext: AppLoadContext -) { - return isbot(request.headers.get("user-agent") || "") - ? handleBotRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ) - : handleBrowserRequest( - request, - responseStatusCode, - responseHeaders, - remixContext - ); -} - -function handleBotRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onAllReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} - -function handleBrowserRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - remixContext: EntryContext -) { - return new Promise((resolve, reject) => { - let shellRendered = false; - const { pipe, abort } = renderToPipeableStream( - , - { - onShellReady() { - shellRendered = true; - const body = new PassThrough(); - const stream = createReadableStreamFromReadable(body); - - responseHeaders.set("Content-Type", "text/html"); - - resolve( - new Response(stream, { - headers: responseHeaders, - status: responseStatusCode, - }) - ); - - pipe(body); - }, - onShellError(error: unknown) { - reject(error); - }, - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - - setTimeout(abort, ABORT_DELAY); - }); -} diff --git a/examples/aws-remix/app/root.tsx b/examples/aws-remix/app/root.tsx deleted file mode 100644 index 61c8b983d2..0000000000 --- a/examples/aws-remix/app/root.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { - Links, - Meta, - Outlet, - Scripts, - ScrollRestoration, -} from "@remix-run/react"; -import type { LinksFunction } from "@remix-run/node"; - -import "./tailwind.css"; - -export const links: LinksFunction = () => [ - { rel: "preconnect", href: "https://fonts.googleapis.com" }, - { - rel: "preconnect", - href: "https://fonts.gstatic.com", - crossOrigin: "anonymous", - }, - { - rel: "stylesheet", - href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap", - }, -]; - -export function Layout({ children }: { children: React.ReactNode }) { - return ( - - - - - - - - - {children} - - - - - ); -} - -export default function App() { - return ; -} diff --git a/examples/aws-remix/app/routes/_index.tsx b/examples/aws-remix/app/routes/_index.tsx deleted file mode 100644 index 38db41f396..0000000000 --- a/examples/aws-remix/app/routes/_index.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import { Resource } from "sst"; -import { useLoaderData } from "@remix-run/react"; -import type { MetaFunction } from "@remix-run/node"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -export const meta: MetaFunction = () => { - return [ - { title: "New Remix App" }, - { name: "description", content: "Welcome to Remix!" }, - ]; -}; - -export async function loader() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return { url }; -} - -export default function Index() { - const data = useLoaderData(); - return ( -
-
-

- Welcome to Remix -

-
{ - e.preventDefault(); - - const file = (e.target as HTMLFormElement).file.files?.[0]!; - - const image = await fetch(data.url, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }} - > - - -
-
-
- ); -} diff --git a/examples/aws-remix/app/tailwind.css b/examples/aws-remix/app/tailwind.css deleted file mode 100644 index 303fe158fc..0000000000 --- a/examples/aws-remix/app/tailwind.css +++ /dev/null @@ -1,12 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -html, -body { - @apply bg-white dark:bg-gray-950; - - @media (prefers-color-scheme: dark) { - color-scheme: dark; - } -} diff --git a/examples/aws-remix/package.json b/examples/aws-remix/package.json deleted file mode 100644 index b0cc925225..0000000000 --- a/examples/aws-remix/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "aws-remix", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "remix vite:build", - "dev": "remix vite:dev", - "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .", - "start": "remix-serve ./build/server/index.js", - "typecheck": "tsc" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.699.0", - "@aws-sdk/s3-request-presigner": "^3.699.0", - "@remix-run/node": "^2.15.0", - "@remix-run/react": "^2.15.0", - "@remix-run/serve": "^2.15.0", - "isbot": "^4.1.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@remix-run/dev": "^2.15.0", - "@types/react": "^18.2.20", - "@types/react-dom": "^18.2.7", - "@typescript-eslint/eslint-plugin": "^6.7.4", - "@typescript-eslint/parser": "^6.7.4", - "autoprefixer": "^10.4.19", - "eslint": "^8.38.0", - "eslint-import-resolver-typescript": "^3.6.1", - "eslint-plugin-import": "^2.28.1", - "eslint-plugin-jsx-a11y": "^6.7.1", - "eslint-plugin-react": "^7.33.2", - "eslint-plugin-react-hooks": "^4.6.0", - "postcss": "^8.4.38", - "tailwindcss": "^3.4.4", - "typescript": "^5.1.6", - "vite": "^5.1.0", - "vite-tsconfig-paths": "^4.2.1" - }, - "engines": { - "node": ">=20.0.0" - }, - "overrides": { - "valibot": "^0.41.0" - } -} diff --git a/examples/aws-remix/postcss.config.js b/examples/aws-remix/postcss.config.js deleted file mode 100644 index 2aa7205d4b..0000000000 --- a/examples/aws-remix/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -}; diff --git a/examples/aws-remix/public/favicon.ico b/examples/aws-remix/public/favicon.ico deleted file mode 100644 index 8830cf6821..0000000000 Binary files a/examples/aws-remix/public/favicon.ico and /dev/null differ diff --git a/examples/aws-remix/public/logo-dark.png b/examples/aws-remix/public/logo-dark.png deleted file mode 100644 index b24c7aee3a..0000000000 Binary files a/examples/aws-remix/public/logo-dark.png and /dev/null differ diff --git a/examples/aws-remix/public/logo-light.png b/examples/aws-remix/public/logo-light.png deleted file mode 100644 index 4490ae7930..0000000000 Binary files a/examples/aws-remix/public/logo-light.png and /dev/null differ diff --git a/examples/aws-remix/sst.config.ts b/examples/aws-remix/sst.config.ts deleted file mode 100644 index 71ea60c142..0000000000 --- a/examples/aws-remix/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-remix", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public" - }); - new sst.aws.Remix("MyWeb", { - link: [bucket], - }); - }, -}); diff --git a/examples/aws-remix/tailwind.config.ts b/examples/aws-remix/tailwind.config.ts deleted file mode 100644 index 5f06ad4ba5..0000000000 --- a/examples/aws-remix/tailwind.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { Config } from "tailwindcss"; - -export default { - content: ["./app/**/{**,.client,.server}/**/*.{js,jsx,ts,tsx}"], - theme: { - extend: { - fontFamily: { - sans: [ - "Inter", - "ui-sans-serif", - "system-ui", - "sans-serif", - "Apple Color Emoji", - "Segoe UI Emoji", - "Segoe UI Symbol", - "Noto Color Emoji", - ], - }, - }, - }, - plugins: [], -} satisfies Config; diff --git a/examples/aws-remix/tsconfig.json b/examples/aws-remix/tsconfig.json deleted file mode 100644 index 9d87dd378f..0000000000 --- a/examples/aws-remix/tsconfig.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "include": [ - "**/*.ts", - "**/*.tsx", - "**/.server/**/*.ts", - "**/.server/**/*.tsx", - "**/.client/**/*.ts", - "**/.client/**/*.tsx" - ], - "compilerOptions": { - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "types": ["@remix-run/node", "vite/client"], - "isolatedModules": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "resolveJsonModule": true, - "target": "ES2022", - "strict": true, - "allowJs": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "baseUrl": ".", - "paths": { - "~/*": ["./app/*"] - }, - - // Vite takes care of building everything, not tsc. - "noEmit": true - } -} diff --git a/examples/aws-remix/vite.config.ts b/examples/aws-remix/vite.config.ts deleted file mode 100644 index e4e8cefc3b..0000000000 --- a/examples/aws-remix/vite.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { vitePlugin as remix } from "@remix-run/dev"; -import { defineConfig } from "vite"; -import tsconfigPaths from "vite-tsconfig-paths"; - -declare module "@remix-run/node" { - interface Future { - v3_singleFetch: true; - } -} - -export default defineConfig({ - plugins: [ - remix({ - future: { - v3_fetcherPersist: true, - v3_relativeSplatPath: true, - v3_throwAbortReason: true, - v3_singleFetch: true, - v3_lazyRouteDiscovery: true, - }, - }), - tsconfigPaths(), - ], -}); diff --git a/examples/aws-router-bucket/package.json b/examples/aws-router-bucket/package.json deleted file mode 100644 index 8870a7c91c..0000000000 --- a/examples/aws-router-bucket/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-router-bucket", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-router-bucket/spongebob.svg b/examples/aws-router-bucket/spongebob.svg deleted file mode 100644 index a9dd142f31..0000000000 --- a/examples/aws-router-bucket/spongebob.svg +++ /dev/null @@ -1 +0,0 @@ -Don’tflop character artwork \ No newline at end of file diff --git a/examples/aws-router-bucket/sst.config.ts b/examples/aws-router-bucket/sst.config.ts deleted file mode 100644 index b1382a1f62..0000000000 --- a/examples/aws-router-bucket/sst.config.ts +++ /dev/null @@ -1,45 +0,0 @@ -/// - -import path from "path"; - -/** - * ## Router and bucket - * - * Creates a router that serves static files from the `public` folder of a given bucket. - */ -export default $config({ - app(input) { - return { - name: "aws-router-bucket", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - // Create a bucket that CloudFront can access - const bucket = new sst.aws.Bucket("MyBucket", { - access: "cloudfront", - }); - - // Upload the image to the `public` folder - new aws.s3.BucketObjectv2("MyImage", { - bucket: bucket.name, - key: "public/spongebob.svg", - contentType: "image/svg+xml", - source: $asset("spongebob.svg"), - }); - - const router = new sst.aws.Router("MyRouter", { - routes: { - "/*": { - bucket, - rewrite: { regex: "^/(.*)$", to: "/public/$1" }, - }, - }, - }); - - return { - image: $interpolate`${router.url}/spongebob.svg`, - }; - }, -}); diff --git a/examples/aws-router-protection/api.ts b/examples/aws-router-protection/api.ts deleted file mode 100644 index bb310ecba1..0000000000 --- a/examples/aws-router-protection/api.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const handler = async (event: any) => { - return { - statusCode: 200, - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(event.headers), - }; -}; diff --git a/examples/aws-router-protection/package.json b/examples/aws-router-protection/package.json deleted file mode 100644 index 6e962323f7..0000000000 --- a/examples/aws-router-protection/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-router-protection", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-router-protection/sst.config.ts b/examples/aws-router-protection/sst.config.ts deleted file mode 100644 index ee813c3267..0000000000 --- a/examples/aws-router-protection/sst.config.ts +++ /dev/null @@ -1,34 +0,0 @@ -/// - -/** - * ## Router protection with OAC - * - * Creates a router with Origin Access Control (OAC) to secure Lambda function URLs - * behind CloudFront. Direct access to the Lambda URL returns 403. - */ -export default $config({ - app(input) { - return { - name: "aws-router-protection", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const router = new sst.aws.Router("MyRouter", { - protection: "oac", - }); - - const api = new sst.aws.Function("MyApi", { - handler: "api.handler", - url: { - router: { instance: router, path: "/api" }, - }, - }); - - return { - router: router.url, - api: api.url, - }; - }, -}); diff --git a/examples/aws-router-waf/api.ts b/examples/aws-router-waf/api.ts deleted file mode 100644 index fb693b1801..0000000000 --- a/examples/aws-router-waf/api.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const handler = async (event: any) => { - return { - statusCode: 200, - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ message: "Hello from WAF-protected Router!" }), - }; -}; diff --git a/examples/aws-router-waf/sst.config.ts b/examples/aws-router-waf/sst.config.ts deleted file mode 100644 index 793edf49ff..0000000000 --- a/examples/aws-router-waf/sst.config.ts +++ /dev/null @@ -1,47 +0,0 @@ -/// - -/** - * ## Router with WAF - * - * Enable WAF (Web Application Firewall) for a Router to protect against common - * web exploits and bots. - * - * WAF includes rate limiting per IP, and AWS managed rules for core rule set, - * known bad inputs, and SQL injection protection. - * - * You can also enable WAF logging to CloudWatch to monitor requests. - */ -export default $config({ - app(input) { - return { - name: "aws-router-waf", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const api = new sst.aws.Function("MyApi", { - handler: "api.handler", - url: true, - }); - - const router = new sst.aws.Router("MyRouter", { - routes: { - "/*": api.url, - }, - waf: { - rateLimitPerIp: 1000, - managedRules: { - coreRuleSet: true, - knownBadInputs: true, - sqlInjection: true, - }, - logging: true, - }, - }); - - return { - url: router.url, - }; - }, -}); diff --git a/examples/aws-router/api.ts b/examples/aws-router/api.ts deleted file mode 100644 index bb310ecba1..0000000000 --- a/examples/aws-router/api.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const handler = async (event: any) => { - return { - statusCode: 200, - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(event.headers), - }; -}; diff --git a/examples/aws-router/package.json b/examples/aws-router/package.json deleted file mode 100644 index 87a5d86ce2..0000000000 --- a/examples/aws-router/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-router", - "version": "0.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-router/sst.config.ts b/examples/aws-router/sst.config.ts deleted file mode 100644 index 5db6f2d75c..0000000000 --- a/examples/aws-router/sst.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// - -/** - * ## Router and function URL - * - * Creates a router that routes all requests to a function with a URL. - */ -export default $config({ - app(input) { - return { - name: "aws-router", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const api = new sst.aws.Function("MyApi", { - handler: "api.handler", - url: true, - }); - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - const router = new sst.aws.Router("MyRouter", { - routes: { - "/api/*": api.url, - "/*": $interpolate`https://${bucket.domain}`, - }, - }); - - return { - router: router.url, - bucket: bucket.domain, - }; - }, -}); diff --git a/examples/aws-rust-api/.gitignore b/examples/aws-rust-api/.gitignore deleted file mode 100644 index 2a7be17e50..0000000000 --- a/examples/aws-rust-api/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target - -# sst -.sst diff --git a/examples/aws-rust-api/Cargo.toml b/examples/aws-rust-api/Cargo.toml deleted file mode 100644 index 72282cdc91..0000000000 --- a/examples/aws-rust-api/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "aws-rust-lambda" -version = "0.1.0" -edition = "2021" - -[dependencies] -aws-config = { version = "1.5.16", features = ["behavior-version-latest"] } -aws-sdk-s3 = "1.73.0" -axum = "0.8.1" -lambda_http = "0.13.0" -serde = { version = "1.0.217", features = ["derive"] } -serde_json = "1.0.138" -# this will break when not in this repo. -sst_sdk = { version = "0.1.0", path = "../../sdk/rust" } -# sst_sdk = "0.1.0" -tokio = { version = "1", features = ["macros"] } -uuid = { version = "1.13.1", features = ["v4"] } diff --git a/examples/aws-rust-api/src/main.rs b/examples/aws-rust-api/src/main.rs deleted file mode 100644 index 7675ea7282..0000000000 --- a/examples/aws-rust-api/src/main.rs +++ /dev/null @@ -1,82 +0,0 @@ -use std::{env::set_var, time::Duration}; - -use aws_sdk_s3::presigning::PresigningConfig; -use axum::{routing::get, Router}; -use lambda_http::{run, tracing, Error}; -use serde::Deserialize; -use sst_sdk::Resource; - -#[derive(Deserialize, Debug)] -struct Bucket { - name: String, -} - -async fn presigned_url() -> String { - let config = aws_config::load_from_env().await; - let client = aws_sdk_s3::Client::new(&config); - let resource = Resource::init().unwrap(); - let Bucket { name } = resource.get("Bucket").unwrap(); - - let url = client - .put_object() - .bucket(name) - .key(uuid::Uuid::new_v4()) - .presigned( - PresigningConfig::builder() - .expires_in(Duration::from_secs(60 * 10)) - .build() - .unwrap(), - ) - .await - .unwrap(); - - url.uri().to_string() -} - -async fn latest() -> String { - let config = aws_config::load_from_env().await; - let client = aws_sdk_s3::Client::new(&config); - let resource = Resource::init().unwrap(); - let Bucket { name } = resource.get("Bucket").unwrap(); - - let objects = client.list_objects().bucket(&name).send().await.unwrap(); - let latest = objects - .contents() - .into_iter() - .min_by_key(|o| o.last_modified().unwrap()) - .unwrap(); - - let url = client - .get_object() - .bucket(name) - .key(latest.key().unwrap()) - .presigned( - PresigningConfig::builder() - .expires_in(Duration::from_secs(60 * 10)) - .build() - .unwrap(), - ) - .await - .unwrap(); - - url.uri().to_string() -} - -#[tokio::main] -async fn main() -> Result<(), Error> { - // If you use API Gateway stages, the Rust Runtime will include the stage name - // as part of the path that your application receives. - // Setting the following environment variable, you can remove the stage from the path. - // This variable only applies to API Gateway stages, - // you can remove it if you don't use them. - // i.e with: `GET /test-stage/todo/id/123` without: `GET /todo/id/123` - set_var("AWS_LAMBDA_HTTP_IGNORE_STAGE_IN_PATH", "true"); - - tracing::init_default_subscriber(); - - let app = Router::new() - .route("/", get(presigned_url)) - .route("/latest", get(latest)); - - run(app).await -} diff --git a/examples/aws-rust-api/sst.config.ts b/examples/aws-rust-api/sst.config.ts deleted file mode 100644 index de11b367dc..0000000000 --- a/examples/aws-rust-api/sst.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// - -/** - * ## Rust function - * - * Deploy a Rust Lambda function with a function URL and a linked S3 bucket. - */ -export default $config({ - app(input) { - return { - name: "aws-rust-api", - removal: input?.stage === "production" ? "retain" : "remove", - protect: ["production"].includes(input?.stage), - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("Bucket"); - const lambda = new sst.aws.Function("RustFunction", { - runtime: "rust", - handler: "./", - url: true, - architecture: "arm64", - link: [bucket], - }); - - return { url: lambda.url }; - }, -}); diff --git a/examples/aws-rust-cluster/.dockerignore b/examples/aws-rust-cluster/.dockerignore deleted file mode 100644 index 3821f7cc63..0000000000 --- a/examples/aws-rust-cluster/.dockerignore +++ /dev/null @@ -1,24 +0,0 @@ -# rust -/target - -# dotfiles -*.env -.git -.gitignore -.dockerignore -.build - -# misc -Dockerfile -docker-compose.yml -README.md - -# node -node_modules -package.json -package-lock.json -tsconfig.json - -# sst -sst.config.ts -.sst \ No newline at end of file diff --git a/examples/aws-rust-cluster/.gitignore b/examples/aws-rust-cluster/.gitignore deleted file mode 100644 index 6b247dbcba..0000000000 --- a/examples/aws-rust-cluster/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# sst -.sst - -# rust -Cargo.lock -target/ \ No newline at end of file diff --git a/examples/aws-rust-cluster/Cargo.toml b/examples/aws-rust-cluster/Cargo.toml deleted file mode 100644 index 36a109f013..0000000000 --- a/examples/aws-rust-cluster/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "aws_rust_cluster" -version = "0.1.0" -edition = "2021" - -[dependencies] -anyhow = "1.0.86" -axum = "0.7.5" -serde = { version = "1.0.209", features = ["derive"] } -tokio = { version = "1.40.0", features = ["rt-multi-thread", "macros", "net"] } diff --git a/examples/aws-rust-cluster/Dockerfile b/examples/aws-rust-cluster/Dockerfile deleted file mode 100644 index 679bdab9e4..0000000000 --- a/examples/aws-rust-cluster/Dockerfile +++ /dev/null @@ -1,28 +0,0 @@ -FROM rust:slim AS chef - -# install build tools -RUN apt-get update -y && \ - apt-get install -y pkg-config make g++ libssl-dev && \ - rustup target add x86_64-unknown-linux-gnu - -# add cargo chef (this installs only once on first build) -RUN cargo install cargo-chef -WORKDIR /app - -FROM chef AS planner -COPY . . -RUN cargo chef prepare --recipe-path recipe.json - -FROM chef AS builder -COPY --from=planner /app/recipe.json recipe.json -# build docker caching layer -RUN cargo chef cook --release --recipe-path recipe.json - -# build binary -COPY . . -RUN cargo build --release --target x86_64-unknown-linux-gnu - -# distroless image; launch app -FROM gcr.io/distroless/cc -COPY --from=builder /app/target/x86_64-unknown-linux-gnu/release/aws_rust_cluster /bin/aws_rust_cluster -ENTRYPOINT [ "/bin/aws_rust_cluster" ] diff --git a/examples/aws-rust-cluster/docker-compose.yml b/examples/aws-rust-cluster/docker-compose.yml deleted file mode 100644 index 7b22f1ec37..0000000000 --- a/examples/aws-rust-cluster/docker-compose.yml +++ /dev/null @@ -1,9 +0,0 @@ -services: - api: - build: - context: . - dockerfile: ./Dockerfile - ports: - - 80:80 - expose: - - 80 \ No newline at end of file diff --git a/examples/aws-rust-cluster/package.json b/examples/aws-rust-cluster/package.json deleted file mode 100644 index 3523728cc7..0000000000 --- a/examples/aws-rust-cluster/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-rust-cluster", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "devDependencies": { - "@types/aws-lambda": "8.10.145", - "sst": "file:../../sdk/js", - "sst-linux-x64": "^4" - }, - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-rust-cluster/src/main.rs b/examples/aws-rust-cluster/src/main.rs deleted file mode 100644 index f8a4e7649f..0000000000 --- a/examples/aws-rust-cluster/src/main.rs +++ /dev/null @@ -1,29 +0,0 @@ -use anyhow::Result; -use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router}; -use serde::Serialize; -use tokio::net::TcpListener; - -#[derive(Serialize)] -pub struct Ping { - message: &'static str, -} - -pub async fn ping() -> impl IntoResponse { - ( - StatusCode::IM_A_TEAPOT, - Json(Ping { - message: "hello from rust :)", - }), - ) -} - -#[tokio::main] -async fn main() -> Result<()> { - let api = Router::new().route("/", get(ping)); - let addr = match cfg!(debug_assertions) { - true => "0.0.0.0:3000", - false => "0.0.0.0:80", - }; - let listener = TcpListener::bind(addr).await?; - Ok(axum::serve(listener, api).await?) -} diff --git a/examples/aws-rust-cluster/sst.config.ts b/examples/aws-rust-cluster/sst.config.ts deleted file mode 100644 index 0641cf6a35..0000000000 --- a/examples/aws-rust-cluster/sst.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -/// - -/** - * ## Rust container - * - * Deploy a Rust app in a container with a load balancer using a Dockerfile. - */ -export default $config({ - app(input) { - return { - name: "aws-rust-cluster", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - aws: { region: "us-east-1" }, - }, - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "gateway" }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - const service = new sst.aws.Service("MyService", { - cluster, - image: { - context: "./", - dockerfile: "Dockerfile", - }, - loadBalancer: { - domain: "rust.dockerfile.dev.sst.dev", - ports: [ - { listen: "80/http" }, - { listen: "443/https", forward: "80/http" }, - ], - }, - }); - - return { - url: service.url, - }; - }, -}); diff --git a/examples/aws-rust-cluster/tsconfig.json b/examples/aws-rust-cluster/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-rust-cluster/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-rust-loco/.dockerignore b/examples/aws-rust-loco/.dockerignore deleted file mode 100644 index f403586fdf..0000000000 --- a/examples/aws-rust-loco/.dockerignore +++ /dev/null @@ -1,9 +0,0 @@ -target -dockerfile -.dockerignore -.git -.gitignore -.cargo - -# sst -.sst diff --git a/examples/aws-rust-loco/.github/workflows/ci.yaml b/examples/aws-rust-loco/.github/workflows/ci.yaml deleted file mode 100644 index b2e3e1162d..0000000000 --- a/examples/aws-rust-loco/.github/workflows/ci.yaml +++ /dev/null @@ -1,101 +0,0 @@ -name: CI -on: - push: - branches: - - master - - main - pull_request: - -env: - RUST_TOOLCHAIN: stable - TOOLCHAIN_PROFILE: minimal - -jobs: - rustfmt: - name: Check Style - runs-on: ubuntu-latest - - permissions: - contents: read - - steps: - - name: Checkout the code - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - components: rustfmt - - name: Run cargo fmt - uses: actions-rs/cargo@v1 - with: - command: fmt - args: --all -- --check - - clippy: - name: Run Clippy - runs-on: ubuntu-latest - - permissions: - contents: read - - steps: - - name: Checkout the code - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - - name: Setup Rust cache - uses: Swatinem/rust-cache@v2 - - name: Run cargo clippy - uses: actions-rs/cargo@v1 - with: - command: clippy - args: --all-features -- -D warnings -W clippy::pedantic -W clippy::nursery -W rust-2018-idioms - - test: - name: Run Tests - runs-on: ubuntu-latest - - permissions: - contents: read - - services: - redis: - image: redis - options: >- - --health-cmd "redis-cli ping" - --health-interval 10s - --health-timeout 5s - --health-retries 5 - ports: - - "6379:6379" - postgres: - image: postgres - env: - POSTGRES_DB: postgres_test - POSTGRES_USER: postgres - POSTGRES_PASSWORD: postgres - ports: - - "5432:5432" - # Set health checks to wait until postgres has started - options: --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - - steps: - - name: Checkout the code - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - - name: Setup Rust cache - uses: Swatinem/rust-cache@v2 - - name: Run cargo test - uses: actions-rs/cargo@v1 - with: - command: test - args: --all-features --all - env: - REDIS_URL: redis://localhost:${{job.services.redis.ports[6379]}} - DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres_test diff --git a/examples/aws-rust-loco/.gitignore b/examples/aws-rust-loco/.gitignore deleted file mode 100644 index 1902da3f36..0000000000 --- a/examples/aws-rust-loco/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -**/config/local.yaml -**/config/*.local.yaml -**/config/production.yaml - -# Generated by Cargo -# will have compiled files and executables -debug/ -target/ - -# include cargo lock -!Cargo.lock -.cargo - -# These are backup files generated by rustfmt -**/*.rs.bk - -# MSVC Windows builds of rustc generate these, which store debugging information -*.pdb - -*.sqlite - -# sst -.sst diff --git a/examples/aws-rust-loco/.rustfmt.toml b/examples/aws-rust-loco/.rustfmt.toml deleted file mode 100644 index d862e08106..0000000000 --- a/examples/aws-rust-loco/.rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -max_width = 100 -use_small_heuristics = "Default" diff --git a/examples/aws-rust-loco/Cargo.toml b/examples/aws-rust-loco/Cargo.toml deleted file mode 100644 index 52b82829ee..0000000000 --- a/examples/aws-rust-loco/Cargo.toml +++ /dev/null @@ -1,50 +0,0 @@ -[workspace] - -[package] -name = "server" -version = "0.1.0" -edition = "2021" -publish = false -default-run = "server-cli" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] - -loco-rs = { version = "0.9.0" } -migration = { path = "migration" } - -serde = { version = "1", features = ["derive"] } -serde_json = "1" -tokio = { version = "1.33.0", default-features = false } -async-trait = "0.1.74" -tracing = "0.1.40" -chrono = "0.4" -validator = { version = "0.16" } -sea-orm = { version = "1.0.0", features = [ - "sqlx-sqlite", - "sqlx-postgres", - "runtime-tokio-rustls", - "macros", -] } - -axum = "0.7.5" -include_dir = "0.7" -uuid = { version = "1.6.0", features = ["v4"] } -tracing-subscriber = { version = "0.3.17", features = ["env-filter", "json"] } - -[[bin]] -name = "server-cli" -path = "src/bin/main.rs" -required-features = [] - -[[bin]] -name = "tool" -path = "src/bin/tool.rs" -required-features = [] - -[dev-dependencies] -serial_test = "3.1.1" -rstest = "0.21.0" -loco-rs = { version = "0.9.0", features = ["testing"] } -insta = { version = "1.34.0", features = ["redactions", "yaml", "filters"] } diff --git a/examples/aws-rust-loco/Dockerfile b/examples/aws-rust-loco/Dockerfile deleted file mode 100644 index 99315f26d2..0000000000 --- a/examples/aws-rust-loco/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM rust:1.74-slim as builder - -WORKDIR /usr/src/ - -COPY . . - -RUN cargo build --release - -FROM debian:bookworm-slim - -WORKDIR /usr/app - -COPY --from=builder /usr/src/config /usr/app/config -COPY --from=builder /usr/src/target/release/server-cli /usr/app/server-cli - -ENTRYPOINT ["/usr/app/server-cli"] \ No newline at end of file diff --git a/examples/aws-rust-loco/Justfile b/examples/aws-rust-loco/Justfile deleted file mode 100644 index 1c1d9b2d59..0000000000 --- a/examples/aws-rust-loco/Justfile +++ /dev/null @@ -1,24 +0,0 @@ -# Command to run SST, process SST_RESOURCE_LocoDatabase, and run cargo loco start -dev stage="production": - #!/usr/bin/env bash - set -euo pipefail - - # Run SST shell and capture its output - SST_OUTPUT=$(pnpm sst shell --stage={{stage}} -- env) - - # Extract SST_RESOURCE_LocoDatabase from SST output - SST_RESOURCE_LocoDatabase=$(echo "$SST_OUTPUT" | grep SST_RESOURCE_LocoDatabase | cut -d '=' -f2-) - - # Ensure the environment variable exists - if [ -z "${SST_RESOURCE_LocoDatabase:-}" ]; then - echo "Error: SST_RESOURCE_LocoDatabase is not set" >&2 - exit 1 - fi - - # Use jq to parse the JSON and construct the DATABASE_URL - export DATABASE_URL=$(echo "$SST_RESOURCE_LocoDatabase" | jq -r ' - "postgres://\(.username):\(.password | @uri)@\(.host):\(.port)/\(.database)" - ') - - # Run cargo loco start with the processed DATABASE_URL - pnpm sst shell --stage={{stage}} -- cargo loco start diff --git a/examples/aws-rust-loco/config/development.yaml b/examples/aws-rust-loco/config/development.yaml deleted file mode 100644 index 940e654b71..0000000000 --- a/examples/aws-rust-loco/config/development.yaml +++ /dev/null @@ -1,145 +0,0 @@ -# Loco configuration file documentation - -# Application logging configuration -logger: - # Enable or disable logging. - enable: true - # Enable pretty backtrace (sets RUST_BACKTRACE=1) - pretty_backtrace: false - # Log level, options: trace, debug, info, warn or error. - level: info - # Define the logging format. options: compact, pretty or json - format: json - # By default the logger has filtering only logs that came from your code or logs that came from `loco` framework. to see all third party libraries - # Uncomment the line below to override to see all third party libraries you can enable this config and override the logger filters. - # override_filter: trace - -# Web server configuration -server: - # Port on which the server will listen. the server binding is 0.0.0.0:{PORT} - port: 5150 - binding: 0.0.0.0 - # The UI hostname or IP address that mailers will point to. - host: http://localhost - # Out of the box middleware configuration. to disable middleware you can changed the `enable` field to `false` of comment the middleware block - middlewares: - # Enable Etag cache header middleware - etag: - enable: true - # Allows to limit the payload size request. payload that bigger than this file will blocked the request. - limit_payload: - # Enable/Disable the middleware. - enable: true - # the limit size. can be b,kb,kib,mb,mib,gb,gib - body_limit: 5mb - # set secure headers - secure_headers: - preset: github - # calculate remote IP based on `X-Forwarded-For` when behind a proxy or load balancer - # use RemoteIP(..) extractor to get the remote IP. - # without this middleware, you'll get the proxy IP instead. - # For more: https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/middleware/remote_ip.rb - # - # NOTE! only enable when under a proxy, otherwise this can lead to IP spoofing vulnerabilities - # trust me, you'll know if you need this middleware. - remote_ip: - enable: false - # # replace the default trusted proxies: - # trusted_proxies: - # - ip range 1 - # - ip range 2 .. - # Generating a unique request ID and enhancing logging with additional information such as the start and completion of request processing, latency, status code, and other request details. - logger: - # Enable/Disable the middleware. - enable: true - # when your code is panicked, the request still returns 500 status code. - catch_panic: - # Enable/Disable the middleware. - enable: true - # Timeout for incoming requests middleware. requests that take more time from the configuration will cute and 408 status code will returned. - timeout_request: - # Enable/Disable the middleware. - enable: false - # Duration time in milliseconds. - timeout: 5000 - cors: - enable: true - # Set the value of the [`Access-Control-Allow-Origin`][mdn] header - # allow_origins: - # - https://loco.rs - # Set the value of the [`Access-Control-Allow-Headers`][mdn] header - # allow_headers: - # - Content-Type - # Set the value of the [`Access-Control-Allow-Methods`][mdn] header - # allow_methods: - # - POST - # Set the value of the [`Access-Control-Max-Age`][mdn] header in seconds - # max_age: 3600 - -# Worker Configuration -workers: - # specifies the worker mode. Options: - # - BackgroundQueue - Workers operate asynchronously in the background, processing queued. - # - ForegroundBlocking - Workers operate in the foreground and block until tasks are completed. - # - BackgroundAsync - Workers operate asynchronously in the background, processing tasks with async capabilities. - mode: BackgroundQueue - -# Mailer Configuration. -mailer: - # SMTP mailer configuration. - smtp: - # Enable/Disable smtp mailer. - enable: false - # SMTP server host. e.x localhost, smtp.gmail.com - host: {{ get_env(name="MAILER_HOST", default="localhost") }} - # SMTP server port - port: 1025 - # Use secure connection (SSL/TLS). - secure: false - # auth: - # user: - # password: - -# Initializers Configuration -# initializers: -# oauth2: -# authorization_code: # Authorization code grant type -# - client_identifier: google # Identifier for the OAuth2 provider. Replace 'google' with your provider's name if different, must be unique within the oauth2 config. -# ... other fields - -# Database Configuration -database: - # Database connection URI - uri: {{ get_env(name="DATABASE_URL", default="postgres://loco:loco@localhost:5432/server_development") }} - # When enabled, the sql query will be logged. - enable_logging: false - # Set the timeout duration when acquiring a connection. - connect_timeout: {{ get_env(name="DB_CONNECT_TIMEOUT", default="500") }} - # Set the idle duration before closing a connection. - idle_timeout: 500 - # Minimum number of connections for a pool. - min_connections: 1 - # Maximum number of connections for a pool. - max_connections: 1 - # Run migration up when application loaded - auto_migrate: false - # Truncate database when application loaded. This is a dangerous operation, make sure that you using this flag only on dev environments or test mode - dangerously_truncate: false - # Recreating schema when application loaded. This is a dangerous operation, make sure that you using this flag only on dev environments or test mode - dangerously_recreate: false - -# Queue Configuration -queue: - # Redis connection URI - uri: {{ get_env(name="REDIS_URL", default="redis://127.0.0.1") }} - # Dangerously flush all data in Redis on startup. dangerous operation, make sure that you using this flag only on dev environments or test mode - dangerously_flush: false - -# Authentication Configuration -auth: - # JWT authentication - jwt: - # Secret key for token generation and verification - secret: KRVK4VAddJ3zV8IkOCTh - # Token expiration time in seconds - expiration: 604800 # 7 days diff --git a/examples/aws-rust-loco/config/test.yaml b/examples/aws-rust-loco/config/test.yaml deleted file mode 100644 index 947d5b1de5..0000000000 --- a/examples/aws-rust-loco/config/test.yaml +++ /dev/null @@ -1,126 +0,0 @@ -# Loco configuration file documentation - -# Application logging configuration -logger: - # Enable or disable logging. - enable: false - # Log level, options: trace, debug, info, warn or error. - level: debug - # Define the logging format. options: compact, pretty or json - format: compact - # By default the logger has filtering only logs that came from your code or logs that came from `loco` framework. to see all third party libraries - # Uncomment the line below to override to see all third party libraries you can enable this config and override the logger filters. - # override_filter: trace - -# Web server configuration -server: - # Port on which the server will listen. the server binding is 0.0.0.0:{PORT} - port: 5150 - # The UI hostname or IP address that mailers will point to. - host: http://localhost - # Out of the box middleware configuration. to disable middleware you can changed the `enable` field to `false` of comment the middleware block - middlewares: - # Allows to limit the payload size request. payload that bigger than this file will blocked the request. - limit_payload: - # Enable/Disable the middleware. - enable: true - # the limit size. can be b,kb,kib,mb,mib,gb,gib - body_limit: 5mb - # Generating a unique request ID and enhancing logging with additional information such as the start and completion of request processing, latency, status code, and other request details. - logger: - # Enable/Disable the middleware. - enable: true - # when your code is panicked, the request still returns 500 status code. - catch_panic: - # Enable/Disable the middleware. - enable: true - # Timeout for incoming requests middleware. requests that take more time from the configuration will cute and 408 status code will returned. - timeout_request: - # Enable/Disable the middleware. - enable: false - # Duration time in milliseconds. - timeout: 5000 - cors: - enable: true - # Set the value of the [`Access-Control-Allow-Origin`][mdn] header - # allow_origins: - # - https://loco.rs - # Set the value of the [`Access-Control-Allow-Headers`][mdn] header - # allow_headers: - # - Content-Type - # Set the value of the [`Access-Control-Allow-Methods`][mdn] header - # allow_methods: - # - POST - # Set the value of the [`Access-Control-Max-Age`][mdn] header in seconds - # max_age: 3600 - -# Worker Configuration -workers: - # specifies the worker mode. Options: - # - BackgroundQueue - Workers operate asynchronously in the background, processing queued. - # - ForegroundBlocking - Workers operate in the foreground and block until tasks are completed. - # - BackgroundAsync - Workers operate asynchronously in the background, processing tasks with async capabilities. - mode: ForegroundBlocking - -# Mailer Configuration. -mailer: - # SMTP mailer configuration. - smtp: - # Enable/Disable smtp mailer. - enable: true - # SMTP server host. e.x localhost, smtp.gmail.com - host: localhost - # SMTP server port - port: 1025 - # Use secure connection (SSL/TLS). - secure: false - # auth: - # user: - # password: - stub: true - -# Initializers Configuration -# initializers: -# oauth2: -# authorization_code: # Authorization code grant type -# - client_identifier: google # Identifier for the OAuth2 provider. Replace 'google' with your provider's name if different, must be unique within the oauth2 config. -# ... other fields - - -# Database Configuration -database: - # Database connection URI - uri: {{get_env(name="DATABASE_URL", default="postgres://loco:loco@localhost:5432/server_test")}} - # When enabled, the sql query will be logged. - enable_logging: false - # Set the timeout duration when acquiring a connection. - connect_timeout: {{ get_env(name="DB_CONNECT_TIMEOUT", default="500") }} - # Set the idle duration before closing a connection. - idle_timeout: 500 - # Minimum number of connections for a pool. - min_connections: 1 - # Maximum number of connections for a pool. - max_connections: 1 - # Run migration up when application loaded - auto_migrate: true - # Truncate database when application loaded. This is a dangerous operation, make sure that you using this flag only on dev environments or test mode - dangerously_truncate: true - # Recreating schema when application loaded. This is a dangerous operation, make sure that you using this flag only on dev environments or test mode - dangerously_recreate: false - -# Queue Configuration -queue: - # Redis connection URI - uri: {{get_env(name="REDIS_URL", default="redis://127.0.0.1")}} - # Dangerously flush all data in Redis on startup. dangerous operation, make sure that you using this flag only on dev environments or test mode - dangerously_flush: false - -# Authentication Configuration -auth: - # JWT authentication - jwt: - # Secret key for token generation and verification - secret: jFb88JjbJsVEsVdwNa8U - # Token expiration time in seconds - expiration: 604800 # 7 days - diff --git a/examples/aws-rust-loco/examples/playground.rs b/examples/aws-rust-loco/examples/playground.rs deleted file mode 100644 index 4dc0bb3873..0000000000 --- a/examples/aws-rust-loco/examples/playground.rs +++ /dev/null @@ -1,21 +0,0 @@ -#[allow(unused_imports)] -use loco_rs::{cli::playground, prelude::*}; -use server::app::App; - -#[tokio::main] -async fn main() -> loco_rs::Result<()> { - let _ctx = playground::().await?; - - // let active_model: articles::ActiveModel = ActiveModel { - // title: Set(Some("how to build apps in 3 steps".to_string())), - // content: Set(Some("use Loco: https://loco.rs".to_string())), - // ..Default::default() - // }; - // active_model.insert(&ctx.db).await.unwrap(); - - // let res = articles::Entity::find().all(&ctx.db).await.unwrap(); - // println!("{:?}", res); - println!("welcome to playground. edit me at `examples/playground.rs`"); - - Ok(()) -} diff --git a/examples/aws-rust-loco/migration/Cargo.toml b/examples/aws-rust-loco/migration/Cargo.toml deleted file mode 100644 index 723b73ccf4..0000000000 --- a/examples/aws-rust-loco/migration/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "migration" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -name = "migration" -path = "src/lib.rs" - -[dependencies] -async-std = { version = "1", features = ["attributes", "tokio1"] } -loco-rs = { version = "0.9.0" } - -[dependencies.sea-orm-migration] -version = "1.0.0" -features = [ - # Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI. - # View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime. - # e.g. - "runtime-tokio-rustls", # `ASYNC_RUNTIME` feature -] diff --git a/examples/aws-rust-loco/migration/src/lib.rs b/examples/aws-rust-loco/migration/src/lib.rs deleted file mode 100644 index 3352f5c573..0000000000 --- a/examples/aws-rust-loco/migration/src/lib.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![allow(elided_lifetimes_in_paths)] -#![allow(clippy::wildcard_imports)] -pub use sea_orm_migration::prelude::*; - -mod m20220101_000001_users; -mod m20231103_114510_notes; - -pub struct Migrator; - -#[async_trait::async_trait] -impl MigratorTrait for Migrator { - fn migrations() -> Vec> { - vec![ - Box::new(m20220101_000001_users::Migration), - Box::new(m20231103_114510_notes::Migration), - ] - } -} diff --git a/examples/aws-rust-loco/migration/src/m20220101_000001_users.rs b/examples/aws-rust-loco/migration/src/m20220101_000001_users.rs deleted file mode 100644 index 936ad3d0cb..0000000000 --- a/examples/aws-rust-loco/migration/src/m20220101_000001_users.rs +++ /dev/null @@ -1,50 +0,0 @@ -use loco_rs::schema::table_auto_tz; -use sea_orm_migration::{prelude::*, schema::*}; - -#[derive(DeriveMigrationName)] -pub struct Migration; - -#[async_trait::async_trait] -impl MigrationTrait for Migration { - async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { - let table = table_auto_tz(Users::Table) - .col(pk_auto(Users::Id)) - .col(uuid(Users::Pid)) - .col(string_uniq(Users::Email)) - .col(string(Users::Password)) - .col(string(Users::ApiKey).unique_key()) - .col(string(Users::Name)) - .col(string_null(Users::ResetToken)) - .col(timestamp_with_time_zone_null(Users::ResetSentAt)) - .col(string_null(Users::EmailVerificationToken)) - .col(timestamp_with_time_zone_null( - Users::EmailVerificationSentAt, - )) - .col(timestamp_with_time_zone_null(Users::EmailVerifiedAt)) - .to_owned(); - manager.create_table(table).await?; - Ok(()) - } - - async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { - manager - .drop_table(Table::drop().table(Users::Table).to_owned()) - .await - } -} - -#[derive(Iden)] -pub enum Users { - Table, - Id, - Pid, - Email, - Name, - Password, - ApiKey, - ResetToken, - ResetSentAt, - EmailVerificationToken, - EmailVerificationSentAt, - EmailVerifiedAt, -} diff --git a/examples/aws-rust-loco/migration/src/m20231103_114510_notes.rs b/examples/aws-rust-loco/migration/src/m20231103_114510_notes.rs deleted file mode 100644 index d0d8a5a0f7..0000000000 --- a/examples/aws-rust-loco/migration/src/m20231103_114510_notes.rs +++ /dev/null @@ -1,34 +0,0 @@ -use loco_rs::schema::table_auto_tz; -use sea_orm_migration::{prelude::*, schema::*}; - -#[derive(DeriveMigrationName)] -pub struct Migration; - -#[async_trait::async_trait] -impl MigrationTrait for Migration { - async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { - manager - .create_table( - table_auto_tz(Notes::Table) - .col(pk_auto(Notes::Id)) - .col(string_null(Notes::Title)) - .col(string_null(Notes::Content)) - .to_owned(), - ) - .await - } - - async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { - manager - .drop_table(Table::drop().table(Notes::Table).to_owned()) - .await - } -} - -#[derive(DeriveIden)] -enum Notes { - Table, - Id, - Title, - Content, -} diff --git a/examples/aws-rust-loco/src/app.rs b/examples/aws-rust-loco/src/app.rs deleted file mode 100644 index 4b76c503bc..0000000000 --- a/examples/aws-rust-loco/src/app.rs +++ /dev/null @@ -1,72 +0,0 @@ -use std::path::Path; - -use async_trait::async_trait; -use loco_rs::{ - app::{AppContext, Hooks}, - boot::{create_app, BootResult, StartMode}, - controller::AppRoutes, - db::{self, truncate_table}, - environment::Environment, - task::Tasks, - worker::{AppWorker, Processor}, - Result, -}; -use migration::Migrator; -use sea_orm::DatabaseConnection; - -use crate::{ - controllers, - models::_entities::{notes, users}, - tasks, - workers::downloader::DownloadWorker, -}; - -pub struct App; -#[async_trait] -impl Hooks for App { - fn app_name() -> &'static str { - env!("CARGO_CRATE_NAME") - } - - fn app_version() -> String { - format!( - "{} ({})", - env!("CARGO_PKG_VERSION"), - option_env!("BUILD_SHA") - .or(option_env!("GITHUB_SHA")) - .unwrap_or("dev") - ) - } - - async fn boot(mode: StartMode, environment: &Environment) -> Result { - create_app::(mode, environment).await - } - - fn routes(_ctx: &AppContext) -> AppRoutes { - AppRoutes::with_default_routes() - .add_route(controllers::health::routes()) - .add_route(controllers::notes::routes()) - .add_route(controllers::auth::routes()) - .add_route(controllers::user::routes()) - } - - fn connect_workers<'a>(p: &'a mut Processor, ctx: &'a AppContext) { - p.register(DownloadWorker::build(ctx)); - } - - fn register_tasks(tasks: &mut Tasks) { - tasks.register(tasks::seed::SeedData); - } - - async fn truncate(db: &DatabaseConnection) -> Result<()> { - truncate_table(db, users::Entity).await?; - truncate_table(db, notes::Entity).await?; - Ok(()) - } - - async fn seed(db: &DatabaseConnection, base: &Path) -> Result<()> { - db::seed::(db, &base.join("users.yaml").display().to_string()).await?; - db::seed::(db, &base.join("notes.yaml").display().to_string()).await?; - Ok(()) - } -} diff --git a/examples/aws-rust-loco/src/bin/main.rs b/examples/aws-rust-loco/src/bin/main.rs deleted file mode 100644 index 9b895c1be2..0000000000 --- a/examples/aws-rust-loco/src/bin/main.rs +++ /dev/null @@ -1,8 +0,0 @@ -use loco_rs::cli; -use server::app::App; -use migration::Migrator; - -#[tokio::main] -async fn main() -> loco_rs::Result<()> { - cli::main::().await -} diff --git a/examples/aws-rust-loco/src/bin/tool.rs b/examples/aws-rust-loco/src/bin/tool.rs deleted file mode 100644 index 9b895c1be2..0000000000 --- a/examples/aws-rust-loco/src/bin/tool.rs +++ /dev/null @@ -1,8 +0,0 @@ -use loco_rs::cli; -use server::app::App; -use migration::Migrator; - -#[tokio::main] -async fn main() -> loco_rs::Result<()> { - cli::main::().await -} diff --git a/examples/aws-rust-loco/src/controllers/auth.rs b/examples/aws-rust-loco/src/controllers/auth.rs deleted file mode 100644 index dba78a3e90..0000000000 --- a/examples/aws-rust-loco/src/controllers/auth.rs +++ /dev/null @@ -1,150 +0,0 @@ -use axum::debug_handler; -use loco_rs::prelude::*; -use serde::{Deserialize, Serialize}; - -use crate::{ - mailers::auth::AuthMailer, - models::{ - _entities::users, - users::{LoginParams, RegisterParams}, - }, - views::auth::LoginResponse, -}; -#[derive(Debug, Deserialize, Serialize)] -pub struct VerifyParams { - pub token: String, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct ForgotParams { - pub email: String, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct ResetParams { - pub token: String, - pub password: String, -} - -/// Register function creates a new user with the given parameters and sends a -/// welcome email to the user -#[debug_handler] -async fn register( - State(ctx): State, - Json(params): Json, -) -> Result { - let res = users::Model::create_with_password(&ctx.db, ¶ms).await; - - let user = match res { - Ok(user) => user, - Err(err) => { - tracing::info!( - message = err.to_string(), - user_email = ¶ms.email, - "could not register user", - ); - return format::json(()); - } - }; - - let user = user - .into_active_model() - .set_email_verification_sent(&ctx.db) - .await?; - - AuthMailer::send_welcome(&ctx, &user).await?; - - format::json(()) -} - -/// Verify register user. if the user not verified his email, he can't login to -/// the system. -#[debug_handler] -async fn verify( - State(ctx): State, - Json(params): Json, -) -> Result { - let user = users::Model::find_by_verification_token(&ctx.db, ¶ms.token).await?; - - if user.email_verified_at.is_some() { - tracing::info!(pid = user.pid.to_string(), "user already verified"); - } else { - let active_model = user.into_active_model(); - let user = active_model.verified(&ctx.db).await?; - tracing::info!(pid = user.pid.to_string(), "user verified"); - } - - format::json(()) -} - -/// In case the user forgot his password this endpoints generate a forgot token -/// and send email to the user. In case the email not found in our DB, we are -/// returning a valid request for for security reasons (not exposing users DB -/// list). -#[debug_handler] -async fn forgot( - State(ctx): State, - Json(params): Json, -) -> Result { - let Ok(user) = users::Model::find_by_email(&ctx.db, ¶ms.email).await else { - // we don't want to expose our users email. if the email is invalid we still - // returning success to the caller - return format::json(()); - }; - - let user = user - .into_active_model() - .set_forgot_password_sent(&ctx.db) - .await?; - - AuthMailer::forgot_password(&ctx, &user).await?; - - format::json(()) -} - -/// reset user password by the given parameters -#[debug_handler] -async fn reset(State(ctx): State, Json(params): Json) -> Result { - let Ok(user) = users::Model::find_by_reset_token(&ctx.db, ¶ms.token).await else { - // we don't want to expose our users email. if the email is invalid we still - // returning success to the caller - tracing::info!("reset token not found"); - - return format::json(()); - }; - user.into_active_model() - .reset_password(&ctx.db, ¶ms.password) - .await?; - - format::json(()) -} - -/// Creates a user login and returns a token -#[debug_handler] -async fn login(State(ctx): State, Json(params): Json) -> Result { - let user = users::Model::find_by_email(&ctx.db, ¶ms.email).await?; - - let valid = user.verify_password(¶ms.password); - - if !valid { - return unauthorized("unauthorized!"); - } - - let jwt_secret = ctx.config.get_jwt_config()?; - - let token = user - .generate_jwt(&jwt_secret.secret, &jwt_secret.expiration) - .or_else(|_| unauthorized("unauthorized!"))?; - - format::json(LoginResponse::new(&user, &token)) -} - -pub fn routes() -> Routes { - Routes::new() - .prefix("auth") - .add("/register", post(register)) - .add("/verify", post(verify)) - .add("/login", post(login)) - .add("/forgot", post(forgot)) - .add("/reset", post(reset)) -} diff --git a/examples/aws-rust-loco/src/controllers/health.rs b/examples/aws-rust-loco/src/controllers/health.rs deleted file mode 100644 index 09858ee4b0..0000000000 --- a/examples/aws-rust-loco/src/controllers/health.rs +++ /dev/null @@ -1,10 +0,0 @@ -use loco_rs::prelude::*; -use serde_json::json; - -async fn check() -> Result { - format::json(json!({ "message": "ok" })) -} - -pub fn routes() -> Routes { - Routes::new().add("/", get(check)) -} diff --git a/examples/aws-rust-loco/src/controllers/mod.rs b/examples/aws-rust-loco/src/controllers/mod.rs deleted file mode 100644 index 5cbdcb54e5..0000000000 --- a/examples/aws-rust-loco/src/controllers/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod auth; -pub mod health; -pub mod notes; -pub mod user; diff --git a/examples/aws-rust-loco/src/controllers/notes.rs b/examples/aws-rust-loco/src/controllers/notes.rs deleted file mode 100644 index f378fb4d8d..0000000000 --- a/examples/aws-rust-loco/src/controllers/notes.rs +++ /dev/null @@ -1,75 +0,0 @@ -#![allow(clippy::missing_errors_doc)] -#![allow(clippy::unnecessary_struct_initialization)] -#![allow(clippy::unused_async)] -use axum::debug_handler; -use loco_rs::prelude::*; -use serde::{Deserialize, Serialize}; - -use crate::models::_entities::notes::{ActiveModel, Entity, Model}; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Params { - pub title: Option, - pub content: Option, -} - -impl Params { - fn update(&self, item: &mut ActiveModel) { - item.title = Set(self.title.clone()); - item.content = Set(self.content.clone()); - } -} - -async fn load_item(ctx: &AppContext, id: i32) -> Result { - let item = Entity::find_by_id(id).one(&ctx.db).await?; - item.ok_or_else(|| Error::NotFound) -} - -#[debug_handler] -pub async fn list(State(ctx): State) -> Result { - format::json(Entity::find().all(&ctx.db).await?) -} - -#[debug_handler] -pub async fn add(State(ctx): State, Json(params): Json) -> Result { - let mut item = ActiveModel { - ..Default::default() - }; - params.update(&mut item); - let item = item.insert(&ctx.db).await?; - format::json(item) -} - -#[debug_handler] -pub async fn update( - Path(id): Path, - State(ctx): State, - Json(params): Json, -) -> Result { - let item = load_item(&ctx, id).await?; - let mut item = item.into_active_model(); - params.update(&mut item); - let item = item.update(&ctx.db).await?; - format::json(item) -} - -#[debug_handler] -pub async fn remove(Path(id): Path, State(ctx): State) -> Result { - load_item(&ctx, id).await?.delete(&ctx.db).await?; - format::empty() -} - -#[debug_handler] -pub async fn get_one(Path(id): Path, State(ctx): State) -> Result { - format::json(load_item(&ctx, id).await?) -} - -pub fn routes() -> Routes { - Routes::new() - .prefix("notes") - .add("/", get(list)) - .add("/", post(add)) - .add("/:id", get(get_one)) - .add("/:id", delete(remove)) - .add("/:id", post(update)) -} diff --git a/examples/aws-rust-loco/src/controllers/user.rs b/examples/aws-rust-loco/src/controllers/user.rs deleted file mode 100644 index 1f432ae9ef..0000000000 --- a/examples/aws-rust-loco/src/controllers/user.rs +++ /dev/null @@ -1,14 +0,0 @@ -use axum::debug_handler; -use loco_rs::prelude::*; - -use crate::{models::_entities::users, views::user::CurrentResponse}; - -#[debug_handler] -async fn current(auth: auth::JWT, State(ctx): State) -> Result { - let user = users::Model::find_by_pid(&ctx.db, &auth.claims.pid).await?; - format::json(CurrentResponse::new(&user)) -} - -pub fn routes() -> Routes { - Routes::new().prefix("user").add("/current", get(current)) -} diff --git a/examples/aws-rust-loco/src/fixtures/notes.yaml b/examples/aws-rust-loco/src/fixtures/notes.yaml deleted file mode 100644 index 0e66c95314..0000000000 --- a/examples/aws-rust-loco/src/fixtures/notes.yaml +++ /dev/null @@ -1,11 +0,0 @@ ---- -- id: 1 - title: Loco note 1 - content: Loco note 1 content - created_at: "2023-11-12T12:34:56.789Z" - updated_at: "2023-11-12T12:34:56.789Z" -- id: 2 - title: Loco note 2 - content: Loco note 2 content - created_at: "2023-11-12T12:34:56.789Z" - updated_at: "2023-11-12T12:34:56.789Z" diff --git a/examples/aws-rust-loco/src/fixtures/users.yaml b/examples/aws-rust-loco/src/fixtures/users.yaml deleted file mode 100644 index 8f5b5ed2e2..0000000000 --- a/examples/aws-rust-loco/src/fixtures/users.yaml +++ /dev/null @@ -1,17 +0,0 @@ ---- -- id: 1 - pid: 11111111-1111-1111-1111-111111111111 - email: user1@example.com - password: "$argon2id$v=19$m=19456,t=2,p=1$ETQBx4rTgNAZhSaeYZKOZg$eYTdH26CRT6nUJtacLDEboP0li6xUwUF/q5nSlQ8uuc" - api_key: lo-95ec80d7-cb60-4b70-9b4b-9ef74cb88758 - name: user1 - created_at: "2023-11-12T12:34:56.789Z" - updated_at: "2023-11-12T12:34:56.789Z" -- id: 2 - pid: 22222222-2222-2222-2222-222222222222 - email: user2@example.com - password: "$argon2id$v=19$m=19456,t=2,p=1$ETQBx4rTgNAZhSaeYZKOZg$eYTdH26CRT6nUJtacLDEboP0li6xUwUF/q5nSlQ8uuc" - api_key: lo-153561ca-fa84-4e1b-813a-c62526d0a77e - name: user2 - created_at: "2023-11-12T12:34:56.789Z" - updated_at: "2023-11-12T12:34:56.789Z" diff --git a/examples/aws-rust-loco/src/lib.rs b/examples/aws-rust-loco/src/lib.rs deleted file mode 100644 index bcd9cbed82..0000000000 --- a/examples/aws-rust-loco/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod app; -pub mod controllers; -pub mod mailers; -pub mod models; -pub mod tasks; -pub mod views; -pub mod workers; diff --git a/examples/aws-rust-loco/src/mailers/auth.rs b/examples/aws-rust-loco/src/mailers/auth.rs deleted file mode 100644 index 30bb1bf2f5..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth.rs +++ /dev/null @@ -1,65 +0,0 @@ -// auth mailer -#![allow(non_upper_case_globals)] - -use loco_rs::prelude::*; -use serde_json::json; - -use crate::models::users; - -static welcome: Dir<'_> = include_dir!("src/mailers/auth/welcome"); -static forgot: Dir<'_> = include_dir!("src/mailers/auth/forgot"); -// #[derive(Mailer)] // -- disabled for faster build speed. it works. but lets -// move on for now. - -#[allow(clippy::module_name_repetitions)] -pub struct AuthMailer {} -impl Mailer for AuthMailer {} -impl AuthMailer { - /// Sending welcome email the the given user - /// - /// # Errors - /// - /// When email sending is failed - pub async fn send_welcome(ctx: &AppContext, user: &users::Model) -> Result<()> { - Self::mail_template( - ctx, - &welcome, - mailer::Args { - to: user.email.to_string(), - locals: json!({ - "name": user.name, - "verifyToken": user.email_verification_token, - "domain": ctx.config.server.full_url() - }), - ..Default::default() - }, - ) - .await?; - - Ok(()) - } - - /// Sending forgot password email - /// - /// # Errors - /// - /// When email sending is failed - pub async fn forgot_password(ctx: &AppContext, user: &users::Model) -> Result<()> { - Self::mail_template( - ctx, - &forgot, - mailer::Args { - to: user.email.to_string(), - locals: json!({ - "name": user.name, - "resetToken": user.reset_token, - "domain": ctx.config.server.full_url() - }), - ..Default::default() - }, - ) - .await?; - - Ok(()) - } -} diff --git a/examples/aws-rust-loco/src/mailers/auth/forgot/html.t b/examples/aws-rust-loco/src/mailers/auth/forgot/html.t deleted file mode 100644 index 221dd60205..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth/forgot/html.t +++ /dev/null @@ -1,11 +0,0 @@ -; - - - Hey {{name}}, - Forgot your password? No worries! You can reset it by clicking the link below: - Reset Your Password - If you didn't request a password reset, please ignore this email. - Best regards,
The Loco Team
- - - diff --git a/examples/aws-rust-loco/src/mailers/auth/forgot/subject.t b/examples/aws-rust-loco/src/mailers/auth/forgot/subject.t deleted file mode 100644 index 4938df1e30..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth/forgot/subject.t +++ /dev/null @@ -1 +0,0 @@ -Your reset password link diff --git a/examples/aws-rust-loco/src/mailers/auth/forgot/text.t b/examples/aws-rust-loco/src/mailers/auth/forgot/text.t deleted file mode 100644 index 58c30fd8d1..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth/forgot/text.t +++ /dev/null @@ -1,3 +0,0 @@ -Reset your password with this link: - -http://localhost/reset#{{resetToken}} diff --git a/examples/aws-rust-loco/src/mailers/auth/welcome/html.t b/examples/aws-rust-loco/src/mailers/auth/welcome/html.t deleted file mode 100644 index ae4c41c654..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth/welcome/html.t +++ /dev/null @@ -1,13 +0,0 @@ -; - - - Dear {{name}}, - Welcome to Loco! You can now log in to your account. - Before you get started, please verify your account by clicking the link below: - - Verify Your Account - -

Best regards,
The Loco Team

- - - diff --git a/examples/aws-rust-loco/src/mailers/auth/welcome/subject.t b/examples/aws-rust-loco/src/mailers/auth/welcome/subject.t deleted file mode 100644 index 82cc6fbf7b..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth/welcome/subject.t +++ /dev/null @@ -1 +0,0 @@ -Welcome {{name}} diff --git a/examples/aws-rust-loco/src/mailers/auth/welcome/text.t b/examples/aws-rust-loco/src/mailers/auth/welcome/text.t deleted file mode 100644 index 63beefd565..0000000000 --- a/examples/aws-rust-loco/src/mailers/auth/welcome/text.t +++ /dev/null @@ -1,4 +0,0 @@ -Welcome {{name}}, you can now log in. - Verify your account with the link below: - - http://localhost/verify#{{verifyToken}} diff --git a/examples/aws-rust-loco/src/mailers/mod.rs b/examples/aws-rust-loco/src/mailers/mod.rs deleted file mode 100644 index 0e4a05d597..0000000000 --- a/examples/aws-rust-loco/src/mailers/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod auth; diff --git a/examples/aws-rust-loco/src/models/_entities/mod.rs b/examples/aws-rust-loco/src/models/_entities/mod.rs deleted file mode 100644 index c04afbb655..0000000000 --- a/examples/aws-rust-loco/src/models/_entities/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 - -pub mod prelude; - -pub mod notes; -pub mod users; diff --git a/examples/aws-rust-loco/src/models/_entities/notes.rs b/examples/aws-rust-loco/src/models/_entities/notes.rs deleted file mode 100644 index a803353897..0000000000 --- a/examples/aws-rust-loco/src/models/_entities/notes.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 - -use sea_orm::entity::prelude::*; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] -#[sea_orm(table_name = "notes")] -pub struct Model { - pub created_at: DateTimeWithTimeZone, - pub updated_at: DateTimeWithTimeZone, - #[sea_orm(primary_key)] - pub id: i32, - pub title: Option, - pub content: Option, -} - -#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] -pub enum Relation {} diff --git a/examples/aws-rust-loco/src/models/_entities/prelude.rs b/examples/aws-rust-loco/src/models/_entities/prelude.rs deleted file mode 100644 index 4d1101962e..0000000000 --- a/examples/aws-rust-loco/src/models/_entities/prelude.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 - -pub use super::notes::Entity as Notes; -pub use super::users::Entity as Users; diff --git a/examples/aws-rust-loco/src/models/_entities/users.rs b/examples/aws-rust-loco/src/models/_entities/users.rs deleted file mode 100644 index 120b1a1b1f..0000000000 --- a/examples/aws-rust-loco/src/models/_entities/users.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0 - -use sea_orm::entity::prelude::*; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] -#[sea_orm(table_name = "users")] -pub struct Model { - pub created_at: DateTimeWithTimeZone, - pub updated_at: DateTimeWithTimeZone, - #[sea_orm(primary_key)] - pub id: i32, - pub pid: Uuid, - #[sea_orm(unique)] - pub email: String, - pub password: String, - #[sea_orm(unique)] - pub api_key: String, - pub name: String, - pub reset_token: Option, - pub reset_sent_at: Option, - pub email_verification_token: Option, - pub email_verification_sent_at: Option, - pub email_verified_at: Option, -} - -#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] -pub enum Relation {} diff --git a/examples/aws-rust-loco/src/models/mod.rs b/examples/aws-rust-loco/src/models/mod.rs deleted file mode 100644 index 917969b1c7..0000000000 --- a/examples/aws-rust-loco/src/models/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod _entities; -pub mod notes; -pub mod users; diff --git a/examples/aws-rust-loco/src/models/notes.rs b/examples/aws-rust-loco/src/models/notes.rs deleted file mode 100644 index 1102598236..0000000000 --- a/examples/aws-rust-loco/src/models/notes.rs +++ /dev/null @@ -1,7 +0,0 @@ -use sea_orm::entity::prelude::*; - -use super::_entities::notes::ActiveModel; - -impl ActiveModelBehavior for ActiveModel { - // extend activemodel below (keep comment for generators) -} diff --git a/examples/aws-rust-loco/src/models/users.rs b/examples/aws-rust-loco/src/models/users.rs deleted file mode 100644 index 510802e0bb..0000000000 --- a/examples/aws-rust-loco/src/models/users.rs +++ /dev/null @@ -1,297 +0,0 @@ -use async_trait::async_trait; -use chrono::offset::Local; -use loco_rs::{auth::jwt, hash, prelude::*}; -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -pub use super::_entities::users::{self, ActiveModel, Entity, Model}; - -#[derive(Debug, Deserialize, Serialize)] -pub struct LoginParams { - pub email: String, - pub password: String, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct RegisterParams { - pub email: String, - pub password: String, - pub name: String, -} - -#[derive(Debug, Validate, Deserialize)] -pub struct Validator { - #[validate(length(min = 2, message = "Name must be at least 2 characters long."))] - pub name: String, - #[validate(custom = "validation::is_valid_email")] - pub email: String, -} - -impl Validatable for super::_entities::users::ActiveModel { - fn validator(&self) -> Box { - Box::new(Validator { - name: self.name.as_ref().to_owned(), - email: self.email.as_ref().to_owned(), - }) - } -} - -#[async_trait::async_trait] -impl ActiveModelBehavior for super::_entities::users::ActiveModel { - async fn before_save(self, _db: &C, insert: bool) -> Result - where - C: ConnectionTrait, - { - self.validate()?; - if insert { - let mut this = self; - this.pid = ActiveValue::Set(Uuid::new_v4()); - this.api_key = ActiveValue::Set(format!("lo-{}", Uuid::new_v4())); - Ok(this) - } else { - Ok(self) - } - } -} - -#[async_trait] -impl Authenticable for super::_entities::users::Model { - async fn find_by_api_key(db: &DatabaseConnection, api_key: &str) -> ModelResult { - let user = users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::ApiKey, api_key) - .build(), - ) - .one(db) - .await?; - user.ok_or_else(|| ModelError::EntityNotFound) - } - - async fn find_by_claims_key(db: &DatabaseConnection, claims_key: &str) -> ModelResult { - Self::find_by_pid(db, claims_key).await - } -} - -impl super::_entities::users::Model { - /// finds a user by the provided email - /// - /// # Errors - /// - /// When could not find user by the given token or DB query error - pub async fn find_by_email(db: &DatabaseConnection, email: &str) -> ModelResult { - let user = users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::Email, email) - .build(), - ) - .one(db) - .await?; - user.ok_or_else(|| ModelError::EntityNotFound) - } - - /// finds a user by the provided verification token - /// - /// # Errors - /// - /// When could not find user by the given token or DB query error - pub async fn find_by_verification_token( - db: &DatabaseConnection, - token: &str, - ) -> ModelResult { - let user = users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::EmailVerificationToken, token) - .build(), - ) - .one(db) - .await?; - user.ok_or_else(|| ModelError::EntityNotFound) - } - - /// /// finds a user by the provided reset token - /// - /// # Errors - /// - /// When could not find user by the given token or DB query error - pub async fn find_by_reset_token(db: &DatabaseConnection, token: &str) -> ModelResult { - let user = users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::ResetToken, token) - .build(), - ) - .one(db) - .await?; - user.ok_or_else(|| ModelError::EntityNotFound) - } - - /// finds a user by the provided pid - /// - /// # Errors - /// - /// When could not find user or DB query error - pub async fn find_by_pid(db: &DatabaseConnection, pid: &str) -> ModelResult { - let parse_uuid = Uuid::parse_str(pid).map_err(|e| ModelError::Any(e.into()))?; - let user = users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::Pid, parse_uuid) - .build(), - ) - .one(db) - .await?; - user.ok_or_else(|| ModelError::EntityNotFound) - } - - /// finds a user by the provided api key - /// - /// # Errors - /// - /// When could not find user by the given token or DB query error - pub async fn find_by_api_key(db: &DatabaseConnection, api_key: &str) -> ModelResult { - let user = users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::ApiKey, api_key) - .build(), - ) - .one(db) - .await?; - user.ok_or_else(|| ModelError::EntityNotFound) - } - - /// Verifies whether the provided plain password matches the hashed password - /// - /// # Errors - /// - /// when could not verify password - #[must_use] - pub fn verify_password(&self, password: &str) -> bool { - hash::verify_password(password, &self.password) - } - - /// Asynchronously creates a user with a password and saves it to the - /// database. - /// - /// # Errors - /// - /// When could not save the user into the DB - pub async fn create_with_password( - db: &DatabaseConnection, - params: &RegisterParams, - ) -> ModelResult { - let txn = db.begin().await?; - - if users::Entity::find() - .filter( - model::query::condition() - .eq(users::Column::Email, ¶ms.email) - .build(), - ) - .one(&txn) - .await? - .is_some() - { - return Err(ModelError::EntityAlreadyExists {}); - } - - let password_hash = - hash::hash_password(¶ms.password).map_err(|e| ModelError::Any(e.into()))?; - let user = users::ActiveModel { - email: ActiveValue::set(params.email.to_string()), - password: ActiveValue::set(password_hash), - name: ActiveValue::set(params.name.to_string()), - ..Default::default() - } - .insert(&txn) - .await?; - - txn.commit().await?; - - Ok(user) - } - - /// Creates a JWT - /// - /// # Errors - /// - /// when could not convert user claims to jwt token - pub fn generate_jwt(&self, secret: &str, expiration: &u64) -> ModelResult { - Ok(jwt::JWT::new(secret).generate_token(expiration, self.pid.to_string(), None)?) - } -} - -impl super::_entities::users::ActiveModel { - /// Sets the email verification information for the user and - /// updates it in the database. - /// - /// This method is used to record the timestamp when the email verification - /// was sent and generate a unique verification token for the user. - /// - /// # Errors - /// - /// when has DB query error - pub async fn set_email_verification_sent( - mut self, - db: &DatabaseConnection, - ) -> ModelResult { - self.email_verification_sent_at = ActiveValue::set(Some(Local::now().into())); - self.email_verification_token = ActiveValue::Set(Some(Uuid::new_v4().to_string())); - Ok(self.update(db).await?) - } - - /// Sets the information for a reset password request, - /// generates a unique reset password token, and updates it in the - /// database. - /// - /// This method records the timestamp when the reset password token is sent - /// and generates a unique token for the user. - /// - /// # Arguments - /// - /// # Errors - /// - /// when has DB query error - pub async fn set_forgot_password_sent(mut self, db: &DatabaseConnection) -> ModelResult { - self.reset_sent_at = ActiveValue::set(Some(Local::now().into())); - self.reset_token = ActiveValue::Set(Some(Uuid::new_v4().to_string())); - Ok(self.update(db).await?) - } - - /// Records the verification time when a user verifies their - /// email and updates it in the database. - /// - /// This method sets the timestamp when the user successfully verifies their - /// email. - /// - /// # Errors - /// - /// when has DB query error - pub async fn verified(mut self, db: &DatabaseConnection) -> ModelResult { - self.email_verified_at = ActiveValue::set(Some(Local::now().into())); - Ok(self.update(db).await?) - } - - /// Resets the current user password with a new password and - /// updates it in the database. - /// - /// This method hashes the provided password and sets it as the new password - /// for the user. - /// # Errors - /// - /// when has DB query error or could not hashed the given password - pub async fn reset_password( - mut self, - db: &DatabaseConnection, - password: &str, - ) -> ModelResult { - self.password = - ActiveValue::set(hash::hash_password(password).map_err(|e| ModelError::Any(e.into()))?); - self.reset_token = ActiveValue::Set(None); - self.reset_sent_at = ActiveValue::Set(None); - Ok(self.update(db).await?) - } -} diff --git a/examples/aws-rust-loco/src/tasks/mod.rs b/examples/aws-rust-loco/src/tasks/mod.rs deleted file mode 100644 index 01fbddaa29..0000000000 --- a/examples/aws-rust-loco/src/tasks/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod seed; diff --git a/examples/aws-rust-loco/src/tasks/seed.rs b/examples/aws-rust-loco/src/tasks/seed.rs deleted file mode 100644 index 1647beb84c..0000000000 --- a/examples/aws-rust-loco/src/tasks/seed.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! This task implements data seeding functionality for initializing new -//! development/demo environments. -//! -//! # Example -//! -//! Run the task with the following command: -//! ```sh -//! cargo run task -//! ``` -//! -//! To override existing data and reset the data structure, use the following -//! command with the `refresh:true` argument: -//! ```sh -//! cargo run task seed_data refresh:true -//! ``` - -use loco_rs::{db, prelude::*}; -use migration::Migrator; - -use crate::app::App; - -#[allow(clippy::module_name_repetitions)] -pub struct SeedData; -#[async_trait] -impl Task for SeedData { - fn task(&self) -> TaskInfo { - TaskInfo { - name: "seed_data".to_string(), - detail: "Task for seeding data".to_string(), - } - } - - async fn run(&self, app_context: &AppContext, vars: &task::Vars) -> Result<()> { - let refresh = vars - .cli_arg("refresh") - .is_ok_and(|refresh| refresh == "true"); - - if refresh { - db::reset::(&app_context.db).await?; - } - let path = std::path::Path::new("src/fixtures"); - db::run_app_seed::(&app_context.db, path).await?; - Ok(()) - } -} diff --git a/examples/aws-rust-loco/src/views/auth.rs b/examples/aws-rust-loco/src/views/auth.rs deleted file mode 100644 index 2240a5087e..0000000000 --- a/examples/aws-rust-loco/src/views/auth.rs +++ /dev/null @@ -1,23 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::models::_entities::users; - -#[derive(Debug, Deserialize, Serialize)] -pub struct LoginResponse { - pub token: String, - pub pid: String, - pub name: String, - pub is_verified: bool, -} - -impl LoginResponse { - #[must_use] - pub fn new(user: &users::Model, token: &String) -> Self { - Self { - token: token.to_string(), - pid: user.pid.to_string(), - name: user.name.clone(), - is_verified: user.email_verified_at.is_some(), - } - } -} diff --git a/examples/aws-rust-loco/src/views/mod.rs b/examples/aws-rust-loco/src/views/mod.rs deleted file mode 100644 index f9bae3db2a..0000000000 --- a/examples/aws-rust-loco/src/views/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod auth; -pub mod user; diff --git a/examples/aws-rust-loco/src/views/user.rs b/examples/aws-rust-loco/src/views/user.rs deleted file mode 100644 index 9d830410fb..0000000000 --- a/examples/aws-rust-loco/src/views/user.rs +++ /dev/null @@ -1,21 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::models::_entities::users; - -#[derive(Debug, Deserialize, Serialize)] -pub struct CurrentResponse { - pub pid: String, - pub name: String, - pub email: String, -} - -impl CurrentResponse { - #[must_use] - pub fn new(user: &users::Model) -> Self { - Self { - pid: user.pid.to_string(), - name: user.name.clone(), - email: user.email.clone(), - } - } -} diff --git a/examples/aws-rust-loco/src/workers/downloader.rs b/examples/aws-rust-loco/src/workers/downloader.rs deleted file mode 100644 index 42c0bd7a46..0000000000 --- a/examples/aws-rust-loco/src/workers/downloader.rs +++ /dev/null @@ -1,43 +0,0 @@ -use std::time::Duration; - -use loco_rs::prelude::*; -use serde::{Deserialize, Serialize}; -use tokio::time::sleep; - -use crate::models::users; - -pub struct DownloadWorker { - pub ctx: AppContext, -} - -#[derive(Deserialize, Debug, Serialize)] -pub struct DownloadWorkerArgs { - pub user_guid: String, -} - -impl worker::AppWorker for DownloadWorker { - fn build(ctx: &AppContext) -> Self { - Self { ctx: ctx.clone() } - } -} - -#[async_trait] -impl worker::Worker for DownloadWorker { - async fn perform(&self, args: DownloadWorkerArgs) -> worker::Result<()> { - // TODO: Some actual work goes here... - println!("================================================"); - println!("Sending payment report to user {}", args.user_guid); - - sleep(Duration::from_millis(2000)).await; - - let all = users::Entity::find() - .all(&self.ctx.db) - .await - .map_err(Box::from)?; - for user in &all { - println!("user: {}", user.id); - } - println!("================================================"); - Ok(()) - } -} diff --git a/examples/aws-rust-loco/src/workers/mod.rs b/examples/aws-rust-loco/src/workers/mod.rs deleted file mode 100644 index acb5733da2..0000000000 --- a/examples/aws-rust-loco/src/workers/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod downloader; diff --git a/examples/aws-rust-loco/sst.config.ts b/examples/aws-rust-loco/sst.config.ts deleted file mode 100644 index bc9a6289d8..0000000000 --- a/examples/aws-rust-loco/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## Rust Loco - * - * Deploy a Rust Loco app with a Postgres database, Redis, and a background worker - * service. - */ -export default $config({ - app(input) { - return { - name: "aws-rust-loco", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("LocoVpc", { - bastion: true, - }); - - const database = new sst.aws.Postgres("LocoDatabase", { vpc }); - - const redis = new sst.aws.Redis("LocoRedis", { vpc }); - - const DATABASE_URL = $interpolate`postgres://${ - database.username - }:${database.password.apply(encodeURIComponent)}@${database.host}:${ - database.port - }/${database.database}`; - const REDIS_URL = $interpolate`redis://${ - redis.username - }:${redis.password.apply(encodeURIComponent)}@${redis.host}:${redis.port}`; - - const locoCluster = new sst.aws.Cluster("LocoCluster", { vpc }); - - // external facing http service - const locoServer = new sst.aws.Service("LocoApp", { - cluster: locoCluster, - architecture: "x86_64", - scaling: { min: 2, max: 4 }, - command: ["start"], - loadBalancer: { - ports: [{ listen: "80/http", forward: "5150/http" }], - }, - environment: { - DATABASE_URL, - REDIS_URL, - }, - link: [database, redis], - dev: { - command: "cargo loco start", - }, - }); - - // add a worker that uses redis to process jobs off a queue - new sst.aws.Service("LocoWorker", { - cluster: locoCluster, - architecture: "x86_64", - command: ["start", "--worker"], - environment: { - DATABASE_URL, - REDIS_URL, - }, - link: [database, redis], - }); - }, -}); diff --git a/examples/aws-rust-loco/tests/mod.rs b/examples/aws-rust-loco/tests/mod.rs deleted file mode 100644 index e56e882575..0000000000 --- a/examples/aws-rust-loco/tests/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod models; -mod requests; -mod tasks; diff --git a/examples/aws-rust-loco/tests/models/mod.rs b/examples/aws-rust-loco/tests/models/mod.rs deleted file mode 100644 index 59759880db..0000000000 --- a/examples/aws-rust-loco/tests/models/mod.rs +++ /dev/null @@ -1 +0,0 @@ -mod users; diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_create_with_password@users.snap b/examples/aws-rust-loco/tests/models/snapshots/can_create_with_password@users.snap deleted file mode 100644 index 6e66fd35ae..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_create_with_password@users.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: tests/models/users.rs -expression: res ---- -Ok( - Model { - created_at: DATE, - updated_at: DATE, - id: ID - pid: PID, - email: "test@framework.com", - password: "PASSWORD", - api_key: "lo-PID", - name: "framework", - reset_token: None, - reset_sent_at: None, - email_verification_token: None, - email_verification_sent_at: None, - email_verified_at: None, - }, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email-2@users.snap b/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email-2@users.snap deleted file mode 100644 index 83dc06e1d9..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email-2@users.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tests/models/main.rs -expression: non_existing_user_results ---- -Err( - EntityNotFound, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email@users-2.snap b/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email@users-2.snap deleted file mode 100644 index 25c700a5a8..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email@users-2.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tests/models/users.rs -expression: non_existing_user_results ---- -Err( - EntityNotFound, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email@users.snap b/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email@users.snap deleted file mode 100644 index 067d0e7521..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_email@users.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: tests/models/users.rs -expression: existing_user ---- -Ok( - Model { - created_at: 2023-11-12T12:34:56.789+00:00, - updated_at: 2023-11-12T12:34:56.789+00:00, - id: 1, - pid: 11111111-1111-1111-1111-111111111111, - email: "user1@example.com", - password: "$argon2id$v=19$m=19456,t=2,p=1$ETQBx4rTgNAZhSaeYZKOZg$eYTdH26CRT6nUJtacLDEboP0li6xUwUF/q5nSlQ8uuc", - api_key: "lo-95ec80d7-cb60-4b70-9b4b-9ef74cb88758", - name: "user1", - reset_token: None, - reset_sent_at: None, - email_verification_token: None, - email_verification_sent_at: None, - email_verified_at: None, - }, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid-2@users.snap b/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid-2@users.snap deleted file mode 100644 index 83dc06e1d9..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid-2@users.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tests/models/main.rs -expression: non_existing_user_results ---- -Err( - EntityNotFound, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid@users-2.snap b/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid@users-2.snap deleted file mode 100644 index 25c700a5a8..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid@users-2.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tests/models/users.rs -expression: non_existing_user_results ---- -Err( - EntityNotFound, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid@users.snap b/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid@users.snap deleted file mode 100644 index 067d0e7521..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_find_by_pid@users.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: tests/models/users.rs -expression: existing_user ---- -Ok( - Model { - created_at: 2023-11-12T12:34:56.789+00:00, - updated_at: 2023-11-12T12:34:56.789+00:00, - id: 1, - pid: 11111111-1111-1111-1111-111111111111, - email: "user1@example.com", - password: "$argon2id$v=19$m=19456,t=2,p=1$ETQBx4rTgNAZhSaeYZKOZg$eYTdH26CRT6nUJtacLDEboP0li6xUwUF/q5nSlQ8uuc", - api_key: "lo-95ec80d7-cb60-4b70-9b4b-9ef74cb88758", - name: "user1", - reset_token: None, - reset_sent_at: None, - email_verification_token: None, - email_verification_sent_at: None, - email_verified_at: None, - }, -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/can_validate_model@users.snap b/examples/aws-rust-loco/tests/models/snapshots/can_validate_model@users.snap deleted file mode 100644 index 4d457a7032..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/can_validate_model@users.snap +++ /dev/null @@ -1,9 +0,0 @@ ---- -source: tests/models/main.rs -expression: res ---- -Err( - Custom( - "{\"email\":[{\"code\":\"invalid email\",\"message\":null}],\"name\":[{\"code\":\"length\",\"message\":\"Name must be at least 2 characters long.\"}]}", - ), -) diff --git a/examples/aws-rust-loco/tests/models/snapshots/handle_create_with_password_with_duplicate@users.snap b/examples/aws-rust-loco/tests/models/snapshots/handle_create_with_password_with_duplicate@users.snap deleted file mode 100644 index ff28ea196a..0000000000 --- a/examples/aws-rust-loco/tests/models/snapshots/handle_create_with_password_with_duplicate@users.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tests/models/users.rs -expression: new_user ---- -Err( - EntityAlreadyExists, -) diff --git a/examples/aws-rust-loco/tests/models/users.rs b/examples/aws-rust-loco/tests/models/users.rs deleted file mode 100644 index f57a32213e..0000000000 --- a/examples/aws-rust-loco/tests/models/users.rs +++ /dev/null @@ -1,223 +0,0 @@ -use insta::assert_debug_snapshot; -use loco_rs::{model::ModelError, testing}; -use server::{ - app::App, - models::users::{self, Model, RegisterParams}, -}; -use sea_orm::{ActiveModelTrait, ActiveValue, IntoActiveModel}; -use serial_test::serial; - -macro_rules! configure_insta { - ($($expr:expr),*) => { - let mut settings = insta::Settings::clone_current(); - settings.set_prepend_module_to_snapshot(false); - settings.set_snapshot_suffix("users"); - let _guard = settings.bind_to_scope(); - }; -} - -#[tokio::test] -#[serial] -async fn test_can_validate_model() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - - let res = users::ActiveModel { - name: ActiveValue::set("1".to_string()), - email: ActiveValue::set("invalid-email".to_string()), - ..Default::default() - } - .insert(&boot.app_context.db) - .await; - - assert_debug_snapshot!(res); -} - -#[tokio::test] -#[serial] -async fn can_create_with_password() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - - let params = RegisterParams { - email: "test@framework.com".to_string(), - password: "1234".to_string(), - name: "framework".to_string(), - }; - let res = Model::create_with_password(&boot.app_context.db, ¶ms).await; - - insta::with_settings!({ - filters => testing::cleanup_user_model() - }, { - assert_debug_snapshot!(res); - }); -} - -#[tokio::test] -#[serial] -async fn handle_create_with_password_with_duplicate() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let new_user: Result = Model::create_with_password( - &boot.app_context.db, - &RegisterParams { - email: "user1@example.com".to_string(), - password: "1234".to_string(), - name: "framework".to_string(), - }, - ) - .await; - assert_debug_snapshot!(new_user); -} - -#[tokio::test] -#[serial] -async fn can_find_by_email() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let existing_user = Model::find_by_email(&boot.app_context.db, "user1@example.com").await; - let non_existing_user_results = - Model::find_by_email(&boot.app_context.db, "un@existing-email.com").await; - - assert_debug_snapshot!(existing_user); - assert_debug_snapshot!(non_existing_user_results); -} - -#[tokio::test] -#[serial] -async fn can_find_by_pid() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let existing_user = - Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111").await; - let non_existing_user_results = - Model::find_by_pid(&boot.app_context.db, "23232323-2323-2323-2323-232323232323").await; - - assert_debug_snapshot!(existing_user); - assert_debug_snapshot!(non_existing_user_results); -} - -#[tokio::test] -#[serial] -async fn can_verification_token() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.email_verification_sent_at.is_none()); - assert!(user.email_verification_token.is_none()); - - assert!(user - .into_active_model() - .set_email_verification_sent(&boot.app_context.db) - .await - .is_ok()); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.email_verification_sent_at.is_some()); - assert!(user.email_verification_token.is_some()); -} - -#[tokio::test] -#[serial] -async fn can_set_forgot_password_sent() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.reset_sent_at.is_none()); - assert!(user.reset_token.is_none()); - - assert!(user - .into_active_model() - .set_forgot_password_sent(&boot.app_context.db) - .await - .is_ok()); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.reset_sent_at.is_some()); - assert!(user.reset_token.is_some()); -} - -#[tokio::test] -#[serial] -async fn can_verified() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.email_verified_at.is_none()); - - assert!(user - .into_active_model() - .verified(&boot.app_context.db) - .await - .is_ok()); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.email_verified_at.is_some()); -} - -#[tokio::test] -#[serial] -async fn can_reset_password() { - configure_insta!(); - - let boot = testing::boot_test::().await.unwrap(); - testing::seed::(&boot.app_context.db).await.unwrap(); - - let user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap(); - - assert!(user.verify_password("12341234")); - - assert!(user - .clone() - .into_active_model() - .reset_password(&boot.app_context.db, "new-password") - .await - .is_ok()); - - assert!( - Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111") - .await - .unwrap() - .verify_password("new-password") - ); -} diff --git a/examples/aws-rust-loco/tests/requests/auth.rs b/examples/aws-rust-loco/tests/requests/auth.rs deleted file mode 100644 index 43352ed1c7..0000000000 --- a/examples/aws-rust-loco/tests/requests/auth.rs +++ /dev/null @@ -1,195 +0,0 @@ -use insta::{assert_debug_snapshot, with_settings}; -use loco_rs::testing; -use server::{app::App, models::users}; -use rstest::rstest; -use serial_test::serial; - -use super::prepare_data; - -// TODO: see how to dedup / extract this to app-local test utils -// not to framework, because that would require a runtime dep on insta -macro_rules! configure_insta { - ($($expr:expr),*) => { - let mut settings = insta::Settings::clone_current(); - settings.set_prepend_module_to_snapshot(false); - settings.set_snapshot_suffix("auth_request"); - let _guard = settings.bind_to_scope(); - }; -} - -#[tokio::test] -#[serial] -async fn can_register() { - configure_insta!(); - - testing::request::(|request, ctx| async move { - let email = "test@loco.com"; - let payload = serde_json::json!({ - "name": "loco", - "email": email, - "password": "12341234" - }); - - let _response = request.post("/api/auth/register").json(&payload).await; - let saved_user = users::Model::find_by_email(&ctx.db, email).await; - - with_settings!({ - filters => testing::cleanup_user_model() - }, { - assert_debug_snapshot!(saved_user); - }); - - with_settings!({ - filters => testing::cleanup_email() - }, { - assert_debug_snapshot!(ctx.mailer.unwrap().deliveries()); - }); - }) - .await; -} - -#[rstest] -#[case("login_with_valid_password", "12341234")] -#[case("login_with_invalid_password", "invalid-password")] -#[tokio::test] -#[serial] -async fn can_login_with_verify(#[case] test_name: &str, #[case] password: &str) { - configure_insta!(); - - testing::request::(|request, ctx| async move { - let email = "test@loco.com"; - let register_payload = serde_json::json!({ - "name": "loco", - "email": email, - "password": "12341234" - }); - - //Creating a new user - _ = request - .post("/api/auth/register") - .json(®ister_payload) - .await; - - let user = users::Model::find_by_email(&ctx.db, email).await.unwrap(); - let verify_payload = serde_json::json!({ - "token": user.email_verification_token, - }); - request.post("/api/auth/verify").json(&verify_payload).await; - - //verify user request - let response = request - .post("/api/auth/login") - .json(&serde_json::json!({ - "email": email, - "password": password - })) - .await; - - // Make sure email_verified_at is set - assert!(users::Model::find_by_email(&ctx.db, email) - .await - .unwrap() - .email_verified_at - .is_some()); - - with_settings!({ - filters => testing::cleanup_user_model() - }, { - assert_debug_snapshot!(test_name, (response.status_code(), response.text())); - }); - }) - .await; -} - -#[tokio::test] -#[serial] -async fn can_login_without_verify() { - configure_insta!(); - - testing::request::(|request, _ctx| async move { - let email = "test@loco.com"; - let password = "12341234"; - let register_payload = serde_json::json!({ - "name": "loco", - "email": email, - "password": password - }); - - //Creating a new user - _ = request - .post("/api/auth/register") - .json(®ister_payload) - .await; - - //verify user request - let response = request - .post("/api/auth/login") - .json(&serde_json::json!({ - "email": email, - "password": password - })) - .await; - - with_settings!({ - filters => testing::cleanup_user_model() - }, { - assert_debug_snapshot!((response.status_code(), response.text())); - }); - }) - .await; -} - -#[tokio::test] -#[serial] -async fn can_reset_password() { - configure_insta!(); - - testing::request::(|request, ctx| async move { - let login_data = prepare_data::init_user_login(&request, &ctx).await; - - let forgot_payload = serde_json::json!({ - "email": login_data.user.email, - }); - _ = request.post("/api/auth/forgot").json(&forgot_payload).await; - - let user = users::Model::find_by_email(&ctx.db, &login_data.user.email) - .await - .unwrap(); - assert!(user.reset_token.is_some()); - assert!(user.reset_sent_at.is_some()); - - let new_password = "new-password"; - let reset_payload = serde_json::json!({ - "token": user.reset_token, - "password": new_password, - }); - - let reset_response = request.post("/api/auth/reset").json(&reset_payload).await; - - let user = users::Model::find_by_email(&ctx.db, &user.email) - .await - .unwrap(); - - assert!(user.reset_token.is_none()); - assert!(user.reset_sent_at.is_none()); - - assert_debug_snapshot!((reset_response.status_code(), reset_response.text())); - - let response = request - .post("/api/auth/login") - .json(&serde_json::json!({ - "email": user.email, - "password": new_password - })) - .await; - - assert_eq!(response.status_code(), 200); - - with_settings!({ - filters => testing::cleanup_email() - }, { - assert_debug_snapshot!(ctx.mailer.unwrap().deliveries()); - }); - }) - .await; -} diff --git a/examples/aws-rust-loco/tests/requests/mod.rs b/examples/aws-rust-loco/tests/requests/mod.rs deleted file mode 100644 index 81ed68f960..0000000000 --- a/examples/aws-rust-loco/tests/requests/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -mod auth; -mod notes; -mod prepare_data; -mod user; diff --git a/examples/aws-rust-loco/tests/requests/notes.rs b/examples/aws-rust-loco/tests/requests/notes.rs deleted file mode 100644 index 4709cf6f47..0000000000 --- a/examples/aws-rust-loco/tests/requests/notes.rs +++ /dev/null @@ -1,123 +0,0 @@ -use insta::{assert_debug_snapshot, with_settings}; -use loco_rs::testing; -use server::{app::App, models::_entities::notes::Entity}; -use sea_orm::entity::prelude::*; -use serial_test::serial; - -// TODO: see how to dedup / extract this to app-local test utils -// not to framework, because that would require a runtime dep on insta -macro_rules! configure_insta { - ($($expr:expr),*) => { - let mut settings = insta::Settings::clone_current(); - settings.set_prepend_module_to_snapshot(false); - settings.set_snapshot_suffix("notes_request"); - let _guard = settings.bind_to_scope(); - }; -} - -#[tokio::test] -#[serial] -async fn can_get_notes() { - configure_insta!(); - - testing::request::(|request, ctx| async move { - testing::seed::(&ctx.db).await.unwrap(); - - let notes = request.get("/api/notes").await; - - with_settings!({ - filters => { - let mut combined_filters = testing::CLEANUP_DATE.to_vec(); - combined_filters.extend(vec![(r#"\"id\\":\d+"#, r#""id\":ID"#)]); - combined_filters - } - }, { - assert_debug_snapshot!( - (notes.status_code(), notes.text()) - ); - }); - }) - .await; -} - -#[tokio::test] -#[serial] -async fn can_add_note() { - configure_insta!(); - - testing::request::(|request, _ctx| async move { - let payload = serde_json::json!({ - "title": "loco", - "content": "loco note test", - }); - - let add_note_request = request.post("/api/notes").json(&payload).await; - - with_settings!({ - filters => { - let mut combined_filters = testing::CLEANUP_DATE.to_vec(); - combined_filters.extend(vec![(r#"\"id\\":\d+"#, r#""id\":ID"#)]); - combined_filters - } - }, { - assert_debug_snapshot!( - (add_note_request.status_code(), add_note_request.text()) - ); - }); - }) - .await; -} - -#[tokio::test] -#[serial] -async fn can_get_note() { - configure_insta!(); - - testing::request::(|request, ctx| async move { - testing::seed::(&ctx.db).await.unwrap(); - - let add_note_request = request.get("/api/notes/1").await; - - with_settings!({ - filters => { - let mut combined_filters = testing::CLEANUP_DATE.to_vec(); - combined_filters.extend(vec![(r#"\"id\\":\d+"#, r#""id\":ID"#)]); - combined_filters - } - }, { - assert_debug_snapshot!( - (add_note_request.status_code(), add_note_request.text()) - ); - }); - }) - .await; -} - -#[tokio::test] -#[serial] -async fn can_delete_note() { - configure_insta!(); - - testing::request::(|request, ctx| async move { - testing::seed::(&ctx.db).await.unwrap(); - - let count_before_delete = Entity::find().all(&ctx.db).await.unwrap().len(); - let delete_note_request = request.delete("/api/notes/1").await; - - with_settings!({ - filters => { - let mut combined_filters = testing::CLEANUP_DATE.to_vec(); - combined_filters.extend(vec![(r#"\"id\\":\d+"#, r#""id\":ID"#)]); - combined_filters - } - }, { - assert_debug_snapshot!( - (delete_note_request.status_code(), delete_note_request.text()) - ); - }); - - let count_after_delete = Entity::find().all(&ctx.db).await.unwrap().len(); - assert_eq!(count_after_delete, count_before_delete - 1); - }) - .await; -} diff --git a/examples/aws-rust-loco/tests/requests/prepare_data.rs b/examples/aws-rust-loco/tests/requests/prepare_data.rs deleted file mode 100644 index 13f9940a7a..0000000000 --- a/examples/aws-rust-loco/tests/requests/prepare_data.rs +++ /dev/null @@ -1,57 +0,0 @@ -use axum::http::{HeaderName, HeaderValue}; -use loco_rs::{app::AppContext, TestServer}; -use server::{models::users, views::auth::LoginResponse}; - -const USER_EMAIL: &str = "test@loco.com"; -const USER_PASSWORD: &str = "1234"; - -pub struct LoggedInUser { - pub user: users::Model, - pub token: String, -} - -pub async fn init_user_login(request: &TestServer, ctx: &AppContext) -> LoggedInUser { - let register_payload = serde_json::json!({ - "name": "loco", - "email": USER_EMAIL, - "password": USER_PASSWORD - }); - - //Creating a new user - request - .post("/api/auth/register") - .json(®ister_payload) - .await; - let user = users::Model::find_by_email(&ctx.db, USER_EMAIL) - .await - .unwrap(); - - let verify_payload = serde_json::json!({ - "token": user.email_verification_token, - }); - - request.post("/api/auth/verify").json(&verify_payload).await; - - let response = request - .post("/api/auth/login") - .json(&serde_json::json!({ - "email": USER_EMAIL, - "password": USER_PASSWORD - })) - .await; - - let login_response: LoginResponse = serde_json::from_str(&response.text()).unwrap(); - - LoggedInUser { - user: users::Model::find_by_email(&ctx.db, USER_EMAIL) - .await - .unwrap(), - token: login_response.token, - } -} - -pub fn auth_header(token: &str) -> (HeaderName, HeaderValue) { - let auth_header_value = HeaderValue::from_str(&format!("Bearer {}", &token)).unwrap(); - - (HeaderName::from_static("authorization"), auth_header_value) -} diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_add_note@notes_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_add_note@notes_request.snap deleted file mode 100644 index f8457d7a47..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_add_note@notes_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/notes.rs -expression: "(add_note_request.status_code(), add_note_request.text())" ---- -( - 200, - "{\"created_at\":\"DATEZ\",\"updated_at\":\"DATEZ\",\"id\":ID,\"title\":\"loco\",\"content\":\"loco note test\"}", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_delete_note@notes_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_delete_note@notes_request.snap deleted file mode 100644 index 3481fc36d8..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_delete_note@notes_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/notes.rs -expression: "(delete_note_request.status_code(), delete_note_request.text())" ---- -( - 200, - "", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_get_current_user@user_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_get_current_user@user_request.snap deleted file mode 100644 index 85d53db17c..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_get_current_user@user_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/user.rs -expression: "(response.status_code(), response.text())" ---- -( - 200, - "{\"pid\":\"PID\",\"name\":\"loco\",\"email\":\"test@loco.com\"}", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_get_current_user_with_api_key@user_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_get_current_user_with_api_key@user_request.snap deleted file mode 100644 index 85d53db17c..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_get_current_user_with_api_key@user_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/user.rs -expression: "(response.status_code(), response.text())" ---- -( - 200, - "{\"pid\":\"PID\",\"name\":\"loco\",\"email\":\"test@loco.com\"}", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_get_note@notes_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_get_note@notes_request.snap deleted file mode 100644 index 8af1604c96..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_get_note@notes_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/notes.rs -expression: "(add_note_request.status_code(), add_note_request.text())" ---- -( - 200, - "{\"created_at\":\"DATEZ\",\"updated_at\":\"DATEZ\",\"id\":ID,\"title\":\"Loco note 1\",\"content\":\"Loco note 1 content\"}", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_get_notes@notes_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_get_notes@notes_request.snap deleted file mode 100644 index 014b75c03d..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_get_notes@notes_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/notes.rs -expression: "(notes.status_code(), notes.text())" ---- -( - 200, - "[{\"created_at\":\"DATEZ\",\"updated_at\":\"DATEZ\",\"id\":ID,\"title\":\"Loco note 1\",\"content\":\"Loco note 1 content\"},{\"created_at\":\"DATEZ\",\"updated_at\":\"DATEZ\",\"id\":ID,\"title\":\"Loco note 2\",\"content\":\"Loco note 2 content\"}]", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_login_without_verify@auth_request.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_login_without_verify@auth_request.snap deleted file mode 100644 index ef54ba6711..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_login_without_verify@auth_request.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tests/requests/auth.rs -expression: "(response.status_code(), response.text())" ---- -( - 200, - "{\"token\":\"TOKEN\",\"pid\":\"PID\",\"name\":\"loco\",\"is_verified\":false}", -) diff --git a/examples/aws-rust-loco/tests/requests/snapshots/can_register@auth_request-2.snap b/examples/aws-rust-loco/tests/requests/snapshots/can_register@auth_request-2.snap deleted file mode 100644 index 45c63cb14c..0000000000 --- a/examples/aws-rust-loco/tests/requests/snapshots/can_register@auth_request-2.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: tests/requests/auth.rs -expression: ctx.mailer.unwrap().deliveries() ---- -Deliveries { - count: 1, - messages: [ - "From: System \r\nTo: test@loco.com\r\nSubject: Welcome =?utf-8?b?bG9jbwo=?=\r\nMIME-Version: 1.0\r\nDate: DATE\r\nContent-Type: multipart/alternative;\r\n boundary=\"IDENTIFIER\"\r\n\r\n--IDENTIFIER\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\nWelcome loco, you can now log in.\r\n Verify your account with the link below:\r\n\r\n http://localhost/verify#RANDOM_ID\r\n\r\n--IDENTIFIER\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n;\r\n\r\n\r\n Dear loco,\r\n Welcome to Loco! You can now log in to your account.\r\n Before you get started, please verify your account by clicking the link b=\r\nelow:\r\n \r\nTo: test@loco.com\r\nSubject: Welcome =?utf-8?b?bG9jbwo=?=\r\nMIME-Version: 1.0\r\nDate: DATE\r\nContent-Type: multipart/alternative;\r\n boundary=\"IDENTIFIER\"\r\n\r\n--IDENTIFIER\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\nWelcome loco, you can now log in.\r\n Verify your account with the link below:\r\n\r\n http://localhost/verify#RANDOM_ID\r\n\r\n--IDENTIFIER\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n;\r\n\r\n\r\n Dear loco,\r\n Welcome to Loco! You can now log in to your account.\r\n Before you get started, please verify your account by clicking the link b=\r\nelow:\r\n \r\nTo: test@loco.com\r\nSubject: Your reset password =?utf-8?b?bGluawo=?=\r\nMIME-Version: 1.0\r\nDate: DATE\r\nContent-Type: multipart/alternative;\r\n boundary=\"IDENTIFIER\"\r\n\r\n--IDENTIFIER\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\nReset your password with this link:\r\n\r\nhttp://localhost/reset#RANDOM_ID\r\n\r\n--IDENTIFIER\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n;\r\n\r\n\r\n Hey loco,\r\n Forgot your password? No worries! You can reset it by clicking the link b=\r\nelow:\r\n { - let mut settings = insta::Settings::clone_current(); - settings.set_prepend_module_to_snapshot(false); - settings.set_snapshot_suffix("user_request"); - let _guard = settings.bind_to_scope(); - }; -} - -#[tokio::test] -#[serial] -async fn can_get_current_user() { - configure_insta!(); - - testing::request::(|request, ctx| async move { - let user = prepare_data::init_user_login(&request, &ctx).await; - - let (auth_key, auth_value) = prepare_data::auth_header(&user.token); - let response = request - .get("/api/user/current") - .add_header(auth_key, auth_value) - .await; - - with_settings!({ - filters => testing::cleanup_user_model() - }, { - assert_debug_snapshot!((response.status_code(), response.text())); - }); - }) - .await; -} diff --git a/examples/aws-rust-loco/tests/tasks/mod.rs b/examples/aws-rust-loco/tests/tasks/mod.rs deleted file mode 100644 index 01fbddaa29..0000000000 --- a/examples/aws-rust-loco/tests/tasks/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod seed; diff --git a/examples/aws-rust-loco/tests/tasks/seed.rs b/examples/aws-rust-loco/tests/tasks/seed.rs deleted file mode 100644 index 444c53b697..0000000000 --- a/examples/aws-rust-loco/tests/tasks/seed.rs +++ /dev/null @@ -1,17 +0,0 @@ -use loco_rs::{boot::run_task, task, testing}; -use server::app::App; -use serial_test::serial; - -#[tokio::test] -#[serial] -async fn test_can_seed_data() { - let boot = testing::boot_test::().await.unwrap(); - - assert!(run_task::( - &boot.app_context, - Some(&"seed_data".to_string()), - &task::Vars::default() - ) - .await - .is_ok()); -} diff --git a/examples/aws-service-discovery/.dockerignore b/examples/aws-service-discovery/.dockerignore deleted file mode 100644 index 52467addcf..0000000000 --- a/examples/aws-service-discovery/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules - -# sst -.sst diff --git a/examples/aws-service-discovery/.gitignore b/examples/aws-service-discovery/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-service-discovery/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-service-discovery/Dockerfile b/examples/aws-service-discovery/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-service-discovery/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-service-discovery/index.mjs b/examples/aws-service-discovery/index.mjs deleted file mode 100644 index 4bedf3130f..0000000000 --- a/examples/aws-service-discovery/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import express from "express"; - -const PORT = 80; - -const app = express(); - -app.get("/", (_req, res) => { - res.send(`Hello from http://localhost:${PORT}`) -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-service-discovery/lambda.ts b/examples/aws-service-discovery/lambda.ts deleted file mode 100644 index f7a871f838..0000000000 --- a/examples/aws-service-discovery/lambda.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Resource } from "sst"; - -export async function handler() { - const response = await fetch( - `http://${Resource.MyService.service}` - ); - - return { - statusCode: 200, - body: await response.text(), - }; -} diff --git a/examples/aws-service-discovery/package.json b/examples/aws-service-discovery/package.json deleted file mode 100644 index 078810d63a..0000000000 --- a/examples/aws-service-discovery/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-service-discovery", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "express": "^4.21.1", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-service-discovery/sst.config.ts b/examples/aws-service-discovery/sst.config.ts deleted file mode 100644 index 8e2fc28f1a..0000000000 --- a/examples/aws-service-discovery/sst.config.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -/** - * ## AWS Cluster Service Discovery - * - * In this example, we are connecting to a service running on a cluster using its AWS Cloud - * Map service host name. This is useful for service discovery. - * - * We are deploying a service to a cluster in a VPC. And we can access it within the VPC using - * the service's cloud map hostname. - * - * ```ts title="lambda.ts" - * const response = await fetch(`http://${Resource.MyService.service}`); - * ``` - * - * Here we are accessing it through a Lambda function that's linked to the service and is - * deployed to the same VPC. - */ -export default $config({ - app(input) { - return { - name: "aws-service-discovery", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { nat: "ec2" }); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - const service = new sst.aws.Service("MyService", { cluster }); - - new sst.aws.Function("MyFunction", { - vpc, - url: true, - link: [service], - handler: "lambda.handler", - }); - }, -}); diff --git a/examples/aws-service-discovery/tsconfig.json b/examples/aws-service-discovery/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-service-discovery/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-service-transform-container/.dockerignore b/examples/aws-service-transform-container/.dockerignore deleted file mode 100644 index 52467addcf..0000000000 --- a/examples/aws-service-transform-container/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules - -# sst -.sst diff --git a/examples/aws-service-transform-container/.gitignore b/examples/aws-service-transform-container/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-service-transform-container/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-service-transform-container/Dockerfile b/examples/aws-service-transform-container/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-service-transform-container/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-service-transform-container/index.mjs b/examples/aws-service-transform-container/index.mjs deleted file mode 100644 index 4bedf3130f..0000000000 --- a/examples/aws-service-transform-container/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import express from "express"; - -const PORT = 80; - -const app = express(); - -app.get("/", (_req, res) => { - res.send(`Hello from http://localhost:${PORT}`) -}); - -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-service-transform-container/package.json b/examples/aws-service-transform-container/package.json deleted file mode 100644 index 7dad309412..0000000000 --- a/examples/aws-service-transform-container/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "aws-service-transform-container", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "express": "^4.21.1", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-service-transform-container/sst.config.ts b/examples/aws-service-transform-container/sst.config.ts deleted file mode 100644 index 6b64bedb9c..0000000000 --- a/examples/aws-service-transform-container/sst.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-service-transform-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - new sst.aws.Service("MyService", { - cluster, - transform: { - taskDefinition: (args) => { - // "containerDefinitions" is a JSON string, parse first - let value = $jsonParse(args.containerDefinitions); - - // Update "portMappings" - value = value.apply((containerDefinitions) => { - containerDefinitions[0].portMappings = [ - { - containerPort: 80, - protocol: "tcp", - }, - ]; - return containerDefinitions; - }); - - // Convert back to JSON string - args.containerDefinitions = $jsonStringify(value); - }, - }, - }); - }, -}); diff --git a/examples/aws-service-transform-container/tsconfig.json b/examples/aws-service-transform-container/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-service-transform-container/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-shared-alb-static/api/.dockerignore b/examples/aws-shared-alb-static/api/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-shared-alb-static/api/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-shared-alb-static/api/Dockerfile b/examples/aws-shared-alb-static/api/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-shared-alb-static/api/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-shared-alb-static/api/index.mjs b/examples/aws-shared-alb-static/api/index.mjs deleted file mode 100644 index 68f1eb62b0..0000000000 --- a/examples/aws-shared-alb-static/api/index.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import express from "express"; - -const PORT = 3000; - -const app = express(); - -app.get("/", (req, res) => { - res.json({ status: "ok" }); -}); - -app.get("/api", (req, res) => { - res.json({ service: "api", message: "Hello from the API service" }); -}); - -app.get("/api/health", (req, res) => { - res.json({ status: "ok" }); -}); - -app.get("/api/greeting", (req, res) => { - res.json({ service: "api", message: "Hello from the API service" }); -}); - -app.get("/api/*", (req, res) => { - res.json({ service: "api", path: req.path }); -}); - -app.listen(PORT, () => { - console.log(`API service is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-shared-alb-static/api/package.json b/examples/aws-shared-alb-static/api/package.json deleted file mode 100644 index bf11689dd1..0000000000 --- a/examples/aws-shared-alb-static/api/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "api", - "version": "1.0.0", - "dependencies": { - "express": "^4.21.1" - } -} diff --git a/examples/aws-shared-alb-static/package.json b/examples/aws-shared-alb-static/package.json deleted file mode 100644 index 138aaa3168..0000000000 --- a/examples/aws-shared-alb-static/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-shared-alb-static", - "version": "1.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-shared-alb-static/sst.config.ts b/examples/aws-shared-alb-static/sst.config.ts deleted file mode 100644 index 87fd8c4550..0000000000 --- a/examples/aws-shared-alb-static/sst.config.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// - -/** - * ## AWS Shared ALB - * - * Creates a standalone ALB that is shared across stages. In dev, the ALB is - * referenced via `Alb.get()`. In production, it's created fresh. - * - * Uses the `$dev ? get : new` pattern to share infrastructure across stages. - */ -export default $config({ - app(input) { - return { - name: "aws-shared-alb", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - aws: { - region: "us-east-1", - }, - }, - }; - }, - async run() { - const vpc = $dev - ? sst.aws.Vpc.get("MyVpc", "vpc-xxx") - : new sst.aws.Vpc("MyVpc"); - - const cluster = $dev - ? sst.aws.Cluster.get("MyCluster", { id: "cluster-xxx", vpc }) - : new sst.aws.Cluster("MyCluster", { vpc }); - - const alb = $dev - ? sst.aws.Alb.get("SharedAlb", "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/xxx") - : new sst.aws.Alb("SharedAlb", { - vpc, - listeners: [ - { port: 80, protocol: "http" }, - ], - }); - - if ($dev) { - new sst.aws.Service("Web", { - cluster, - image: { context: "web/" }, - loadBalancer: { - instance: alb, - rules: [ - { - listen: "80/http", - forward: "3000/http", - conditions: { path: "/app/*" }, - priority: 200, - }, - ], - }, - }); - } - - new sst.aws.Service("Api", { - cluster, - image: { context: "api/" }, - loadBalancer: { - instance: alb, - rules: [ - { - listen: "80/http", - forward: "3000/http", - conditions: { path: "/api/*" }, - priority: 100, - }, - ], - }, - }); - - return { - url: alb.url, - }; - }, -}); diff --git a/examples/aws-shared-alb-static/web/.dockerignore b/examples/aws-shared-alb-static/web/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-shared-alb-static/web/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-shared-alb-static/web/Dockerfile b/examples/aws-shared-alb-static/web/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-shared-alb-static/web/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-shared-alb-static/web/index.mjs b/examples/aws-shared-alb-static/web/index.mjs deleted file mode 100644 index 0d64a1452d..0000000000 --- a/examples/aws-shared-alb-static/web/index.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import express from "express"; - -const PORT = 3000; - -const app = express(); - -app.get("/", (req, res) => { - res.json({ status: "ok" }); -}); - -app.get("/app", (req, res) => { - res.send("

Web App

Hello from the Web service

"); -}); - -app.get("/app/health", (req, res) => { - res.json({ status: "ok" }); -}); - -app.get("/app/greeting", (req, res) => { - res.send("

Web App

Hello from the Web service

"); -}); - -app.get("/app/*", (req, res) => { - res.send(`

Web App

Path: ${req.path}

`); -}); - -app.listen(PORT, () => { - console.log(`Web service is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-shared-alb-static/web/package.json b/examples/aws-shared-alb-static/web/package.json deleted file mode 100644 index 9c43fe9bb1..0000000000 --- a/examples/aws-shared-alb-static/web/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "web", - "version": "1.0.0", - "dependencies": { - "express": "^4.21.1" - } -} diff --git a/examples/aws-shared-alb/api/.dockerignore b/examples/aws-shared-alb/api/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-shared-alb/api/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-shared-alb/api/Dockerfile b/examples/aws-shared-alb/api/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-shared-alb/api/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-shared-alb/api/index.mjs b/examples/aws-shared-alb/api/index.mjs deleted file mode 100644 index d229500c93..0000000000 --- a/examples/aws-shared-alb/api/index.mjs +++ /dev/null @@ -1,21 +0,0 @@ -import express from "express"; - -const PORT = 3000; - -const app = express(); - -app.get("/api", (req, res) => { - res.json({ service: "api", message: "Hello from the API service" }); -}); - -app.get("/api/health", (req, res) => { - res.json({ status: "ok" }); -}); - -app.get("/api/*", (req, res) => { - res.json({ service: "api", path: req.path }); -}); - -app.listen(PORT, () => { - console.log(`API service is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-shared-alb/api/package.json b/examples/aws-shared-alb/api/package.json deleted file mode 100644 index bf11689dd1..0000000000 --- a/examples/aws-shared-alb/api/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "api", - "version": "1.0.0", - "dependencies": { - "express": "^4.21.1" - } -} diff --git a/examples/aws-shared-alb/package.json b/examples/aws-shared-alb/package.json deleted file mode 100644 index 0f75962a1a..0000000000 --- a/examples/aws-shared-alb/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "aws-shared-alb", - "version": "1.0.0", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-shared-alb/sst.config.ts b/examples/aws-shared-alb/sst.config.ts deleted file mode 100644 index 34f2c072f1..0000000000 --- a/examples/aws-shared-alb/sst.config.ts +++ /dev/null @@ -1,124 +0,0 @@ -/// - -/** - * ## AWS Shared ALB - * - * Creates a standalone ALB shared across multiple services. - * Shows advanced routing with path conditions, header conditions, and health checks. - * - * ```ts title="sst.config.ts" - * const alb = new sst.aws.Alb("SharedAlb", { - * vpc, - * listeners: [ - * { port: 80, protocol: "http" }, - * ], - * }); - * ``` - * - * Services can use header-based routing in addition to path-based: - * - * ```ts title="sst.config.ts" - * new sst.aws.Service("InternalApi", { - * cluster, - * image: { context: "api/" }, - * loadBalancer: { - * instance: alb, - * rules: [ - * { - * listen: "80/http", - * forward: "3000/http", - * conditions: { - * path: "/api/*", - * header: { name: "x-internal", values: ["true"] }, - * }, - * priority: 50, - * }, - * ], - * }, - * }); - * ``` - * - * This example creates: - * - A shared ALB with an HTTP listener - * - An API service with path-based routing and custom health check - * - A Web service with path-based routing - * - Both services share the same ALB - */ -export default $config({ - app(input) { - return { - name: "aws-shared-alb", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - aws: { - region: "us-east-1", - }, - }, - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - // Create a shared ALB with an HTTP listener - const alb = new sst.aws.Alb("SharedAlb", { - vpc, - listeners: [{ port: 80, protocol: "http" }], - }); - - // API service — handles /api/* with a custom health check path - new sst.aws.Service("Api", { - cluster, - image: { context: "api/" }, - loadBalancer: { - instance: alb, - rules: [ - { - listen: "80/http", - forward: "3000/http", - conditions: { path: "/api/*" }, - priority: 100, - }, - ], - health: { - "3000/http": { - path: "/api/health", - interval: "10 seconds", - timeout: "5 seconds", - healthyThreshold: 2, - unhealthyThreshold: 3, - }, - }, - }, - }); - - // Web service — handles everything else under /app/* - new sst.aws.Service("Web", { - cluster, - image: { context: "web/" }, - loadBalancer: { - instance: alb, - rules: [ - { - listen: "80/http", - forward: "3000/http", - conditions: { path: "/app/*" }, - priority: 200, - }, - ], - health: { - "3000/http": { - path: "/app/health", - interval: "10 seconds", - timeout: "5 seconds", - }, - }, - }, - }); - - return { - url: alb.url, - }; - }, -}); diff --git a/examples/aws-shared-alb/test.sh b/examples/aws-shared-alb/test.sh deleted file mode 100755 index 2f7495c709..0000000000 --- a/examples/aws-shared-alb/test.sh +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Test the shared ALB example endpoints after deployment. -# -# Usage: -# ./test.sh [alb-url] -# -# If no URL is provided, attempts to read it from sst output. - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -cd "$SCRIPT_DIR" - -# Get ALB URL from argument or sst output -if [ -n "${1:-}" ]; then - ALB_URL="$1" -else - echo "Fetching ALB URL from sst output..." - ALB_URL=$(npx sst output url 2>/dev/null || true) - if [ -z "$ALB_URL" ]; then - echo "ERROR: Could not determine ALB URL." - echo "Usage: ./test.sh " - echo " e.g. ./test.sh http://SharedAlb-123456.us-east-1.elb.amazonaws.com" - exit 1 - fi -fi - -# Strip trailing slash -ALB_URL="${ALB_URL%/}" - -echo "=== Testing Shared ALB Example ===" -echo "ALB URL: $ALB_URL" -echo "" - -PASS=0 -FAIL=0 - -run_test() { - local name="$1" - local url="$2" - local expected="$3" - - echo -n "TEST: $name ... " - HTTP_CODE=$(curl -s -o /tmp/alb_test_response -w "%{http_code}" --max-time 10 "$url" 2>/dev/null || echo "000") - BODY=$(cat /tmp/alb_test_response 2>/dev/null || echo "") - - if [ "$HTTP_CODE" = "000" ]; then - echo "FAIL (connection error)" - FAIL=$((FAIL + 1)) - return - fi - - if echo "$BODY" | grep -q "$expected"; then - echo "OK (HTTP $HTTP_CODE) → $BODY" - PASS=$((PASS + 1)) - else - echo "FAIL (HTTP $HTTP_CODE, expected '$expected')" - echo " Got: $BODY" - FAIL=$((FAIL + 1)) - fi -} - -# Note: ALB path pattern "/api/*" matches "/api/" but NOT "/api" itself. -# Tests use paths with a trailing segment to match the wildcard. - -# Test 1: API service — /api/health returns { "status": "ok" } -run_test "API health (/api/health)" "$ALB_URL/api/health" '"status":"ok"' - -# Test 2: API service — /api/users returns { "service": "api", "path": "/api/users" } -run_test "API routing (/api/users)" "$ALB_URL/api/users" '"service":"api"' - -# Test 3: API service — /api/greeting returns path info -run_test "API greeting (/api/greeting)" "$ALB_URL/api/greeting" "/api/greeting" - -# Test 4: Web service — /app/health returns { "status": "ok" } -run_test "Web health (/app/health)" "$ALB_URL/app/health" '"status":"ok"' - -# Test 5: Web service — /app/dashboard returns HTML with path -run_test "Web routing (/app/dashboard)" "$ALB_URL/app/dashboard" "/app/dashboard" - -# Test 6: Web service — /app/greeting returns path info -run_test "Web greeting (/app/greeting)" "$ALB_URL/app/greeting" "/app/greeting" - -# Test 7: Default action — / should return 404 (ALB default) -echo -n "TEST: Default action (/) ... " -HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$ALB_URL/" 2>/dev/null || echo "000") -if [ "$HTTP_CODE" = "403" ]; then - echo "PASS (HTTP 403 as expected)" - PASS=$((PASS + 1)) -else - echo "FAIL (expected 403, got HTTP $HTTP_CODE)" - FAIL=$((FAIL + 1)) -fi - -echo "" -echo "=== Results: $PASS passed, $FAIL failed ===" - -if [ "$FAIL" -gt 0 ]; then - exit 1 -fi diff --git a/examples/aws-shared-alb/web/.dockerignore b/examples/aws-shared-alb/web/.dockerignore deleted file mode 100644 index d98fe17111..0000000000 --- a/examples/aws-shared-alb/web/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-shared-alb/web/Dockerfile b/examples/aws-shared-alb/web/Dockerfile deleted file mode 100644 index 53718c02f4..0000000000 --- a/examples/aws-shared-alb/web/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM node:18-bullseye-slim - -WORKDIR /app/ - -COPY package.json /app -RUN npm install - -COPY index.mjs /app - -ENTRYPOINT ["node", "index.mjs"] diff --git a/examples/aws-shared-alb/web/index.mjs b/examples/aws-shared-alb/web/index.mjs deleted file mode 100644 index 6640bec96f..0000000000 --- a/examples/aws-shared-alb/web/index.mjs +++ /dev/null @@ -1,21 +0,0 @@ -import express from "express"; - -const PORT = 3000; - -const app = express(); - -app.get("/app", (req, res) => { - res.send("

Web App

Hello from the Web service

"); -}); - -app.get("/app/health", (req, res) => { - res.json({ status: "ok" }); -}); - -app.get("/app/*", (req, res) => { - res.send(`

Web App

Path: ${req.path}

`); -}); - -app.listen(PORT, () => { - console.log(`Web service is running on http://localhost:${PORT}`); -}); diff --git a/examples/aws-shared-alb/web/package.json b/examples/aws-shared-alb/web/package.json deleted file mode 100644 index 9c43fe9bb1..0000000000 --- a/examples/aws-shared-alb/web/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "web", - "version": "1.0.0", - "dependencies": { - "express": "^4.21.1" - } -} diff --git a/examples/aws-sharp/.gitignore b/examples/aws-sharp/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-sharp/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-sharp/index.ts b/examples/aws-sharp/index.ts deleted file mode 100644 index 7bb58fff18..0000000000 --- a/examples/aws-sharp/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import sharp from "sharp"; -import { promises as fs } from "fs"; - -export async function handler() { - const imagePath = "logo.png"; - - try { - // Read the image file - const imageBuffer = await fs.readFile(imagePath); - - // Resize the image - const resizedImage = await sharp(imageBuffer) - .resize(100, 100) // Resize to 100x100 - .toBuffer(); - - // Convert the buffer to base64 - const body = resizedImage.toString("base64"); - - console.log("Successfully resized logo.png"); - - return { - body, - statusCode: 200, - headers: { - "Content-Type": "image/png", - "Content-Disposition": "inline" - }, - isBase64Encoded: true - }; - } catch (error) { - console.log(error); - return { - statusCode: 500, - body: JSON.stringify("Error resizing image: " + error.message), - }; - } -} diff --git a/examples/aws-sharp/logo.png b/examples/aws-sharp/logo.png deleted file mode 100644 index 4a98ec9023..0000000000 Binary files a/examples/aws-sharp/logo.png and /dev/null differ diff --git a/examples/aws-sharp/package.json b/examples/aws-sharp/package.json deleted file mode 100644 index 941e53db73..0000000000 --- a/examples/aws-sharp/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "aws-sharp", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sharp": "^0.33.5", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "8.10.145" - } -} diff --git a/examples/aws-sharp/sst.config.ts b/examples/aws-sharp/sst.config.ts deleted file mode 100644 index 533c44b782..0000000000 --- a/examples/aws-sharp/sst.config.ts +++ /dev/null @@ -1,55 +0,0 @@ -/// - -/** - * ## Sharp in Lambda - * - * Uses the [Sharp](https://sharp.pixelplumbing.com/) library to resize images. In this example, - * it resizes a `logo.png` local file to 100x100 pixels. - * - * ```json title="sst.config.ts" - * { - * nodejs: { install: ["sharp"] } - * } - * ``` - * - * We don't need a layer to deploy this because `sharp` comes with a pre-built binary for Lambda. - * This is handled by [`nodejs.install`](/docs/component/aws/function#nodejs-install). - * - * :::tip - * You don't need to use a Lambda layer to use Sharp. - * ::: - * - * In dev, this uses the sharp npm package locally. - * - * ```json title="package.json" - * { - * "dependencies": { - * "sharp": "^0.33.5" - * } - * } - * ``` - * - * On deploy, SST will use the right binary from the sharp package for the target Lambda - * architecture. - */ -export default $config({ - app(input) { - return { - name: "aws-sharp", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const func = new sst.aws.Function("MyFunction", { - url: true, - handler: "index.handler", - nodejs: { install: ["sharp"] }, - copyFiles: [{ from: "logo.png" }], - }); - - return { - url: func.url, - }; - }, -}); diff --git a/examples/aws-sharp/tsconfig.json b/examples/aws-sharp/tsconfig.json deleted file mode 100644 index 2f98042715..0000000000 --- a/examples/aws-sharp/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "esModuleInterop": true - } -} diff --git a/examples/aws-solid-container-ws/.dockerignore b/examples/aws-solid-container-ws/.dockerignore deleted file mode 100644 index 89e3d841fd..0000000000 --- a/examples/aws-solid-container-ws/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -# sst -.sst diff --git a/examples/aws-solid-container-ws/.gitignore b/examples/aws-solid-container-ws/.gitignore deleted file mode 100644 index 8ebae30246..0000000000 --- a/examples/aws-solid-container-ws/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ - -dist -.solid -.output -.vercel -.netlify -.vinxi -app.config.timestamp_*.js - -# Environment -.env -.env*.local - -# dependencies -/node_modules - -# IDEs and editors -/.idea -.project -.classpath -*.launch -.settings/ - -# Temp -gitignore - -# System Files -.DS_Store -Thumbs.db - -# sst -.sst diff --git a/examples/aws-solid-container-ws/Dockerfile b/examples/aws-solid-container-ws/Dockerfile deleted file mode 100644 index eb842b02d5..0000000000 --- a/examples/aws-solid-container-ws/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM node:lts AS base - -WORKDIR /src - -# Build -FROM base as build - -COPY --link package.json package-lock.json ./ -RUN npm install - -COPY --link . . - -RUN npm run build - -# Run -FROM base - -ENV PORT=3000 -ENV NODE_ENV=production - -COPY --from=build /src/.output /src/.output - -CMD [ "node", ".output/server/index.mjs" ] diff --git a/examples/aws-solid-container-ws/app.config.ts b/examples/aws-solid-container-ws/app.config.ts deleted file mode 100644 index 792fe7a649..0000000000 --- a/examples/aws-solid-container-ws/app.config.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { defineConfig } from "@solidjs/start/config"; - -export default defineConfig({ - server: { - experimental: { - websocket: true, - }, - }, -}).addRouter({ - name: "ws", - type: "http", - handler: "./src/ws.ts", - target: "server", - base: "/ws", -}); diff --git a/examples/aws-solid-container-ws/package.json b/examples/aws-solid-container-ws/package.json deleted file mode 100644 index 27a783d39f..0000000000 --- a/examples/aws-solid-container-ws/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "aws-solid-container-ws", - "type": "module", - "scripts": { - "build": "vinxi build", - "dev": "vinxi dev", - "start": "vinxi start", - "version": "vinxi version" - }, - "dependencies": { - "@solidjs/meta": "^0.29.4", - "@solidjs/router": "^0.14.7", - "@solidjs/start": "^1.0.8", - "solid-js": "^1.9.1", - "sst": "file:../../sdk/js", - "vinxi": "^0.4.3" - }, - "engines": { - "node": ">=18" - } -} diff --git a/examples/aws-solid-container-ws/public/favicon.ico b/examples/aws-solid-container-ws/public/favicon.ico deleted file mode 100644 index fb282da071..0000000000 Binary files a/examples/aws-solid-container-ws/public/favicon.ico and /dev/null differ diff --git a/examples/aws-solid-container-ws/src/app.css b/examples/aws-solid-container-ws/src/app.css deleted file mode 100644 index 8596998a49..0000000000 --- a/examples/aws-solid-container-ws/src/app.css +++ /dev/null @@ -1,39 +0,0 @@ -body { - font-family: Gordita, Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; -} - -a { - margin-right: 1rem; -} - -main { - text-align: center; - padding: 1em; - margin: 0 auto; -} - -h1 { - color: #335d92; - text-transform: uppercase; - font-size: 4rem; - font-weight: 100; - line-height: 1.1; - margin: 4rem auto; - max-width: 14rem; -} - -p { - max-width: 14rem; - margin: 2rem auto; - line-height: 1.35; -} - -@media (min-width: 480px) { - h1 { - max-width: none; - } - - p { - max-width: none; - } -} diff --git a/examples/aws-solid-container-ws/src/app.tsx b/examples/aws-solid-container-ws/src/app.tsx deleted file mode 100644 index d1359c8d82..0000000000 --- a/examples/aws-solid-container-ws/src/app.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { MetaProvider, Title } from "@solidjs/meta"; -import { Router } from "@solidjs/router"; -import { FileRoutes } from "@solidjs/start/router"; -import { Suspense } from "solid-js"; -import "./app.css"; - -export default function App() { - return ( - ( - - SolidStart - Basic -
Index - About - {props.children} - - )} - > - - - ); -} diff --git a/examples/aws-solid-container-ws/src/components/Counter.css b/examples/aws-solid-container-ws/src/components/Counter.css deleted file mode 100644 index 220e179460..0000000000 --- a/examples/aws-solid-container-ws/src/components/Counter.css +++ /dev/null @@ -1,21 +0,0 @@ -.increment { - font-family: inherit; - font-size: inherit; - padding: 1em 2em; - color: #335d92; - background-color: rgba(68, 107, 158, 0.1); - border-radius: 2em; - border: 2px solid rgba(68, 107, 158, 0); - outline: none; - width: 200px; - font-variant-numeric: tabular-nums; - cursor: pointer; -} - -.increment:focus { - border: 2px solid #335d92; -} - -.increment:active { - background-color: rgba(68, 107, 158, 0.2); -} \ No newline at end of file diff --git a/examples/aws-solid-container-ws/src/components/Counter.tsx b/examples/aws-solid-container-ws/src/components/Counter.tsx deleted file mode 100644 index 091fc5d0bc..0000000000 --- a/examples/aws-solid-container-ws/src/components/Counter.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createSignal } from "solid-js"; -import "./Counter.css"; - -export default function Counter() { - const [count, setCount] = createSignal(0); - return ( - - ); -} diff --git a/examples/aws-solid-container-ws/src/entry-client.tsx b/examples/aws-solid-container-ws/src/entry-client.tsx deleted file mode 100644 index 0ca4e3c300..0000000000 --- a/examples/aws-solid-container-ws/src/entry-client.tsx +++ /dev/null @@ -1,4 +0,0 @@ -// @refresh reload -import { mount, StartClient } from "@solidjs/start/client"; - -mount(() => , document.getElementById("app")!); diff --git a/examples/aws-solid-container-ws/src/entry-server.tsx b/examples/aws-solid-container-ws/src/entry-server.tsx deleted file mode 100644 index 401eff83fd..0000000000 --- a/examples/aws-solid-container-ws/src/entry-server.tsx +++ /dev/null @@ -1,21 +0,0 @@ -// @refresh reload -import { createHandler, StartServer } from "@solidjs/start/server"; - -export default createHandler(() => ( - ( - - - - - - {assets} - - -
{children}
- {scripts} - - - )} - /> -)); diff --git a/examples/aws-solid-container-ws/src/global.d.ts b/examples/aws-solid-container-ws/src/global.d.ts deleted file mode 100644 index dc6f10c226..0000000000 --- a/examples/aws-solid-container-ws/src/global.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/aws-solid-container-ws/src/routes/[...404].tsx b/examples/aws-solid-container-ws/src/routes/[...404].tsx deleted file mode 100644 index 4ea71ec7fe..0000000000 --- a/examples/aws-solid-container-ws/src/routes/[...404].tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Title } from "@solidjs/meta"; -import { HttpStatusCode } from "@solidjs/start"; - -export default function NotFound() { - return ( -
- Not Found - -

Page Not Found

-

- Visit{" "} - - start.solidjs.com - {" "} - to learn how to build SolidStart apps. -

-
- ); -} diff --git a/examples/aws-solid-container-ws/src/routes/about.tsx b/examples/aws-solid-container-ws/src/routes/about.tsx deleted file mode 100644 index 8371d911cd..0000000000 --- a/examples/aws-solid-container-ws/src/routes/about.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Title } from "@solidjs/meta"; - -export default function Home() { - return ( -
- About -

About

-
- ); -} diff --git a/examples/aws-solid-container-ws/src/routes/index.tsx b/examples/aws-solid-container-ws/src/routes/index.tsx deleted file mode 100644 index 5d557d819f..0000000000 --- a/examples/aws-solid-container-ws/src/routes/index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Title } from "@solidjs/meta"; -import Counter from "~/components/Counter"; - -export default function Home() { - return ( -
- Hello World -

Hello world!

- -

- Visit{" "} - - start.solidjs.com - {" "} - to learn how to build SolidStart apps. -

-
- ); -} diff --git a/examples/aws-solid-container-ws/src/ws.ts b/examples/aws-solid-container-ws/src/ws.ts deleted file mode 100644 index 7ee8d34f4c..0000000000 --- a/examples/aws-solid-container-ws/src/ws.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { eventHandler } from "vinxi/http"; -export default eventHandler({ - handler() { }, - websocket: { - async open(peer) { - console.log("open", peer.id, peer.url); - }, - async message(peer, msg) { - const message = msg.text(); - console.log("msg", peer.id, peer.url, message); - - setTimeout(() => { - peer.send("Message received from: #" + peer.id); - }, 3000); - }, - async close(peer, _details) { - console.log("close", peer.id, peer.url); - }, - async error(peer, error) { - console.log("error", peer.id, peer.url, error); - }, - }, -}); diff --git a/examples/aws-solid-container-ws/sst.config.ts b/examples/aws-solid-container-ws/sst.config.ts deleted file mode 100644 index 2b1905639e..0000000000 --- a/examples/aws-solid-container-ws/sst.config.ts +++ /dev/null @@ -1,51 +0,0 @@ -/// - -/** - * ## AWS SolidStart WebSocket endpoint - * - * Deploys a SolidStart app with a [WebSocket endpoint](https://docs.solidjs.com/solid-start/advanced/websocket) - * in a container to AWS. - * - * Uses the experimental WebSocket support in Nitro. - * - * ```ts title="app.config.ts" {4} - * export default defineConfig({ - * server: { - * experimental: { - * websocket: true, - * }, - * }, - * }).addRouter({ - * name: "ws", - * type: "http", - * handler: "./src/ws.ts", - * target: "server", - * base: "/ws", - * }); - * ``` - * - * Once deployed you can test the `/ws` endpoint and it'll send a message back after a 3s delay. - */ -export default $config({ - app(input) { - return { - name: "aws-solid-container-ws", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-solid-container-ws/tsconfig.json b/examples/aws-solid-container-ws/tsconfig.json deleted file mode 100644 index 7d5871a07a..0000000000 --- a/examples/aws-solid-container-ws/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "bundler", - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowJs": true, - "strict": true, - "noEmit": true, - "types": ["vinxi/types/client"], - "isolatedModules": true, - "paths": { - "~/*": ["./src/*"] - } - } -} diff --git a/examples/aws-solid-container/.dockerignore b/examples/aws-solid-container/.dockerignore deleted file mode 100644 index ea0aaeeec9..0000000000 --- a/examples/aws-solid-container/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-solid-container/.gitignore b/examples/aws-solid-container/.gitignore deleted file mode 100644 index 8ebae30246..0000000000 --- a/examples/aws-solid-container/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ - -dist -.solid -.output -.vercel -.netlify -.vinxi -app.config.timestamp_*.js - -# Environment -.env -.env*.local - -# dependencies -/node_modules - -# IDEs and editors -/.idea -.project -.classpath -*.launch -.settings/ - -# Temp -gitignore - -# System Files -.DS_Store -Thumbs.db - -# sst -.sst diff --git a/examples/aws-solid-container/Dockerfile b/examples/aws-solid-container/Dockerfile deleted file mode 100644 index eb842b02d5..0000000000 --- a/examples/aws-solid-container/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM node:lts AS base - -WORKDIR /src - -# Build -FROM base as build - -COPY --link package.json package-lock.json ./ -RUN npm install - -COPY --link . . - -RUN npm run build - -# Run -FROM base - -ENV PORT=3000 -ENV NODE_ENV=production - -COPY --from=build /src/.output /src/.output - -CMD [ "node", ".output/server/index.mjs" ] diff --git a/examples/aws-solid-container/app.config.ts b/examples/aws-solid-container/app.config.ts deleted file mode 100644 index de7f83103a..0000000000 --- a/examples/aws-solid-container/app.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { defineConfig } from "@solidjs/start/config"; - -export default defineConfig({}); diff --git a/examples/aws-solid-container/package.json b/examples/aws-solid-container/package.json deleted file mode 100644 index 3f3f4c9222..0000000000 --- a/examples/aws-solid-container/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "aws-solid-container", - "type": "module", - "scripts": { - "build": "vinxi build", - "dev": "vinxi dev", - "start": "vinxi start", - "version": "vinxi version" - }, - "dependencies": { - "@solidjs/meta": "^0.29.4", - "@solidjs/router": "^0.14.8", - "@solidjs/start": "^1.0.8", - "ioredis": "^5.4.1", - "solid-js": "^1.9.1", - "sst": "file:../../sdk/js", - "vinxi": "^0.4.3" - }, - "engines": { - "node": ">=18" - }, - "overrides": { - "nitropack": "npm:nitropack-nightly@latest" - } -} diff --git a/examples/aws-solid-container/public/favicon.ico b/examples/aws-solid-container/public/favicon.ico deleted file mode 100644 index fb282da071..0000000000 Binary files a/examples/aws-solid-container/public/favicon.ico and /dev/null differ diff --git a/examples/aws-solid-container/src/app.css b/examples/aws-solid-container/src/app.css deleted file mode 100644 index 8596998a49..0000000000 --- a/examples/aws-solid-container/src/app.css +++ /dev/null @@ -1,39 +0,0 @@ -body { - font-family: Gordita, Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; -} - -a { - margin-right: 1rem; -} - -main { - text-align: center; - padding: 1em; - margin: 0 auto; -} - -h1 { - color: #335d92; - text-transform: uppercase; - font-size: 4rem; - font-weight: 100; - line-height: 1.1; - margin: 4rem auto; - max-width: 14rem; -} - -p { - max-width: 14rem; - margin: 2rem auto; - line-height: 1.35; -} - -@media (min-width: 480px) { - h1 { - max-width: none; - } - - p { - max-width: none; - } -} diff --git a/examples/aws-solid-container/src/app.tsx b/examples/aws-solid-container/src/app.tsx deleted file mode 100644 index d1359c8d82..0000000000 --- a/examples/aws-solid-container/src/app.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { MetaProvider, Title } from "@solidjs/meta"; -import { Router } from "@solidjs/router"; -import { FileRoutes } from "@solidjs/start/router"; -import { Suspense } from "solid-js"; -import "./app.css"; - -export default function App() { - return ( - ( - - SolidStart - Basic - Index - About - {props.children} - - )} - > - - - ); -} diff --git a/examples/aws-solid-container/src/components/Counter.css b/examples/aws-solid-container/src/components/Counter.css deleted file mode 100644 index 220e179460..0000000000 --- a/examples/aws-solid-container/src/components/Counter.css +++ /dev/null @@ -1,21 +0,0 @@ -.increment { - font-family: inherit; - font-size: inherit; - padding: 1em 2em; - color: #335d92; - background-color: rgba(68, 107, 158, 0.1); - border-radius: 2em; - border: 2px solid rgba(68, 107, 158, 0); - outline: none; - width: 200px; - font-variant-numeric: tabular-nums; - cursor: pointer; -} - -.increment:focus { - border: 2px solid #335d92; -} - -.increment:active { - background-color: rgba(68, 107, 158, 0.2); -} \ No newline at end of file diff --git a/examples/aws-solid-container/src/components/Counter.tsx b/examples/aws-solid-container/src/components/Counter.tsx deleted file mode 100644 index 091fc5d0bc..0000000000 --- a/examples/aws-solid-container/src/components/Counter.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createSignal } from "solid-js"; -import "./Counter.css"; - -export default function Counter() { - const [count, setCount] = createSignal(0); - return ( - - ); -} diff --git a/examples/aws-solid-container/src/entry-client.tsx b/examples/aws-solid-container/src/entry-client.tsx deleted file mode 100644 index 0ca4e3c300..0000000000 --- a/examples/aws-solid-container/src/entry-client.tsx +++ /dev/null @@ -1,4 +0,0 @@ -// @refresh reload -import { mount, StartClient } from "@solidjs/start/client"; - -mount(() => , document.getElementById("app")!); diff --git a/examples/aws-solid-container/src/entry-server.tsx b/examples/aws-solid-container/src/entry-server.tsx deleted file mode 100644 index 401eff83fd..0000000000 --- a/examples/aws-solid-container/src/entry-server.tsx +++ /dev/null @@ -1,21 +0,0 @@ -// @refresh reload -import { createHandler, StartServer } from "@solidjs/start/server"; - -export default createHandler(() => ( - ( - - - - - - {assets} - - -
{children}
- {scripts} - - - )} - /> -)); diff --git a/examples/aws-solid-container/src/global.d.ts b/examples/aws-solid-container/src/global.d.ts deleted file mode 100644 index dc6f10c226..0000000000 --- a/examples/aws-solid-container/src/global.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/aws-solid-container/src/routes/[...404].tsx b/examples/aws-solid-container/src/routes/[...404].tsx deleted file mode 100644 index 4ea71ec7fe..0000000000 --- a/examples/aws-solid-container/src/routes/[...404].tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Title } from "@solidjs/meta"; -import { HttpStatusCode } from "@solidjs/start"; - -export default function NotFound() { - return ( -
- Not Found - -

Page Not Found

-

- Visit{" "} - - start.solidjs.com - {" "} - to learn how to build SolidStart apps. -

-
- ); -} diff --git a/examples/aws-solid-container/src/routes/about.tsx b/examples/aws-solid-container/src/routes/about.tsx deleted file mode 100644 index 8371d911cd..0000000000 --- a/examples/aws-solid-container/src/routes/about.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Title } from "@solidjs/meta"; - -export default function Home() { - return ( -
- About -

About

-
- ); -} diff --git a/examples/aws-solid-container/src/routes/index.tsx b/examples/aws-solid-container/src/routes/index.tsx deleted file mode 100644 index ff472de40e..0000000000 --- a/examples/aws-solid-container/src/routes/index.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; -import { createAsync, cache } from "@solidjs/router"; - -const getCounter = cache(async () => { - "use server"; - const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } - ); - - return await redis.incr("counter"); -}, "counter"); - -export const route = { - load: () => getCounter(), -}; - -export default function Page() { - const counter = createAsync(() => getCounter()); - - return

Hit counter: {counter()}

; -} diff --git a/examples/aws-solid-container/sst.config.ts b/examples/aws-solid-container/sst.config.ts deleted file mode 100644 index 34e9e92282..0000000000 --- a/examples/aws-solid-container/sst.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-solid-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-solid-container/tsconfig.json b/examples/aws-solid-container/tsconfig.json deleted file mode 100644 index 7d5871a07a..0000000000 --- a/examples/aws-solid-container/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "bundler", - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowJs": true, - "strict": true, - "noEmit": true, - "types": ["vinxi/types/client"], - "isolatedModules": true, - "paths": { - "~/*": ["./src/*"] - } - } -} diff --git a/examples/aws-solid/.gitignore b/examples/aws-solid/.gitignore deleted file mode 100644 index 8ebae30246..0000000000 --- a/examples/aws-solid/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ - -dist -.solid -.output -.vercel -.netlify -.vinxi -app.config.timestamp_*.js - -# Environment -.env -.env*.local - -# dependencies -/node_modules - -# IDEs and editors -/.idea -.project -.classpath -*.launch -.settings/ - -# Temp -gitignore - -# System Files -.DS_Store -Thumbs.db - -# sst -.sst diff --git a/examples/aws-solid/app.config.ts b/examples/aws-solid/app.config.ts deleted file mode 100644 index 499d53e43b..0000000000 --- a/examples/aws-solid/app.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from "@solidjs/start/config"; - -export default defineConfig({ - server: { - preset: "aws-lambda", - awsLambda: { - streaming: true, - }, - }, -}); diff --git a/examples/aws-solid/package.json b/examples/aws-solid/package.json deleted file mode 100644 index a9fa8b8ca3..0000000000 --- a/examples/aws-solid/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "aws-solid", - "type": "module", - "scripts": { - "build": "vinxi build", - "dev": "vinxi dev", - "start": "vinxi start", - "version": "vinxi version" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.670.0", - "@aws-sdk/s3-request-presigner": "^3.670.0", - "@solidjs/meta": "^0.29.4", - "@solidjs/router": "^0.14.8", - "@solidjs/start": "^1.0.8", - "solid-js": "^1.9.1", - "sst": "file:../../sdk/js", - "vinxi": "^0.4.3" - }, - "engines": { - "node": ">=18" - }, - "overrides": { - "nitropack": "npm:nitropack-nightly@latest" - } -} diff --git a/examples/aws-solid/public/favicon.ico b/examples/aws-solid/public/favicon.ico deleted file mode 100644 index fb282da071..0000000000 Binary files a/examples/aws-solid/public/favicon.ico and /dev/null differ diff --git a/examples/aws-solid/src/app.css b/examples/aws-solid/src/app.css deleted file mode 100644 index 8596998a49..0000000000 --- a/examples/aws-solid/src/app.css +++ /dev/null @@ -1,39 +0,0 @@ -body { - font-family: Gordita, Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; -} - -a { - margin-right: 1rem; -} - -main { - text-align: center; - padding: 1em; - margin: 0 auto; -} - -h1 { - color: #335d92; - text-transform: uppercase; - font-size: 4rem; - font-weight: 100; - line-height: 1.1; - margin: 4rem auto; - max-width: 14rem; -} - -p { - max-width: 14rem; - margin: 2rem auto; - line-height: 1.35; -} - -@media (min-width: 480px) { - h1 { - max-width: none; - } - - p { - max-width: none; - } -} diff --git a/examples/aws-solid/src/app.tsx b/examples/aws-solid/src/app.tsx deleted file mode 100644 index d1359c8d82..0000000000 --- a/examples/aws-solid/src/app.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { MetaProvider, Title } from "@solidjs/meta"; -import { Router } from "@solidjs/router"; -import { FileRoutes } from "@solidjs/start/router"; -import { Suspense } from "solid-js"; -import "./app.css"; - -export default function App() { - return ( - ( - - SolidStart - Basic - Index - About - {props.children} - - )} - > - - - ); -} diff --git a/examples/aws-solid/src/components/Counter.css b/examples/aws-solid/src/components/Counter.css deleted file mode 100644 index 220e179460..0000000000 --- a/examples/aws-solid/src/components/Counter.css +++ /dev/null @@ -1,21 +0,0 @@ -.increment { - font-family: inherit; - font-size: inherit; - padding: 1em 2em; - color: #335d92; - background-color: rgba(68, 107, 158, 0.1); - border-radius: 2em; - border: 2px solid rgba(68, 107, 158, 0); - outline: none; - width: 200px; - font-variant-numeric: tabular-nums; - cursor: pointer; -} - -.increment:focus { - border: 2px solid #335d92; -} - -.increment:active { - background-color: rgba(68, 107, 158, 0.2); -} \ No newline at end of file diff --git a/examples/aws-solid/src/components/Counter.tsx b/examples/aws-solid/src/components/Counter.tsx deleted file mode 100644 index 091fc5d0bc..0000000000 --- a/examples/aws-solid/src/components/Counter.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createSignal } from "solid-js"; -import "./Counter.css"; - -export default function Counter() { - const [count, setCount] = createSignal(0); - return ( - - ); -} diff --git a/examples/aws-solid/src/entry-client.tsx b/examples/aws-solid/src/entry-client.tsx deleted file mode 100644 index 0ca4e3c300..0000000000 --- a/examples/aws-solid/src/entry-client.tsx +++ /dev/null @@ -1,4 +0,0 @@ -// @refresh reload -import { mount, StartClient } from "@solidjs/start/client"; - -mount(() => , document.getElementById("app")!); diff --git a/examples/aws-solid/src/entry-server.tsx b/examples/aws-solid/src/entry-server.tsx deleted file mode 100644 index 401eff83fd..0000000000 --- a/examples/aws-solid/src/entry-server.tsx +++ /dev/null @@ -1,21 +0,0 @@ -// @refresh reload -import { createHandler, StartServer } from "@solidjs/start/server"; - -export default createHandler(() => ( - ( - - - - - - {assets} - - -
{children}
- {scripts} - - - )} - /> -)); diff --git a/examples/aws-solid/src/global.d.ts b/examples/aws-solid/src/global.d.ts deleted file mode 100644 index dc6f10c226..0000000000 --- a/examples/aws-solid/src/global.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/aws-solid/src/routes/[...404].tsx b/examples/aws-solid/src/routes/[...404].tsx deleted file mode 100644 index 4ea71ec7fe..0000000000 --- a/examples/aws-solid/src/routes/[...404].tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Title } from "@solidjs/meta"; -import { HttpStatusCode } from "@solidjs/start"; - -export default function NotFound() { - return ( -
- Not Found - -

Page Not Found

-

- Visit{" "} - - start.solidjs.com - {" "} - to learn how to build SolidStart apps. -

-
- ); -} diff --git a/examples/aws-solid/src/routes/about.tsx b/examples/aws-solid/src/routes/about.tsx deleted file mode 100644 index 8371d911cd..0000000000 --- a/examples/aws-solid/src/routes/about.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Title } from "@solidjs/meta"; - -export default function Home() { - return ( -
- About -

About

-
- ); -} diff --git a/examples/aws-solid/src/routes/index.tsx b/examples/aws-solid/src/routes/index.tsx deleted file mode 100644 index 9d59f86dee..0000000000 --- a/examples/aws-solid/src/routes/index.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { Resource } from "sst"; -import { createAsync } from "@solidjs/router"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -async function presignedUrl() { - "use server"; - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - return await getSignedUrl(new S3Client({}), command); -} - -export const route = { - load: () => presignedUrl(), -}; - -export default function Home() { - const url = createAsync(() => presignedUrl()); - - return ( -
-

Hello world!

-
{ - e.preventDefault(); - - const file = (e.target as HTMLFormElement).file.files?.[0]!; - - const image = await fetch(url() as string, { - body: file, - method: "PUT", - headers: { - "Content-Type": file.type, - "Content-Disposition": `attachment; filename="${file.name}"`, - }, - }); - - window.location.href = image.url.split("?")[0]; - }} - > - - -
-
- ); -} diff --git a/examples/aws-solid/sst.config.ts b/examples/aws-solid/sst.config.ts deleted file mode 100644 index b14575b398..0000000000 --- a/examples/aws-solid/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-solid", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public" - }); - new sst.aws.SolidStart("MyWeb", { - link: [bucket], - }); - }, -}); diff --git a/examples/aws-solid/tsconfig.json b/examples/aws-solid/tsconfig.json deleted file mode 100644 index 7d5871a07a..0000000000 --- a/examples/aws-solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "bundler", - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowJs": true, - "strict": true, - "noEmit": true, - "types": ["vinxi/types/client"], - "isolatedModules": true, - "paths": { - "~/*": ["./src/*"] - } - } -} diff --git a/examples/aws-static-site-basic-auth/package.json b/examples/aws-static-site-basic-auth/package.json deleted file mode 100644 index da474b02d6..0000000000 --- a/examples/aws-static-site-basic-auth/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-static-site-basic-auth", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-static-site-basic-auth/site/index.html b/examples/aws-static-site-basic-auth/site/index.html deleted file mode 100644 index 781e1c2cf4..0000000000 --- a/examples/aws-static-site-basic-auth/site/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - -

hello world!

- - diff --git a/examples/aws-static-site-basic-auth/sst.config.ts b/examples/aws-static-site-basic-auth/sst.config.ts deleted file mode 100644 index 212e65f84c..0000000000 --- a/examples/aws-static-site-basic-auth/sst.config.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// - -/** - * ## AWS static site basic auth - * - * This deploys a simple static site and adds basic auth to it. - * - * This is useful for dev environments where you want to share a static site with your team but - * ensure that it's not publicly accessible. - * - * This works by injecting some code into a CloudFront function that checks the basic auth - * header and matches it against the `USERNAME` and `PASSWORD` secrets. - * - * ```ts title="sst.config.ts" - * { - * injection: $interpolate` - * if ( - * !event.request.headers.authorization - * || event.request.headers.authorization.value !== "Basic ${basicAuth}" - * ) { - * return { - * statusCode: 401, - * headers: { - * "www-authenticate": { value: "Basic" } - * } - * }; - * }`, - * } - * ``` - * - * To deploy this, you need to first set the `USERNAME` and `PASSWORD` secrets. - * - * ```bash - * sst secret set USERNAME my-username - * sst secret set PASSWORD my-password - * ``` - * - * If you are deploying this to preview environments, you might want to set the secrets using - * the [`--fallback`](/docs/reference/cli#secret) flag. - */ -export default $config({ - app(input) { - return { - name: "aws-static-site-basic-auth", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - const username = new sst.Secret("USERNAME"); - const password = new sst.Secret("PASSWORD"); - const basicAuth = $resolve([username.value, password.value]).apply( - ([username, password]) => - Buffer.from(`${username}:${password}`).toString("base64") - ); - - new sst.aws.StaticSite("MySite", { - path: "site", - // Don't password protect prod - edge: $app.stage !== "production" - ? { - viewerRequest: { - injection: $interpolate` - if ( - !event.request.headers.authorization - || event.request.headers.authorization.value !== "Basic ${basicAuth}" - ) { - return { - statusCode: 401, - headers: { - "www-authenticate": { value: "Basic" } - } - }; - }`, - }, - } - : undefined, - }); - }, -}); diff --git a/examples/aws-static-site/package.json b/examples/aws-static-site/package.json deleted file mode 100644 index 5e4a51b0c2..0000000000 --- a/examples/aws-static-site/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "aws-static-site", - "version": "1.0.0", - "main": "index.js", - "devDependencies": { - "sst": "file:../../sdk/js" - }, - "scripts": { - "dev": "npx --yes serve ./site" - }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "" -} diff --git a/examples/aws-static-site/site/404.html b/examples/aws-static-site/site/404.html deleted file mode 100644 index e1dc7559af..0000000000 --- a/examples/aws-static-site/site/404.html +++ /dev/null @@ -1,7 +0,0 @@ - - - 404 Not Found - -

404 - Page Not Found

- - diff --git a/examples/aws-static-site/site/index.html b/examples/aws-static-site/site/index.html deleted file mode 100644 index 9605cebdeb..0000000000 --- a/examples/aws-static-site/site/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/examples/aws-static-site/sst.config.ts b/examples/aws-static-site/sst.config.ts deleted file mode 100644 index 2cde0b1837..0000000000 --- a/examples/aws-static-site/sst.config.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// - -/** - * ## AWS static site - * - * Deploy a simple HTML file as a static site with S3 and CloudFront. The website is stored in - * the `site/` directory. - */ -export default $config({ - app(input) { - return { - name: "aws-static-site", - home: "aws", - removal: input?.stage === "production" ? "retain" : "remove", - }; - }, - async run() { - new sst.aws.StaticSite("MySite", { - path: "site", - errorPage: "404.html", - }); - }, -}); diff --git a/examples/aws-step-functions-task-token/.gitignore b/examples/aws-step-functions-task-token/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-step-functions-task-token/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-step-functions-task-token/index.ts b/examples/aws-step-functions-task-token/index.ts deleted file mode 100644 index 4019bcbab7..0000000000 --- a/examples/aws-step-functions-task-token/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { SQSEvent } from "aws-lambda"; -import { SFNClient, SendTaskSuccessCommand } from "@aws-sdk/client-sfn"; - -const sfn = new SFNClient(); - -export async function handler(e: SQSEvent) { - // Parse the task token - const { body } = e.Records[0]; - const { MyTaskToken } = JSON.parse(body); - - // Do some work - await new Promise((resolve) => setTimeout(resolve, 1000)); - - // Call `SendTaskSuccess` to mark the task done - await sfn.send( - new SendTaskSuccessCommand({ - taskToken: MyTaskToken, - output: JSON.stringify({ result: "foo" }), - }) - ); - - return "ok"; -} diff --git a/examples/aws-step-functions-task-token/package.json b/examples/aws-step-functions-task-token/package.json deleted file mode 100644 index 6f54d1065d..0000000000 --- a/examples/aws-step-functions-task-token/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "aws-step-functions-task-token", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@aws-sdk/client-sfn": "^3.812.0", - "sst": "file:../../sdk/js" - }, - "devDependencies": { - "@types/aws-lambda": "^8.10.11" - } -} diff --git a/examples/aws-step-functions-task-token/sst.config.ts b/examples/aws-step-functions-task-token/sst.config.ts deleted file mode 100644 index bb47484940..0000000000 --- a/examples/aws-step-functions-task-token/sst.config.ts +++ /dev/null @@ -1,45 +0,0 @@ -/// - -/** - * ## AWS Step Functions task token - * - * Use Step Functions with task tokens to pause execution, send a message to an - * SQS queue, and resume after processing. - */ -export default $config({ - app(input) { - return { - name: "aws-step-functions-task-token", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // Create a queue the state machine will send messages to - const queue = new sst.aws.Queue("MyQueue"); - - // Define all the states of the state machine - const sendMessage = sst.aws.StepFunctions.sqsSendMessage({ - name: "SendMessage", - integration: "token", - queue, - messageBody: { - // Task token passed in the message body - MyTaskToken: "{% $states.context.Task.Token %}", - }, - }); - const success = sst.aws.StepFunctions.succeed({ name: "Succeed" }); - - // Create the state machine - const stepFunction = new sst.aws.StepFunctions("MyStateMachine", { - definition: sendMessage.next(success), - }); - - // Create a function that will receive messages from the queue - queue.subscribe({ - handler: "index.handler", - // Linking the state machine to grant permissions to call `SendTaskSuccess` - link: [stepFunction], - }); - }, -}); diff --git a/examples/aws-step-functions-task-token/tsconfig.json b/examples/aws-step-functions-task-token/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-step-functions-task-token/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-step-functions/.gitignore b/examples/aws-step-functions/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-step-functions/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-step-functions/index.ts b/examples/aws-step-functions/index.ts deleted file mode 100644 index 6e7064b8d5..0000000000 --- a/examples/aws-step-functions/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export async function handler() { - return { - message: "v1", - }; -} diff --git a/examples/aws-step-functions/package.json b/examples/aws-step-functions/package.json deleted file mode 100644 index f1d60f0a31..0000000000 --- a/examples/aws-step-functions/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "aws-step-functions", - "version": "1.0.0", - "description": "", - "type": "module", - "main": "index.js", - "scripts": { - "deploy": "go run ../../cmd/sst deploy", - "remove": "go run ../../cmd/sst remove", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-step-functions/sst.config.ts b/examples/aws-step-functions/sst.config.ts deleted file mode 100644 index e8982e1878..0000000000 --- a/examples/aws-step-functions/sst.config.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-step-functions", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - // Create a function to be invoked by the state machine - const app = new sst.aws.Function("MyApp", { - handler: "index.handler", - }); - - // Define all the states of the state machine - const lambdaInvoke = sst.aws.StepFunctions.lambdaInvoke({ - name: "LambdaInvoke", - function: app, - payload: { - foo: "bar", - }, - }); - const pass = sst.aws.StepFunctions.pass({ name: "Pass" }); - const wait = sst.aws.StepFunctions.wait({ - name: "Wait", - time: "2 seconds", - }); - const choice = sst.aws.StepFunctions.choice({ name: "Choice" }); - const parallel = sst.aws.StepFunctions.parallel({ name: "Parallel" }); - const parallelA = sst.aws.StepFunctions.pass({ name: "ParallelA" }); - const parallelB = sst.aws.StepFunctions.pass({ name: "ParallelB" }); - const parallelC = sst.aws.StepFunctions.pass({ name: "ParallelC" }); - const mapA = sst.aws.StepFunctions.pass({ name: "MapA" }); - const mapB = sst.aws.StepFunctions.pass({ name: "MapB" }); - const map = sst.aws.StepFunctions.map({ - name: "Map", - processor: mapA.next(mapB), - items: ["a", "b", "c"], - }); - const success = sst.aws.StepFunctions.succeed({ name: "Succeed" }); - const fail = sst.aws.StepFunctions.fail({ name: "Fail" }); - const last = sst.aws.StepFunctions.pass({ name: "Last" }); - - // Create the state machine - new sst.aws.StepFunctions("MyStateMachine", { - definition: lambdaInvoke - .catch(fail) - .next(pass) - .next(wait) - .next(parallel.branch(parallelA.next(parallelB)).branch(parallelC)) - .next(map) - .next( - choice - .when("{% 1+1 = 2 %}", success) - .when("{% 1+1 = 3 %}", fail) - .otherwise(last) - ), - }); - }, -}); diff --git a/examples/aws-step-functions/tsconfig.json b/examples/aws-step-functions/tsconfig.json deleted file mode 100644 index 0967ef424b..0000000000 --- a/examples/aws-step-functions/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/examples/aws-supabase-drizzle/.gitignore b/examples/aws-supabase-drizzle/.gitignore deleted file mode 100644 index cc54d25a17..0000000000 --- a/examples/aws-supabase-drizzle/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -# sst -.sst diff --git a/examples/aws-supabase-drizzle/drizzle.config.ts b/examples/aws-supabase-drizzle/drizzle.config.ts deleted file mode 100644 index 7f110ab1ad..0000000000 --- a/examples/aws-supabase-drizzle/drizzle.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from "drizzle-kit"; -import { Resource } from "sst"; -export default defineConfig({ - schema: ["./src/**/*.sql.ts"], - out: "./migrations", - dialect: "postgresql", - dbCredentials: { - host: Resource.Database.host, - database: Resource.Database.database, - port: Resource.Database.port, - user: Resource.Database.user, - password: Resource.Database.password, - }, -}); diff --git a/examples/aws-supabase-drizzle/migrations/0000_great_solo.sql b/examples/aws-supabase-drizzle/migrations/0000_great_solo.sql deleted file mode 100644 index db52d6f17f..0000000000 --- a/examples/aws-supabase-drizzle/migrations/0000_great_solo.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE IF NOT EXISTS "todo" ( - "id" serial PRIMARY KEY NOT NULL, - "title" text NOT NULL, - "description" text -); diff --git a/examples/aws-supabase-drizzle/migrations/meta/0000_snapshot.json b/examples/aws-supabase-drizzle/migrations/meta/0000_snapshot.json deleted file mode 100644 index 64994dcf98..0000000000 --- a/examples/aws-supabase-drizzle/migrations/meta/0000_snapshot.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "id": "60c8abb1-7e2d-4b3d-8bc3-68b4a51c8fb8", - "prevId": "00000000-0000-0000-0000-000000000000", - "version": "6", - "dialect": "postgresql", - "tables": { - "public.todo": { - "name": "todo", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {} - } - }, - "enums": {}, - "schemas": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/examples/aws-supabase-drizzle/migrations/meta/_journal.json b/examples/aws-supabase-drizzle/migrations/meta/_journal.json deleted file mode 100644 index 6088d1cbd8..0000000000 --- a/examples/aws-supabase-drizzle/migrations/meta/_journal.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "version": "5", - "dialect": "pg", - "entries": [ - { - "idx": 0, - "version": "6", - "when": 1715012302701, - "tag": "0000_great_solo", - "breakpoints": true - } - ] -} \ No newline at end of file diff --git a/examples/aws-supabase-drizzle/package.json b/examples/aws-supabase-drizzle/package.json deleted file mode 100644 index 9439872cd4..0000000000 --- a/examples/aws-supabase-drizzle/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "aws-supabase-drizzle", - "version": "0.0.0", - "type": "module", - "scripts": { - "db": "sst shell drizzle-kit", - "db:studio": "sst shell drizzle-kit studio", - "db:migrate": "sst shell drizzle-kit migrate" - }, - "dependencies": { - "@aws-sdk/client-rds-data": "^3.564.0", - "drizzle-kit": "0.20.17-679add7", - "drizzle-orm": "^0.30.9", - "postgres": "^3.4.4", - "sst": "file:../../sdk/js" - } -} diff --git a/examples/aws-supabase-drizzle/src/api.ts b/examples/aws-supabase-drizzle/src/api.ts deleted file mode 100644 index b4abb9a66d..0000000000 --- a/examples/aws-supabase-drizzle/src/api.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { db } from "./drizzle"; -import { todo } from "./todo.sql"; -import { APIGatewayProxyHandlerV2 } from "aws-lambda"; -import { randomUUID } from "node:crypto"; - -export const handler: APIGatewayProxyHandlerV2 = async (evt) => { - if (evt.requestContext.http.method === "GET") { - const result = await db.select().from(todo).execute(); - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } - - if (evt.requestContext.http.method === "POST") { - const result = await db - .insert(todo) - .values({ title: "new todo " + randomUUID() }) - .returning() - .execute(); - return { - statusCode: 200, - body: JSON.stringify(result), - }; - } - - return { - statusCode: 404, - body: "not found", - }; -}; diff --git a/examples/aws-supabase-drizzle/src/drizzle.ts b/examples/aws-supabase-drizzle/src/drizzle.ts deleted file mode 100644 index 72efbb6aa3..0000000000 --- a/examples/aws-supabase-drizzle/src/drizzle.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { drizzle } from "drizzle-orm/postgres-js"; -import { Resource } from "sst"; -import postgres from "postgres"; - -const client = postgres({ - password: Resource.Database.password, - user: Resource.Database.user, - port: Resource.Database.port, - host: Resource.Database.host, - db: "postgres", -}); - -export const db = drizzle(client); diff --git a/examples/aws-supabase-drizzle/src/todo.sql.ts b/examples/aws-supabase-drizzle/src/todo.sql.ts deleted file mode 100644 index 1de457f10b..0000000000 --- a/examples/aws-supabase-drizzle/src/todo.sql.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { pgTable, text, serial } from "drizzle-orm/pg-core"; - -export const todo = pgTable("todo", { - id: serial("id").primaryKey(), - title: text("title").notNull(), - description: text("description"), -}); diff --git a/examples/aws-supabase-drizzle/sst.config.ts b/examples/aws-supabase-drizzle/sst.config.ts deleted file mode 100644 index 232b2e7e53..0000000000 --- a/examples/aws-supabase-drizzle/sst.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-supabase-drizzle", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - providers: { - random: true, - supabase: true, - }, - }; - }, - async run() { - sst.Linkable.wrap(supabase.Project, function (item) { - return { - properties: { - user: $interpolate`postgres.${item.id}`, - password: item.databasePassword, - host: $interpolate`aws-0-${item.region}.pooler.supabase.com`, - port: 5432, - database: "postgres", - }, - }; - }); - const project = new supabase.Project("Database", { - name: $interpolate`${$app.name}-${$app.stage}`, - region: "us-east-1", - organizationId: process.env.SUPABASE_ORG_ID!, - databasePassword: new random.RandomString("DatabasePassword", { - length: 16, - }).result, - }); - const api = new sst.aws.Function("Api", { - url: true, - handler: "src/api.handler", - link: [project], - }); - return { - url: api.url, - }; - }, -}); diff --git a/examples/aws-supabase-drizzle/tsconfig.json b/examples/aws-supabase-drizzle/tsconfig.json deleted file mode 100644 index b6955c086e..0000000000 --- a/examples/aws-supabase-drizzle/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "esModuleInterop": true, - } -} diff --git a/examples/aws-svelte-container/.dockerignore b/examples/aws-svelte-container/.dockerignore deleted file mode 100644 index 54159dd073..0000000000 --- a/examples/aws-svelte-container/.dockerignore +++ /dev/null @@ -1,6 +0,0 @@ -.DS_Store -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-svelte-container/.gitignore b/examples/aws-svelte-container/.gitignore deleted file mode 100644 index 82ed85c1d6..0000000000 --- a/examples/aws-svelte-container/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -node_modules - -# Output -.output -.vercel -/.svelte-kit -/build - -# OS -.DS_Store -Thumbs.db - -# Env -.env -.env.* -!.env.example -!.env.test - -# Vite -vite.config.js.timestamp-* -vite.config.ts.timestamp-* - -# sst -.sst diff --git a/examples/aws-svelte-container/.npmrc b/examples/aws-svelte-container/.npmrc deleted file mode 100644 index b6f27f1359..0000000000 --- a/examples/aws-svelte-container/.npmrc +++ /dev/null @@ -1 +0,0 @@ -engine-strict=true diff --git a/examples/aws-svelte-container/Dockerfile b/examples/aws-svelte-container/Dockerfile deleted file mode 100644 index 6c82f47358..0000000000 --- a/examples/aws-svelte-container/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM node:18.18.0-alpine AS builder - -WORKDIR /app -COPY package*.json . -RUN npm install -COPY . . -RUN npm run build -RUN npm prune --prod - -FROM builder AS deployer - -WORKDIR /app -COPY --from=builder /app/build build/ -COPY --from=builder /app/package.json . -EXPOSE 3000 -ENV NODE_ENV=production -CMD [ "node", "build" ] diff --git a/examples/aws-svelte-container/package.json b/examples/aws-svelte-container/package.json deleted file mode 100644 index f62de0b433..0000000000 --- a/examples/aws-svelte-container/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "aws-svelte-container", - "version": "0.0.1", - "type": "module", - "scripts": { - "build": "vite build", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", - "dev": "vite dev", - "preview": "vite preview" - }, - "devDependencies": { - "@sveltejs/adapter-auto": "^3.0.0", - "@sveltejs/adapter-node": "^5.2.9", - "@sveltejs/kit": "^2.0.0", - "@sveltejs/vite-plugin-svelte": "^4.0.0", - "svelte": "^5.0.0", - "svelte-check": "^4.0.0", - "typescript": "^5.0.0", - "vite": "^5.0.3" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.701.0", - "@aws-sdk/s3-request-presigner": "^3.701.0", - "sst": "file:../../sdk/js", - "svelte-kit-sst": "2.43.5" - } -} diff --git a/examples/aws-svelte-container/src/app.d.ts b/examples/aws-svelte-container/src/app.d.ts deleted file mode 100644 index da08e6da59..0000000000 --- a/examples/aws-svelte-container/src/app.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// See https://svelte.dev/docs/kit/types#app.d.ts -// for information about these interfaces -declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface PageState {} - // interface Platform {} - } -} - -export {}; diff --git a/examples/aws-svelte-container/src/app.html b/examples/aws-svelte-container/src/app.html deleted file mode 100644 index 77a5ff52c9..0000000000 --- a/examples/aws-svelte-container/src/app.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - %sveltekit.head% - - -
%sveltekit.body%
- - diff --git a/examples/aws-svelte-container/src/lib/index.ts b/examples/aws-svelte-container/src/lib/index.ts deleted file mode 100644 index 856f2b6c38..0000000000 --- a/examples/aws-svelte-container/src/lib/index.ts +++ /dev/null @@ -1 +0,0 @@ -// place files you want to import through the `$lib` alias in this folder. diff --git a/examples/aws-svelte-container/src/routes/+page.server.ts b/examples/aws-svelte-container/src/routes/+page.server.ts deleted file mode 100644 index d5ff41caed..0000000000 --- a/examples/aws-svelte-container/src/routes/+page.server.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -/** @type {import('./$types').PageServerLoad} */ -export async function load() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return { url }; -} diff --git a/examples/aws-svelte-container/src/routes/+page.svelte b/examples/aws-svelte-container/src/routes/+page.svelte deleted file mode 100644 index cbc3260f8b..0000000000 --- a/examples/aws-svelte-container/src/routes/+page.svelte +++ /dev/null @@ -1,38 +0,0 @@ - - - - -
-
- - -
-
diff --git a/examples/aws-svelte-container/sst.config.ts b/examples/aws-svelte-container/sst.config.ts deleted file mode 100644 index dac8837874..0000000000 --- a/examples/aws-svelte-container/sst.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-svelte-container", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc"); - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public", - }); - - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [bucket], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-svelte-container/static/favicon.png b/examples/aws-svelte-container/static/favicon.png deleted file mode 100644 index 825b9e65af..0000000000 Binary files a/examples/aws-svelte-container/static/favicon.png and /dev/null differ diff --git a/examples/aws-svelte-container/svelte.config.js b/examples/aws-svelte-container/svelte.config.js deleted file mode 100644 index e0a641ee7f..0000000000 --- a/examples/aws-svelte-container/svelte.config.js +++ /dev/null @@ -1,18 +0,0 @@ -import adapter from '@sveltejs/adapter-node'; -import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; - -/** @type {import('@sveltejs/kit').Config} */ -const config = { - // Consult https://svelte.dev/docs/kit/integrations - // for more information about preprocessors - preprocess: vitePreprocess(), - - kit: { - // adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list. - // If your environment is not supported, or you settled on a specific environment, switch out the adapter. - // See https://svelte.dev/docs/kit/adapters for more information about adapters. - adapter: adapter() - } -}; - -export default config; diff --git a/examples/aws-svelte-container/tsconfig.json b/examples/aws-svelte-container/tsconfig.json deleted file mode 100644 index 0b2d8865f4..0000000000 --- a/examples/aws-svelte-container/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "./.svelte-kit/tsconfig.json", - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "sourceMap": true, - "strict": true, - "moduleResolution": "bundler" - } - // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias - // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files - // - // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes - // from the referenced tsconfig.json - TypeScript does not merge them in -} diff --git a/examples/aws-svelte-container/vite.config.ts b/examples/aws-svelte-container/vite.config.ts deleted file mode 100644 index bbf8c7da43..0000000000 --- a/examples/aws-svelte-container/vite.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { sveltekit } from '@sveltejs/kit/vite'; -import { defineConfig } from 'vite'; - -export default defineConfig({ - plugins: [sveltekit()] -}); diff --git a/examples/aws-svelte-kit-remote-functions/.gitignore b/examples/aws-svelte-kit-remote-functions/.gitignore deleted file mode 100644 index 37e9161d16..0000000000 --- a/examples/aws-svelte-kit-remote-functions/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -node_modules - -# Output -.output -.vercel -/.svelte-kit -/build - -# OS -.DS_Store -Thumbs.db - -# Env -.env -.env.* -!.env.example -!.env.test - -# Vite -vite.config.js.timestamp-* -vite.config.ts.timestamp-* - -# sst -.sst - diff --git a/examples/aws-svelte-kit-remote-functions/.npmrc b/examples/aws-svelte-kit-remote-functions/.npmrc deleted file mode 100644 index b6f27f1359..0000000000 --- a/examples/aws-svelte-kit-remote-functions/.npmrc +++ /dev/null @@ -1 +0,0 @@ -engine-strict=true diff --git a/examples/aws-svelte-kit-remote-functions/package.json b/examples/aws-svelte-kit-remote-functions/package.json deleted file mode 100644 index 2996b0ffc1..0000000000 --- a/examples/aws-svelte-kit-remote-functions/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "aws-svelte-kit-remote-functions", - "private": true, - "version": "0.0.1", - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "preview": "vite preview", - "prepare": "svelte-kit sync || echo ''", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" - }, - "devDependencies": { - "@sveltejs/adapter-auto": "^6.1.0", - "@sveltejs/kit": "^2.43.2", - "@sveltejs/vite-plugin-svelte": "^6.2.0", - "@tailwindcss/vite": "^4.1.13", - "svelte": "^5.39.5", - "svelte-check": "^4.3.2", - "tailwindcss": "^4.1.13", - "typescript": "^5.9.2", - "vite": "^7.1.7" - }, - "dependencies": { - "sst": "file:../../sdk/js", - "svelte-kit-sst": "latest" - } -} diff --git a/examples/aws-svelte-kit-remote-functions/src/app.css b/examples/aws-svelte-kit-remote-functions/src/app.css deleted file mode 100644 index d4b5078586..0000000000 --- a/examples/aws-svelte-kit-remote-functions/src/app.css +++ /dev/null @@ -1 +0,0 @@ -@import 'tailwindcss'; diff --git a/examples/aws-svelte-kit-remote-functions/src/app.d.ts b/examples/aws-svelte-kit-remote-functions/src/app.d.ts deleted file mode 100644 index da08e6da59..0000000000 --- a/examples/aws-svelte-kit-remote-functions/src/app.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// See https://svelte.dev/docs/kit/types#app.d.ts -// for information about these interfaces -declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface PageState {} - // interface Platform {} - } -} - -export {}; diff --git a/examples/aws-svelte-kit-remote-functions/src/app.html b/examples/aws-svelte-kit-remote-functions/src/app.html deleted file mode 100644 index f273cc58f7..0000000000 --- a/examples/aws-svelte-kit-remote-functions/src/app.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - %sveltekit.head% - - -
%sveltekit.body%
- - diff --git a/examples/aws-svelte-kit-remote-functions/src/lib/assets/favicon.svg b/examples/aws-svelte-kit-remote-functions/src/lib/assets/favicon.svg deleted file mode 100644 index cc5dc66a3a..0000000000 --- a/examples/aws-svelte-kit-remote-functions/src/lib/assets/favicon.svg +++ /dev/null @@ -1 +0,0 @@ -svelte-logo \ No newline at end of file diff --git a/examples/aws-svelte-kit-remote-functions/src/routes/+page.svelte b/examples/aws-svelte-kit-remote-functions/src/routes/+page.svelte deleted file mode 100644 index 9890126cad..0000000000 --- a/examples/aws-svelte-kit-remote-functions/src/routes/+page.svelte +++ /dev/null @@ -1,24 +0,0 @@ - - - - {#snippet pending()} -

Loading...

- {/snippet} - - {#snippet failed(err, reset)} -

Error: {err}

- - {/snippet} - -
    - {#each await getArbitraryData() as item} -
  • {item}
  • - {/each} -
-
diff --git a/examples/aws-svelte-kit-remote-functions/src/routes/home.remote.ts b/examples/aws-svelte-kit-remote-functions/src/routes/home.remote.ts deleted file mode 100644 index b36e1eb5c7..0000000000 --- a/examples/aws-svelte-kit-remote-functions/src/routes/home.remote.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { query } from "$app/server"; - -export const getArbitraryData = query(async () => { - await new Promise((resolve) => setTimeout(resolve, 2000)); - return ["foo", "bar", "baz"]; -}); diff --git a/examples/aws-svelte-kit-remote-functions/sst.config.ts b/examples/aws-svelte-kit-remote-functions/sst.config.ts deleted file mode 100644 index b50ebbfb2b..0000000000 --- a/examples/aws-svelte-kit-remote-functions/sst.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-svelte-kit-remote-functions", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - new sst.aws.SvelteKit("MyWeb", { - dev: { - command: "bun run dev", - }, - }); - }, -}); diff --git a/examples/aws-svelte-kit-remote-functions/static/robots.txt b/examples/aws-svelte-kit-remote-functions/static/robots.txt deleted file mode 100644 index b6dd6670cb..0000000000 --- a/examples/aws-svelte-kit-remote-functions/static/robots.txt +++ /dev/null @@ -1,3 +0,0 @@ -# allow crawling everything by default -User-agent: * -Disallow: diff --git a/examples/aws-svelte-kit-remote-functions/svelte.config.js b/examples/aws-svelte-kit-remote-functions/svelte.config.js deleted file mode 100644 index 77f720c3d8..0000000000 --- a/examples/aws-svelte-kit-remote-functions/svelte.config.js +++ /dev/null @@ -1,25 +0,0 @@ -import adapter from "svelte-kit-sst"; -import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; - -/** @type {import('@sveltejs/kit').Config} */ -const config = { - // Consult https://svelte.dev/docs/kit/integrations - // for more information about preprocessors - preprocess: vitePreprocess(), - compilerOptions: { - experimental: { - async: true, - }, - }, - kit: { - experimental: { - remoteFunctions: true, - }, - // adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list. - // If your environment is not supported, or you settled on a specific environment, switch out the adapter. - // See https://svelte.dev/docs/kit/adapters for more information about adapters. - adapter: adapter(), - }, -}; - -export default config; diff --git a/examples/aws-svelte-kit-remote-functions/tsconfig.json b/examples/aws-svelte-kit-remote-functions/tsconfig.json deleted file mode 100644 index a5567ee6bb..0000000000 --- a/examples/aws-svelte-kit-remote-functions/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "./.svelte-kit/tsconfig.json", - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "sourceMap": true, - "strict": true, - "moduleResolution": "bundler" - } - // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias - // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files - // - // To make changes to top-level options such as include and exclude, we recommend extending - // the generated config; see https://svelte.dev/docs/kit/configuration#typescript -} diff --git a/examples/aws-svelte-kit-remote-functions/vite.config.ts b/examples/aws-svelte-kit-remote-functions/vite.config.ts deleted file mode 100644 index 2d35c4f5af..0000000000 --- a/examples/aws-svelte-kit-remote-functions/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import tailwindcss from '@tailwindcss/vite'; -import { sveltekit } from '@sveltejs/kit/vite'; -import { defineConfig } from 'vite'; - -export default defineConfig({ - plugins: [tailwindcss(), sveltekit()] -}); diff --git a/examples/aws-svelte-kit/.gitignore b/examples/aws-svelte-kit/.gitignore deleted file mode 100644 index 82ed85c1d6..0000000000 --- a/examples/aws-svelte-kit/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -node_modules - -# Output -.output -.vercel -/.svelte-kit -/build - -# OS -.DS_Store -Thumbs.db - -# Env -.env -.env.* -!.env.example -!.env.test - -# Vite -vite.config.js.timestamp-* -vite.config.ts.timestamp-* - -# sst -.sst diff --git a/examples/aws-svelte-kit/.npmrc b/examples/aws-svelte-kit/.npmrc deleted file mode 100644 index b6f27f1359..0000000000 --- a/examples/aws-svelte-kit/.npmrc +++ /dev/null @@ -1 +0,0 @@ -engine-strict=true diff --git a/examples/aws-svelte-kit/package.json b/examples/aws-svelte-kit/package.json deleted file mode 100644 index 7db901eb05..0000000000 --- a/examples/aws-svelte-kit/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "aws-svelte-kit", - "version": "0.0.1", - "type": "module", - "scripts": { - "build": "vite build", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", - "dev": "vite dev", - "preview": "vite preview" - }, - "devDependencies": { - "@sveltejs/adapter-auto": "^3.0.0", - "@sveltejs/kit": "^2.0.0", - "@sveltejs/vite-plugin-svelte": "^4.0.0", - "svelte": "^5.0.0", - "svelte-check": "^4.0.0", - "typescript": "^5.0.0", - "vite": "^5.0.3" - }, - "dependencies": { - "@aws-sdk/client-s3": "^3.700.0", - "@aws-sdk/s3-request-presigner": "^3.700.0", - "sst": "file:../../sdk/js", - "svelte-kit-sst": "2.43.5" - } -} diff --git a/examples/aws-svelte-kit/src/app.d.ts b/examples/aws-svelte-kit/src/app.d.ts deleted file mode 100644 index da08e6da59..0000000000 --- a/examples/aws-svelte-kit/src/app.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// See https://svelte.dev/docs/kit/types#app.d.ts -// for information about these interfaces -declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface PageState {} - // interface Platform {} - } -} - -export {}; diff --git a/examples/aws-svelte-kit/src/app.html b/examples/aws-svelte-kit/src/app.html deleted file mode 100644 index 77a5ff52c9..0000000000 --- a/examples/aws-svelte-kit/src/app.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - %sveltekit.head% - - -
%sveltekit.body%
- - diff --git a/examples/aws-svelte-kit/src/lib/index.ts b/examples/aws-svelte-kit/src/lib/index.ts deleted file mode 100644 index 856f2b6c38..0000000000 --- a/examples/aws-svelte-kit/src/lib/index.ts +++ /dev/null @@ -1 +0,0 @@ -// place files you want to import through the `$lib` alias in this folder. diff --git a/examples/aws-svelte-kit/src/routes/+page.server.ts b/examples/aws-svelte-kit/src/routes/+page.server.ts deleted file mode 100644 index d5ff41caed..0000000000 --- a/examples/aws-svelte-kit/src/routes/+page.server.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Resource } from "sst"; -import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; -import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; - -/** @type {import('./$types').PageServerLoad} */ -export async function load() { - const command = new PutObjectCommand({ - Key: crypto.randomUUID(), - Bucket: Resource.MyBucket.name, - }); - const url = await getSignedUrl(new S3Client({}), command); - - return { url }; -} diff --git a/examples/aws-svelte-kit/src/routes/+page.svelte b/examples/aws-svelte-kit/src/routes/+page.svelte deleted file mode 100644 index cbc3260f8b..0000000000 --- a/examples/aws-svelte-kit/src/routes/+page.svelte +++ /dev/null @@ -1,38 +0,0 @@ - - - - -
-
- - -
-
diff --git a/examples/aws-svelte-kit/sst.config.ts b/examples/aws-svelte-kit/sst.config.ts deleted file mode 100644 index ac35800175..0000000000 --- a/examples/aws-svelte-kit/sst.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// - -export default $config({ - app(input) { - return { - name: "aws-svelte-kit", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const bucket = new sst.aws.Bucket("MyBucket", { - access: "public" - }); - new sst.aws.SvelteKit("MyWeb", { - link: [bucket] - }); - }, -}); diff --git a/examples/aws-svelte-kit/static/favicon.png b/examples/aws-svelte-kit/static/favicon.png deleted file mode 100644 index 825b9e65af..0000000000 Binary files a/examples/aws-svelte-kit/static/favicon.png and /dev/null differ diff --git a/examples/aws-svelte-kit/svelte.config.js b/examples/aws-svelte-kit/svelte.config.js deleted file mode 100644 index 7ea4b69156..0000000000 --- a/examples/aws-svelte-kit/svelte.config.js +++ /dev/null @@ -1,18 +0,0 @@ -import adapter from "svelte-kit-sst"; -import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; - -/** @type {import('@sveltejs/kit').Config} */ -const config = { - // Consult https://svelte.dev/docs/kit/integrations - // for more information about preprocessors - preprocess: vitePreprocess(), - - kit: { - // adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list. - // If your environment is not supported, or you settled on a specific environment, switch out the adapter. - // See https://svelte.dev/docs/kit/adapters for more information about adapters. - adapter: adapter() - } -}; - -export default config; diff --git a/examples/aws-svelte-kit/tsconfig.json b/examples/aws-svelte-kit/tsconfig.json deleted file mode 100644 index 0b2d8865f4..0000000000 --- a/examples/aws-svelte-kit/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "./.svelte-kit/tsconfig.json", - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "sourceMap": true, - "strict": true, - "moduleResolution": "bundler" - } - // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias - // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files - // - // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes - // from the referenced tsconfig.json - TypeScript does not merge them in -} diff --git a/examples/aws-svelte-kit/vite.config.ts b/examples/aws-svelte-kit/vite.config.ts deleted file mode 100644 index bbf8c7da43..0000000000 --- a/examples/aws-svelte-kit/vite.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { sveltekit } from '@sveltejs/kit/vite'; -import { defineConfig } from 'vite'; - -export default defineConfig({ - plugins: [sveltekit()] -}); diff --git a/examples/aws-svelte-redis/.dockerignore b/examples/aws-svelte-redis/.dockerignore deleted file mode 100644 index ea0aaeeec9..0000000000 --- a/examples/aws-svelte-redis/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules - - -# sst -.sst \ No newline at end of file diff --git a/examples/aws-svelte-redis/.gitignore b/examples/aws-svelte-redis/.gitignore deleted file mode 100644 index 82ed85c1d6..0000000000 --- a/examples/aws-svelte-redis/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -node_modules - -# Output -.output -.vercel -/.svelte-kit -/build - -# OS -.DS_Store -Thumbs.db - -# Env -.env -.env.* -!.env.example -!.env.test - -# Vite -vite.config.js.timestamp-* -vite.config.ts.timestamp-* - -# sst -.sst diff --git a/examples/aws-svelte-redis/.npmrc b/examples/aws-svelte-redis/.npmrc deleted file mode 100644 index b6f27f1359..0000000000 --- a/examples/aws-svelte-redis/.npmrc +++ /dev/null @@ -1 +0,0 @@ -engine-strict=true diff --git a/examples/aws-svelte-redis/Dockerfile b/examples/aws-svelte-redis/Dockerfile deleted file mode 100644 index 442e34ca15..0000000000 --- a/examples/aws-svelte-redis/Dockerfile +++ /dev/null @@ -1,28 +0,0 @@ -FROM node:lts-alpine AS builder - -# Add linked resources to the environment -ARG SST_RESOURCE_MyRedis - -WORKDIR /app - -COPY package*.json . - -RUN npm install - -COPY . . - -RUN npm run build -RUN npm prune --prod - -FROM builder AS deployer - -WORKDIR /app - -COPY --from=builder /app/build build/ -COPY --from=builder /app/package.json . - -EXPOSE 3000 - -ENV NODE_ENV=production - -CMD [ "node", "build" ] diff --git a/examples/aws-svelte-redis/package.json b/examples/aws-svelte-redis/package.json deleted file mode 100644 index 4eee5e0d29..0000000000 --- a/examples/aws-svelte-redis/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "aws-svelte-redis", - "version": "0.0.1", - "private": true, - "scripts": { - "build": "vite build", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", - "dev": "vite dev", - "preview": "vite preview" - }, - "devDependencies": { - "@sveltejs/adapter-auto": "^3.0.0", - "@sveltejs/adapter-node": "^5.2.6", - "@sveltejs/kit": "^2.0.0", - "@sveltejs/vite-plugin-svelte": "^3.0.0", - "svelte": "^4.2.7", - "svelte-check": "^4.0.0", - "typescript": "^5.0.0", - "vite": "^5.0.3" - }, - "type": "module", - "dependencies": { - "ioredis": "^5.4.1", - "sst": "file:../../sdk/js", - "svelte-kit-sst": "2.43.5" - } -} diff --git a/examples/aws-svelte-redis/src/app.d.ts b/examples/aws-svelte-redis/src/app.d.ts deleted file mode 100644 index 743f07b2e5..0000000000 --- a/examples/aws-svelte-redis/src/app.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// See https://kit.svelte.dev/docs/types#app -// for information about these interfaces -declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface PageState {} - // interface Platform {} - } -} - -export {}; diff --git a/examples/aws-svelte-redis/src/app.html b/examples/aws-svelte-redis/src/app.html deleted file mode 100644 index 77a5ff52c9..0000000000 --- a/examples/aws-svelte-redis/src/app.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - %sveltekit.head% - - -
%sveltekit.body%
- - diff --git a/examples/aws-svelte-redis/src/lib/index.ts b/examples/aws-svelte-redis/src/lib/index.ts deleted file mode 100644 index 856f2b6c38..0000000000 --- a/examples/aws-svelte-redis/src/lib/index.ts +++ /dev/null @@ -1 +0,0 @@ -// place files you want to import through the `$lib` alias in this folder. diff --git a/examples/aws-svelte-redis/src/routes/+page.server.ts b/examples/aws-svelte-redis/src/routes/+page.server.ts deleted file mode 100644 index 237509c421..0000000000 --- a/examples/aws-svelte-redis/src/routes/+page.server.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Resource } from "sst"; -import { Cluster } from "ioredis"; - -const redis = new Cluster( - [{ host: Resource.MyRedis.host, port: Resource.MyRedis.port }], - { - dnsLookup: (address, callback) => callback(null, address), - redisOptions: { - tls: {}, - username: Resource.MyRedis.username, - password: Resource.MyRedis.password, - }, - } -); - -/** @type {import('./$types').PageServerLoad} */ -export async function load() { - const counter = await redis.incr("counter"); - - return { counter }; -} diff --git a/examples/aws-svelte-redis/src/routes/+page.svelte b/examples/aws-svelte-redis/src/routes/+page.svelte deleted file mode 100644 index d128445512..0000000000 --- a/examples/aws-svelte-redis/src/routes/+page.svelte +++ /dev/null @@ -1,6 +0,0 @@ - - -

Hit counter: {data.counter}

diff --git a/examples/aws-svelte-redis/sst.config.ts b/examples/aws-svelte-redis/sst.config.ts deleted file mode 100644 index dba368da71..0000000000 --- a/examples/aws-svelte-redis/sst.config.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// - -/** - * ## AWS SvelteKit container with Redis - * - * Creates a hit counter app with SvelteKit and Redis. - * - * This deploys SvelteKit as a Fargate service to ECS and it's linked to Redis. - * - * ```ts title="sst.config.ts" {3} - * new sst.aws.Service("MyService", { - * cluster, - * link: [redis], - * loadBalancer: { - * ports: [{ listen: "80/http", forward: "3000/http" }], - * }, - * dev: { - * command: "npm run dev", - * }, - * }); - * ``` - * - * Since our Redis cluster is in a VPC, we’ll need a tunnel to connect to it from our local - * machine. - * - * ```bash "sudo" - * sudo npx sst tunnel install - * ``` - * - * This needs _sudo_ to create a network interface on your machine. You’ll only need to do this - * once on your machine. - * - * To start your app locally run. - * - * ```bash - * npx sst dev - * ``` - * - * Now if you go to `http://localhost:5173` you’ll see a counter update as you refresh the page. - * - * Finally, you can deploy it by adding the `Dockerfile` that's included in this example and - * running `npx sst deploy --stage production`. - */ -export default $config({ - app(input) { - return { - name: "aws-svelte-redis", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true }); - const redis = new sst.aws.Redis("MyRedis", { vpc }); - const cluster = new sst.aws.Cluster("MyCluster", { vpc }); - - new sst.aws.Service("MyService", { - cluster, - link: [redis], - loadBalancer: { - ports: [{ listen: "80/http", forward: "3000/http" }], - }, - dev: { - command: "npm run dev", - }, - }); - }, -}); diff --git a/examples/aws-svelte-redis/static/favicon.png b/examples/aws-svelte-redis/static/favicon.png deleted file mode 100644 index 825b9e65af..0000000000 Binary files a/examples/aws-svelte-redis/static/favicon.png and /dev/null differ diff --git a/examples/aws-svelte-redis/svelte.config.js b/examples/aws-svelte-redis/svelte.config.js deleted file mode 100644 index fffb8494ec..0000000000 --- a/examples/aws-svelte-redis/svelte.config.js +++ /dev/null @@ -1,18 +0,0 @@ -import adapter from '@sveltejs/adapter-node'; -import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; - -/** @type {import('@sveltejs/kit').Config} */ -const config = { - // Consult https://kit.svelte.dev/docs/integrations#preprocessors - // for more information about preprocessors - preprocess: vitePreprocess(), - - kit: { - // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. - // If your environment is not supported, or you settled on a specific environment, switch out the adapter. - // See https://kit.svelte.dev/docs/adapters for more information about adapters. - adapter: adapter() - } -}; - -export default config; diff --git a/examples/aws-svelte-redis/tsconfig.json b/examples/aws-svelte-redis/tsconfig.json deleted file mode 100644 index 60c2cf6020..0000000000 --- a/examples/aws-svelte-redis/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "extends": "./.svelte-kit/tsconfig.json", - "include": [ - "ambient.d.ts", - "non-ambient.d.ts", - "./types/**/$types.d.ts", - "../sst-env.d.ts", - "../vite.config.js", - "../vite.config.ts", - "../src/**/*.js", - "../src/**/*.ts", - "../src/**/*.svelte", - "../tests/**/*.js", - "../tests/**/*.ts", - "../tests/**/*.svelte" - ], - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "sourceMap": true, - "strict": true, - "moduleResolution": "bundler" - } - // Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias - // except $lib which is handled by https://kit.svelte.dev/docs/configuration#files - // - // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes - // from the referenced tsconfig.json - TypeScript does not merge them in -} diff --git a/examples/aws-svelte-redis/vite.config.ts b/examples/aws-svelte-redis/vite.config.ts deleted file mode 100644 index bbf8c7da43..0000000000 --- a/examples/aws-svelte-redis/vite.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { sveltekit } from '@sveltejs/kit/vite'; -import { defineConfig } from 'vite'; - -export default defineConfig({ - plugins: [sveltekit()] -}); diff --git a/examples/aws-swift/.gitignore b/examples/aws-swift/.gitignore deleted file mode 100644 index 170c6abc12..0000000000 --- a/examples/aws-swift/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -.DS_Store -/.build -/Packages -xcuserdata/ -DerivedData/ -.swiftpm/configuration/registries.json -.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata -.netrc - -# sst -.sst diff --git a/examples/aws-swift/Package.resolved b/examples/aws-swift/Package.resolved deleted file mode 100644 index cdd70ce01d..0000000000 --- a/examples/aws-swift/Package.resolved +++ /dev/null @@ -1,69 +0,0 @@ -{ - "originHash" : "3450710b2977c7d009c49e0f4520bf340c82a58cf41f2fbcfa9012df78a27936", - "pins" : [ - { - "identity" : "swift-atomics", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-atomics.git", - "state" : { - "revision" : "cd142fd2f64be2100422d658e7411e39489da985", - "version" : "1.2.0" - } - }, - { - "identity" : "swift-aws-lambda-events", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swift-server/swift-aws-lambda-events.git", - "state" : { - "branch" : "main", - "revision" : "5b4633d1cc511a179ace6793d45fb973232b2c6c" - } - }, - { - "identity" : "swift-aws-lambda-runtime", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swift-server/swift-aws-lambda-runtime.git", - "state" : { - "branch" : "main", - "revision" : "e6a59c2cf0f35740d4ea72a702f69e45c20a974d" - } - }, - { - "identity" : "swift-collections", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-collections.git", - "state" : { - "revision" : "94cf62b3ba8d4bed62680a282d4c25f9c63c2efb", - "version" : "1.1.0" - } - }, - { - "identity" : "swift-log", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-log.git", - "state" : { - "revision" : "e97a6fcb1ab07462881ac165fdbb37f067e205d5", - "version" : "1.5.4" - } - }, - { - "identity" : "swift-nio", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-nio.git", - "state" : { - "revision" : "fc63f0cf4e55a4597407a9fc95b16a2bc44b4982", - "version" : "2.64.0" - } - }, - { - "identity" : "swift-system", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-system.git", - "state" : { - "revision" : "025bcb1165deab2e20d4eaba79967ce73013f496", - "version" : "1.2.1" - } - } - ], - "version" : 3 -} diff --git a/examples/aws-swift/Package.swift b/examples/aws-swift/Package.swift deleted file mode 100644 index 00ce5fb110..0000000000 --- a/examples/aws-swift/Package.swift +++ /dev/null @@ -1,23 +0,0 @@ -// swift-tools-version: 5.10 - -import PackageDescription - -let package = Package( - name: "swift", - platforms: [ - .macOS(.v14) - ], - dependencies: [ - .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", branch: "main"), - .package(url: "https://github.com/swift-server/swift-aws-lambda-events.git", branch: "main"), - ], - targets: [ - .executableTarget( - name: "app", - dependencies: [ - .product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"), - .product(name: "AWSLambdaEvents", package: "swift-aws-lambda-events"), - ] - ) - ] -) diff --git a/examples/aws-swift/Sources/App.swift b/examples/aws-swift/Sources/App.swift deleted file mode 100644 index 0ca9f498f3..0000000000 --- a/examples/aws-swift/Sources/App.swift +++ /dev/null @@ -1,15 +0,0 @@ -import AWSLambdaEvents -import AWSLambdaRuntime - -@main -struct App: SimpleLambdaHandler { - func handle( - _ event: APIGatewayV2Request, context: LambdaContext - ) async throws -> APIGatewayV2Response { - .init( - statusCode: .ok, - headers: ["Content-Type": "text/plain"], - body: "Hello, Swift" - ) - } -} diff --git a/examples/aws-swift/sst.config.ts b/examples/aws-swift/sst.config.ts deleted file mode 100644 index 7ed8591bfd..0000000000 --- a/examples/aws-swift/sst.config.ts +++ /dev/null @@ -1,51 +0,0 @@ -/// - -const swiftVersion = "5.10"; - -/** - * ## Swift in Lambda - * - * Deploys a simple Swift application to Lambda using the `al2023` runtime. - * - * :::note - * Building this function requires Docker. - * ::: - * - * Check out the README in the repo for more details. - */ -export default $config({ - app(input) { - return { - name: "aws-swift", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const swift = new sst.aws.Function("Swift", { - runtime: "provided.al2023", - architecture: process.arch === "arm64" ? "arm64" : "x86_64", - bundle: build("app"), - handler: "bootstrap", - url: true, - }); - const router = new sst.aws.Router("SwiftRouter", { - routes: { - "/*": swift.url, - }, - domain: "swift.dev.sst.dev", - }); - return { - url: router.url, - }; - }, -}); - -function build(target: string) { - require("child_process").execSync(` - swift package --disable-sandbox archive --products ${target} --swift-version ${swiftVersion} - mkdir -p .build/lambda/${target} - cp .build/release/${target} .build/lambda/${target}/bootstrap - `); - return `.build/lambda/${target}`; -} diff --git a/examples/aws-t3/.eslintrc.cjs b/examples/aws-t3/.eslintrc.cjs deleted file mode 100644 index 88c180dda5..0000000000 --- a/examples/aws-t3/.eslintrc.cjs +++ /dev/null @@ -1,61 +0,0 @@ -/** @type {import("eslint").Linter.Config} */ -const config = { - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": true - }, - "plugins": [ - "@typescript-eslint", - "drizzle" - ], - "extends": [ - "next/core-web-vitals", - "plugin:@typescript-eslint/recommended-type-checked", - "plugin:@typescript-eslint/stylistic-type-checked" - ], - "rules": { - "@typescript-eslint/array-type": "off", - "@typescript-eslint/consistent-type-definitions": "off", - "@typescript-eslint/consistent-type-imports": [ - "warn", - { - "prefer": "type-imports", - "fixStyle": "inline-type-imports" - } - ], - "@typescript-eslint/no-unused-vars": [ - "warn", - { - "argsIgnorePattern": "^_" - } - ], - "@typescript-eslint/require-await": "off", - "@typescript-eslint/no-misused-promises": [ - "error", - { - "checksVoidReturn": { - "attributes": false - } - } - ], - "drizzle/enforce-delete-with-where": [ - "error", - { - "drizzleObjectName": [ - "db", - "ctx.db" - ] - } - ], - "drizzle/enforce-update-with-where": [ - "error", - { - "drizzleObjectName": [ - "db", - "ctx.db" - ] - } - ] - } -} -module.exports = config; \ No newline at end of file diff --git a/examples/aws-t3/.gitignore b/examples/aws-t3/.gitignore deleted file mode 100644 index 9b3f2f5fbc..0000000000 --- a/examples/aws-t3/.gitignore +++ /dev/null @@ -1,53 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js - -# testing -/coverage - -# database -/prisma/db.sqlite -/prisma/db.sqlite-journal -db.sqlite - -# next.js -/.next/ -/out/ -next-env.d.ts - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* -.pnpm-debug.log* - -# local env files -# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables -.env -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo - -# idea files -.idea - -# sst -.sst - - -# open-next -.open-next diff --git a/examples/aws-t3/drizzle.config.ts b/examples/aws-t3/drizzle.config.ts deleted file mode 100644 index d66cca49e1..0000000000 --- a/examples/aws-t3/drizzle.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Resource } from "sst"; -import { type Config } from "drizzle-kit"; - -export default { - schema: "./src/server/db/schema.ts", - dialect: "postgresql", - dbCredentials: { - ssl: { - rejectUnauthorized: false, - }, - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, - }, - tablesFilter: ["aws-t3_*"], -} satisfies Config; diff --git a/examples/aws-t3/next.config.js b/examples/aws-t3/next.config.js deleted file mode 100644 index 9bfe4a0e2a..0000000000 --- a/examples/aws-t3/next.config.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful - * for Docker builds. - */ -await import("./src/env.js"); - -/** @type {import("next").NextConfig} */ -const config = {}; - -export default config; diff --git a/examples/aws-t3/package.json b/examples/aws-t3/package.json deleted file mode 100644 index 101bfcffd5..0000000000 --- a/examples/aws-t3/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "aws-t3", - "version": "0.1.0", - "private": true, - "type": "module", - "scripts": { - "build": "next build", - "db:generate": "sst shell drizzle-kit generate", - "db:migrate": "sst shell drizzle-kit migrate", - "db:push": "sst shell drizzle-kit push", - "db:studio": "sst shell drizzle-kit studio", - "dev": "next dev", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "@t3-oss/env-nextjs": "^0.10.1", - "@tanstack/react-query": "^5.50.0", - "@trpc/client": "^11.0.0-rc.446", - "@trpc/react-query": "^11.0.0-rc.446", - "@trpc/server": "^11.0.0-rc.446", - "drizzle-orm": "^0.35.1", - "geist": "^1.3.0", - "next": "^14.2.4", - "pg": "^8.13.1", - "postgres": "^3.4.4", - "react": "^18.3.1", - "react-dom": "^18.3.1", - "server-only": "^0.0.1", - "sst": "file:../../sdk/js", - "superjson": "^2.2.1", - "zod": "^3.23.3" - }, - "devDependencies": { - "@types/eslint": "^8.56.10", - "@types/node": "^20.14.10", - "@types/pg": "^8.11.10", - "@types/react": "^18.3.3", - "@types/react-dom": "^18.3.0", - "@typescript-eslint/eslint-plugin": "^8.1.0", - "@typescript-eslint/parser": "^8.1.0", - "drizzle-kit": "^0.26.2", - "eslint": "^8.57.0", - "eslint-config-next": "^14.2.4", - "eslint-plugin-drizzle": "^0.2.3", - "postcss": "^8.4.39", - "prettier": "^3.3.2", - "prettier-plugin-tailwindcss": "^0.6.5", - "tailwindcss": "^3.4.3", - "typescript": "^5.5.3" - }, - "ct3aMetadata": { - "initVersion": "7.37.0" - }, - "packageManager": "npm@10.2.4" -} diff --git a/examples/aws-t3/postcss.config.cjs b/examples/aws-t3/postcss.config.cjs deleted file mode 100644 index 4cdb2f430f..0000000000 --- a/examples/aws-t3/postcss.config.cjs +++ /dev/null @@ -1,7 +0,0 @@ -const config = { - plugins: { - tailwindcss: {}, - }, -}; - -module.exports = config; diff --git a/examples/aws-t3/prettier.config.js b/examples/aws-t3/prettier.config.js deleted file mode 100644 index b2d59b460f..0000000000 --- a/examples/aws-t3/prettier.config.js +++ /dev/null @@ -1,6 +0,0 @@ -/** @type {import('prettier').Config & import('prettier-plugin-tailwindcss').PluginOptions} */ -const config = { - plugins: ["prettier-plugin-tailwindcss"], -}; - -export default config; diff --git a/examples/aws-t3/public/favicon.ico b/examples/aws-t3/public/favicon.ico deleted file mode 100644 index 60c702aac1..0000000000 Binary files a/examples/aws-t3/public/favicon.ico and /dev/null differ diff --git a/examples/aws-t3/src/app/_components/post.tsx b/examples/aws-t3/src/app/_components/post.tsx deleted file mode 100644 index ebe15eab4a..0000000000 --- a/examples/aws-t3/src/app/_components/post.tsx +++ /dev/null @@ -1,50 +0,0 @@ -"use client"; - -import { useState } from "react"; - -import { api } from "~/trpc/react"; - -export function LatestPost() { - const [latestPost] = api.post.getLatest.useSuspenseQuery(); - - const utils = api.useUtils(); - const [name, setName] = useState(""); - const createPost = api.post.create.useMutation({ - onSuccess: async () => { - await utils.post.invalidate(); - setName(""); - }, - }); - - return ( -
- {latestPost ? ( -

Your most recent post: {latestPost.name}

- ) : ( -

You have no posts yet.

- )} -
{ - e.preventDefault(); - createPost.mutate({ name }); - }} - className="flex flex-col gap-2" - > - setName(e.target.value)} - className="w-full rounded-full px-4 py-2 text-black" - /> - -
-
- ); -} diff --git a/examples/aws-t3/src/app/api/trpc/[trpc]/route.ts b/examples/aws-t3/src/app/api/trpc/[trpc]/route.ts deleted file mode 100644 index 5fbd827d90..0000000000 --- a/examples/aws-t3/src/app/api/trpc/[trpc]/route.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; -import { type NextRequest } from "next/server"; - -import { env } from "~/env"; -import { appRouter } from "~/server/api/root"; -import { createTRPCContext } from "~/server/api/trpc"; - -/** - * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when - * handling a HTTP request (e.g. when you make requests from Client Components). - */ -const createContext = async (req: NextRequest) => { - return createTRPCContext({ - headers: req.headers, - }); -}; - -const handler = (req: NextRequest) => - fetchRequestHandler({ - endpoint: "/api/trpc", - req, - router: appRouter, - createContext: () => createContext(req), - onError: - env.NODE_ENV === "development" - ? ({ path, error }) => { - console.error( - `❌ tRPC failed on ${path ?? ""}: ${error.message}` - ); - } - : undefined, - }); - -export { handler as GET, handler as POST }; diff --git a/examples/aws-t3/src/app/layout.tsx b/examples/aws-t3/src/app/layout.tsx deleted file mode 100644 index c2215fff12..0000000000 --- a/examples/aws-t3/src/app/layout.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import "~/styles/globals.css"; - -import { GeistSans } from "geist/font/sans"; -import { type Metadata } from "next"; - -import { TRPCReactProvider } from "~/trpc/react"; - -export const metadata: Metadata = { - title: "Create T3 App", - description: "Generated by create-t3-app", - icons: [{ rel: "icon", url: "/favicon.ico" }], -}; - -export default function RootLayout({ - children, -}: Readonly<{ children: React.ReactNode }>) { - return ( - - - {children} - - - ); -} diff --git a/examples/aws-t3/src/app/page.tsx b/examples/aws-t3/src/app/page.tsx deleted file mode 100644 index d7121d83d6..0000000000 --- a/examples/aws-t3/src/app/page.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import Link from "next/link"; - -import { LatestPost } from "~/app/_components/post"; -import { api, HydrateClient } from "~/trpc/server"; - -export default async function Home() { - const hello = await api.post.hello({ text: "from tRPC" }); - - void api.post.getLatest.prefetch(); - - return ( - -
-
-

- Create T3 App -

-
- -

First Steps →

-
- Just the basics - Everything you need to know to set up your - database and authentication. -
- - -

Documentation →

-
- Learn more about Create T3 App, the libraries it uses, and how - to deploy it. -
- -
-
-

- {hello ? hello.greeting : "Loading tRPC query..."} -

-
- - -
-
-
- ); -} diff --git a/examples/aws-t3/src/env.js b/examples/aws-t3/src/env.js deleted file mode 100644 index c884758c63..0000000000 --- a/examples/aws-t3/src/env.js +++ /dev/null @@ -1,44 +0,0 @@ -import { createEnv } from "@t3-oss/env-nextjs"; -import { z } from "zod"; - -export const env = createEnv({ - /** - * Specify your server-side environment variables schema here. This way you can ensure the app - * isn't built with invalid env vars. - */ - server: { - // DATABASE_URL: z.string().url(), - NODE_ENV: z - .enum(["development", "test", "production"]) - .default("development"), - }, - - /** - * Specify your client-side environment variables schema here. This way you can ensure the app - * isn't built with invalid env vars. To expose them to the client, prefix them with - * `NEXT_PUBLIC_`. - */ - client: { - // NEXT_PUBLIC_CLIENTVAR: z.string(), - }, - - /** - * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. - * middlewares) or client-side so we need to destruct manually. - */ - runtimeEnv: { - // DATABASE_URL: process.env.DATABASE_URL, - NODE_ENV: process.env.NODE_ENV, - // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, - }, - /** - * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially - * useful for Docker builds. - */ - skipValidation: !!process.env.SKIP_ENV_VALIDATION, - /** - * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and - * `SOME_VAR=''` will throw an error. - */ - emptyStringAsUndefined: true, -}); diff --git a/examples/aws-t3/src/server/api/root.ts b/examples/aws-t3/src/server/api/root.ts deleted file mode 100644 index b341fc4d64..0000000000 --- a/examples/aws-t3/src/server/api/root.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { postRouter } from "~/server/api/routers/post"; -import { createCallerFactory, createTRPCRouter } from "~/server/api/trpc"; - -/** - * This is the primary router for your server. - * - * All routers added in /api/routers should be manually added here. - */ -export const appRouter = createTRPCRouter({ - post: postRouter, -}); - -// export type definition of API -export type AppRouter = typeof appRouter; - -/** - * Create a server-side caller for the tRPC API. - * @example - * const trpc = createCaller(createContext); - * const res = await trpc.post.all(); - * ^? Post[] - */ -export const createCaller = createCallerFactory(appRouter); diff --git a/examples/aws-t3/src/server/api/routers/post.ts b/examples/aws-t3/src/server/api/routers/post.ts deleted file mode 100644 index 4bbf615b31..0000000000 --- a/examples/aws-t3/src/server/api/routers/post.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { z } from "zod"; - -import { createTRPCRouter, publicProcedure } from "~/server/api/trpc"; -import { posts } from "~/server/db/schema"; - -export const postRouter = createTRPCRouter({ - hello: publicProcedure - .input(z.object({ text: z.string() })) - .query(({ input }) => { - return { - greeting: `Hello ${input.text}`, - }; - }), - - create: publicProcedure - .input(z.object({ name: z.string().min(1) })) - .mutation(async ({ ctx, input }) => { - await ctx.db.insert(posts).values({ - name: input.name, - }); - }), - - getLatest: publicProcedure.query(async ({ ctx }) => { - const post = await ctx.db.query.posts.findFirst({ - orderBy: (posts, { desc }) => [desc(posts.createdAt)], - }); - - return post ?? null; - }), -}); diff --git a/examples/aws-t3/src/server/api/trpc.ts b/examples/aws-t3/src/server/api/trpc.ts deleted file mode 100644 index 4e24ba4373..0000000000 --- a/examples/aws-t3/src/server/api/trpc.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: - * 1. You want to modify request context (see Part 1). - * 2. You want to create a new middleware or type of procedure (see Part 3). - * - * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will - * need to use are documented accordingly near the end. - */ -import { initTRPC } from "@trpc/server"; -import superjson from "superjson"; -import { ZodError } from "zod"; - -import { db } from "~/server/db"; - -/** - * 1. CONTEXT - * - * This section defines the "contexts" that are available in the backend API. - * - * These allow you to access things when processing a request, like the database, the session, etc. - * - * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each - * wrap this and provides the required context. - * - * @see https://trpc.io/docs/server/context - */ -export const createTRPCContext = async (opts: { headers: Headers }) => { - return { - db, - ...opts, - }; -}; - -/** - * 2. INITIALIZATION - * - * This is where the tRPC API is initialized, connecting the context and transformer. We also parse - * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation - * errors on the backend. - */ -const t = initTRPC.context().create({ - transformer: superjson, - errorFormatter({ shape, error }) { - return { - ...shape, - data: { - ...shape.data, - zodError: - error.cause instanceof ZodError ? error.cause.flatten() : null, - }, - }; - }, -}); - -/** - * Create a server-side caller. - * - * @see https://trpc.io/docs/server/server-side-calls - */ -export const createCallerFactory = t.createCallerFactory; - -/** - * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) - * - * These are the pieces you use to build your tRPC API. You should import these a lot in the - * "/src/server/api/routers" directory. - */ - -/** - * This is how you create new routers and sub-routers in your tRPC API. - * - * @see https://trpc.io/docs/router - */ -export const createTRPCRouter = t.router; - -/** - * Middleware for timing procedure execution and adding an artificial delay in development. - * - * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating - * network latency that would occur in production but not in local development. - */ -const timingMiddleware = t.middleware(async ({ next, path }) => { - const start = Date.now(); - - if (t._config.isDev) { - // artificial delay in dev - const waitMs = Math.floor(Math.random() * 400) + 100; - await new Promise((resolve) => setTimeout(resolve, waitMs)); - } - - const result = await next(); - - const end = Date.now(); - console.log(`[TRPC] ${path} took ${end - start}ms to execute`); - - return result; -}); - -/** - * Public (unauthenticated) procedure - * - * This is the base piece you use to build new queries and mutations on your tRPC API. It does not - * guarantee that a user querying is authorized, but you can still access user session data if they - * are logged in. - */ -export const publicProcedure = t.procedure.use(timingMiddleware); diff --git a/examples/aws-t3/src/server/db/index.ts b/examples/aws-t3/src/server/db/index.ts deleted file mode 100644 index 580dbfc0ff..0000000000 --- a/examples/aws-t3/src/server/db/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Pool } from "pg"; -import { Resource } from "sst"; -import { drizzle } from "drizzle-orm/node-postgres"; - -import * as schema from "./schema"; - -const pool = new Pool({ - host: Resource.MyPostgres.host, - port: Resource.MyPostgres.port, - user: Resource.MyPostgres.username, - password: Resource.MyPostgres.password, - database: Resource.MyPostgres.database, -}); - -export const db = drizzle(pool, { schema }); diff --git a/examples/aws-t3/src/server/db/schema.ts b/examples/aws-t3/src/server/db/schema.ts deleted file mode 100644 index 19ffe2a0c7..0000000000 --- a/examples/aws-t3/src/server/db/schema.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Example model schema from the Drizzle docs -// https://orm.drizzle.team/docs/sql-schema-declaration - -import { sql } from "drizzle-orm"; -import { - index, - pgTableCreator, - serial, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; - -/** - * This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same - * database instance for multiple projects. - * - * @see https://orm.drizzle.team/docs/goodies#multi-project-schema - */ -export const createTable = pgTableCreator((name) => `aws-t3_${name}`); - -export const posts = createTable( - "post", - { - id: serial("id").primaryKey(), - name: varchar("name", { length: 256 }), - createdAt: timestamp("created_at", { withTimezone: true }) - .default(sql`CURRENT_TIMESTAMP`) - .notNull(), - updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate( - () => new Date() - ), - }, - (example) => ({ - nameIndex: index("name_idx").on(example.name), - }) -); diff --git a/examples/aws-t3/src/styles/globals.css b/examples/aws-t3/src/styles/globals.css deleted file mode 100644 index b5c61c9567..0000000000 --- a/examples/aws-t3/src/styles/globals.css +++ /dev/null @@ -1,3 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; diff --git a/examples/aws-t3/src/trpc/query-client.ts b/examples/aws-t3/src/trpc/query-client.ts deleted file mode 100644 index bda64397ca..0000000000 --- a/examples/aws-t3/src/trpc/query-client.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { - defaultShouldDehydrateQuery, - QueryClient, -} from "@tanstack/react-query"; -import SuperJSON from "superjson"; - -export const createQueryClient = () => - new QueryClient({ - defaultOptions: { - queries: { - // With SSR, we usually want to set some default staleTime - // above 0 to avoid refetching immediately on the client - staleTime: 30 * 1000, - }, - dehydrate: { - serializeData: SuperJSON.serialize, - shouldDehydrateQuery: (query) => - defaultShouldDehydrateQuery(query) || - query.state.status === "pending", - }, - hydrate: { - deserializeData: SuperJSON.deserialize, - }, - }, - }); diff --git a/examples/aws-t3/src/trpc/react.tsx b/examples/aws-t3/src/trpc/react.tsx deleted file mode 100644 index 8c0521a74e..0000000000 --- a/examples/aws-t3/src/trpc/react.tsx +++ /dev/null @@ -1,76 +0,0 @@ -"use client"; - -import { QueryClientProvider, type QueryClient } from "@tanstack/react-query"; -import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client"; -import { createTRPCReact } from "@trpc/react-query"; -import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; -import { useState } from "react"; -import SuperJSON from "superjson"; - -import { type AppRouter } from "~/server/api/root"; -import { createQueryClient } from "./query-client"; - -let clientQueryClientSingleton: QueryClient | undefined = undefined; -const getQueryClient = () => { - if (typeof window === "undefined") { - // Server: always make a new query client - return createQueryClient(); - } - // Browser: use singleton pattern to keep the same query client - return (clientQueryClientSingleton ??= createQueryClient()); -}; - -export const api = createTRPCReact(); - -/** - * Inference helper for inputs. - * - * @example type HelloInput = RouterInputs['example']['hello'] - */ -export type RouterInputs = inferRouterInputs; - -/** - * Inference helper for outputs. - * - * @example type HelloOutput = RouterOutputs['example']['hello'] - */ -export type RouterOutputs = inferRouterOutputs; - -export function TRPCReactProvider(props: { children: React.ReactNode }) { - const queryClient = getQueryClient(); - - const [trpcClient] = useState(() => - api.createClient({ - links: [ - loggerLink({ - enabled: (op) => - process.env.NODE_ENV === "development" || - (op.direction === "down" && op.result instanceof Error), - }), - unstable_httpBatchStreamLink({ - transformer: SuperJSON, - url: getBaseUrl() + "/api/trpc", - headers: () => { - const headers = new Headers(); - headers.set("x-trpc-source", "nextjs-react"); - return headers; - }, - }), - ], - }) - ); - - return ( - - - {props.children} - - - ); -} - -function getBaseUrl() { - if (typeof window !== "undefined") return window.location.origin; - if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; - return `http://localhost:${process.env.PORT ?? 3000}`; -} diff --git a/examples/aws-t3/src/trpc/server.ts b/examples/aws-t3/src/trpc/server.ts deleted file mode 100644 index 59300a638b..0000000000 --- a/examples/aws-t3/src/trpc/server.ts +++ /dev/null @@ -1,30 +0,0 @@ -import "server-only"; - -import { createHydrationHelpers } from "@trpc/react-query/rsc"; -import { headers } from "next/headers"; -import { cache } from "react"; - -import { createCaller, type AppRouter } from "~/server/api/root"; -import { createTRPCContext } from "~/server/api/trpc"; -import { createQueryClient } from "./query-client"; - -/** - * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when - * handling a tRPC call from a React Server Component. - */ -const createContext = cache(() => { - const heads = new Headers(headers()); - heads.set("x-trpc-source", "rsc"); - - return createTRPCContext({ - headers: heads, - }); -}); - -const getQueryClient = cache(createQueryClient); -const caller = createCaller(createContext); - -export const { trpc: api, HydrateClient } = createHydrationHelpers( - caller, - getQueryClient -); diff --git a/examples/aws-t3/sst.config.ts b/examples/aws-t3/sst.config.ts deleted file mode 100644 index 240886315c..0000000000 --- a/examples/aws-t3/sst.config.ts +++ /dev/null @@ -1,145 +0,0 @@ -/// - -/** - * ## T3 Stack in AWS - * - * Deploy [T3 stack](https://create.t3.gg) with Drizzle and Postgres to AWS. - * - * This example was created using `create-t3-app` and the following options: tRPC, Drizzle, - * no auth, Tailwind, Postgres, and the App Router. - * - * Instead of a local database, we'll be using an RDS Postgres database. - * - * ```ts title="src/server/db/index.ts" {2-6} - * const pool = new Pool({ - * host: Resource.MyPostgres.host, - * port: Resource.MyPostgres.port, - * user: Resource.MyPostgres.username, - * password: Resource.MyPostgres.password, - * database: Resource.MyPostgres.database, - * }); - * ``` - * - * Similarly, for Drizzle Kit. - * - * ```ts title="drizzle.config.ts" {8-12} - * export default { - * schema: "./src/server/db/schema.ts", - * dialect: "postgresql", - * dbCredentials: { - * ssl: { - * rejectUnauthorized: false, - * }, - * host: Resource.MyPostgres.host, - * port: Resource.MyPostgres.port, - * user: Resource.MyPostgres.username, - * password: Resource.MyPostgres.password, - * database: Resource.MyPostgres.database, - * }, - * tablesFilter: ["aws-t3_*"], - * } satisfies Config; - * ``` - * - * In our Next.js app we can access our Postgres database because we [link them](/docs/linking/) - * both. We don't need to use our `.env` files. - * - * ```ts title="sst.config.ts" {5} - * const rds = new sst.aws.Postgres("MyPostgres", { vpc, proxy: true }); - * - * new sst.aws.Nextjs("MyWeb", { - * vpc, - * link: [rds] - * }); - * ``` - * - * To run this in dev mode run: - * - * ```bash - * npm install - * npx sst dev - * ``` - * - * It'll take a few minutes to deploy the database and the VPC. - * - * This also starts a tunnel to let your local machine connect to the RDS Postgres database. - * Make sure you have it installed, you only need to do this once for your local machine. - * - * ```bash - * sudo npx sst tunnel install - * ``` - * - * Now in a new terminal you can run the database migrations. - * - * ```bash - * npm run db:push - * ``` - * - * We also have the Drizzle Studio start automatically in dev mode under the **Studio** tab. - * - * ```ts title="sst.config.ts" - * new sst.x.DevCommand("Studio", { - * link: [rds], - * dev: { - * command: "npx drizzle-kit studio", - * }, - * }); - * ``` - * - * And to make sure our credentials are available, we update our `package.json` - * with the [`sst shell`](/docs/reference/cli) CLI. - * - * ```json title="package.json" - * "db:generate": "sst shell drizzle-kit generate", - * "db:migrate": "sst shell drizzle-kit migrate", - * "db:push": "sst shell drizzle-kit push", - * "db:studio": "sst shell drizzle-kit studio", - * ``` - * - * So running `npm run db:push` will run Drizzle Kit with the right credentials. - * - * To deploy this to production run: - * - * ```bash - * npx sst deploy --stage production - * ``` - * - * Then run the migrations. - * - * ```bash - * npx sst shell --stage production npx drizzle-kit push - * ``` - * - * If you are running this locally, you'll need to have a tunnel running. - * - * ```bash - * npx sst tunnel --stage production - * ``` - * - * If you are doing this in a CI/CD pipeline, you'd want your build containers to be in the - * same VPC. - */ -export default $config({ - app(input) { - return { - name: "aws-t3", - removal: input?.stage === "production" ? "retain" : "remove", - home: "aws", - }; - }, - async run() { - const vpc = new sst.aws.Vpc("MyVpc", { bastion: true, nat: "ec2" }); - const rds = new sst.aws.Postgres("MyPostgres", { vpc, proxy: true }); - - new sst.aws.Nextjs("MyWeb", { - vpc, - link: [rds] - }); - - new sst.x.DevCommand("Studio", { - link: [rds], - dev: { - command: "npx drizzle-kit studio", - }, - }); - }, -}); diff --git a/examples/aws-t3/start-database.sh b/examples/aws-t3/start-database.sh deleted file mode 100755 index 610f54b3f5..0000000000 --- a/examples/aws-t3/start-database.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -# Use this script to start a docker container for a local development database - -# TO RUN ON WINDOWS: -# 1. Install WSL (Windows Subsystem for Linux) - https://learn.microsoft.com/en-us/windows/wsl/install -# 2. Install Docker Desktop for Windows - https://docs.docker.com/docker-for-windows/install/ -# 3. Open WSL - `wsl` -# 4. Run this script - `./start-database.sh` - -# On Linux and macOS you can run this script directly - `./start-database.sh` - -DB_CONTAINER_NAME="aws-t3-postgres" - -if ! [ -x "$(command -v docker)" ]; then - echo -e "Docker is not installed. Please install docker and try again.\nDocker install guide: https://docs.docker.com/engine/install/" - exit 1 -fi - -if [ "$(docker ps -q -f name=$DB_CONTAINER_NAME)" ]; then - echo "Database container '$DB_CONTAINER_NAME' already running" - exit 0 -fi - -if [ "$(docker ps -q -a -f name=$DB_CONTAINER_NAME)" ]; then - docker start "$DB_CONTAINER_NAME" - echo "Existing database container '$DB_CONTAINER_NAME' started" - exit 0 -fi - -# import env variables from .env -set -a -source .env - -DB_PASSWORD=$(echo "$DATABASE_URL" | awk -F':' '{print $3}' | awk -F'@' '{print $1}') -DB_PORT=$(echo "$DATABASE_URL" | awk -F':' '{print $4}' | awk -F'\/' '{print $1}') - -if [ "$DB_PASSWORD" = "password" ]; then - echo "You are using the default database password" - read -p "Should we generate a random password for you? [y/N]: " -r REPLY - if ! [[ $REPLY =~ ^[Yy]$ ]]; then - echo "Please change the default password in the .env file and try again" - exit 1 - fi - # Generate a random URL-safe password - DB_PASSWORD=$(openssl rand -base64 12 | tr '+/' '-_') - sed -i -e "s#:password@#:$DB_PASSWORD@#" .env -fi - -docker run -d \ - --name $DB_CONTAINER_NAME \ - -e POSTGRES_USER="postgres" \ - -e POSTGRES_PASSWORD="$DB_PASSWORD" \ - -e POSTGRES_DB=aws-t3 \ - -p "$DB_PORT":5432 \ - docker.io/postgres && echo "Database container '$DB_CONTAINER_NAME' was successfully created" diff --git a/examples/aws-t3/tailwind.config.ts b/examples/aws-t3/tailwind.config.ts deleted file mode 100644 index 5fd44e8f23..0000000000 --- a/examples/aws-t3/tailwind.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { type Config } from "tailwindcss"; -import { fontFamily } from "tailwindcss/defaultTheme"; - -export default { - content: ["./src/**/*.tsx"], - theme: { - extend: { - fontFamily: { - sans: ["var(--font-geist-sans)", ...fontFamily.sans], - }, - }, - }, - plugins: [], -} satisfies Config; diff --git a/examples/aws-t3/tsconfig.json b/examples/aws-t3/tsconfig.json deleted file mode 100644 index ba905904d9..0000000000 --- a/examples/aws-t3/tsconfig.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "compilerOptions": { - /* Base Options: */ - "esModuleInterop": true, - "skipLibCheck": true, - "target": "es2022", - "allowJs": true, - "resolveJsonModule": true, - "moduleDetection": "force", - "isolatedModules": true, - - /* Strictness */ - "strict": true, - "noUncheckedIndexedAccess": true, - "checkJs": true, - - /* Bundled projects */ - "lib": ["dom", "dom.iterable", "ES2022"], - "noEmit": true, - "module": "ESNext", - "moduleResolution": "Bundler", - "jsx": "preserve", - "plugins": [{ "name": "next" }], - "incremental": true, - - /* Path Aliases */ - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - } - }, - "include": [ - ".eslintrc.cjs", - "next-env.d.ts", - "**/*.ts", - "**/*.tsx", - "**/*.cjs", - "**/*.js", - ".next/types/**/*.ts" - ], - "exclude": ["node_modules","sst.config.ts"] -} diff --git a/examples/aws-tanstack-start/.cta.json b/examples/aws-tanstack-start/.cta.json deleted file mode 100644 index 82493fe963..0000000000 --- a/examples/aws-tanstack-start/.cta.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "projectName": "app", - "mode": "file-router", - "typescript": true, - "tailwind": true, - "packageManager": "pnpm", - "addOnOptions": {}, - "git": true, - "version": 1, - "framework": "react-cra", - "chosenAddOns": [ - "eslint", - "nitro", - "start", - "form", - "shadcn", - "tanstack-query" - ] -} \ No newline at end of file diff --git a/examples/aws-tanstack-start/.cursorrules b/examples/aws-tanstack-start/.cursorrules deleted file mode 100644 index 1472639b19..0000000000 --- a/examples/aws-tanstack-start/.cursorrules +++ /dev/null @@ -1,7 +0,0 @@ -# shadcn instructions - -Use the latest version of Shadcn to install new components, like this command to add a button component: - -```bash -pnpx shadcn@latest add button -``` diff --git a/examples/aws-tanstack-start/.gitignore b/examples/aws-tanstack-start/.gitignore deleted file mode 100644 index b4687f1d19..0000000000 --- a/examples/aws-tanstack-start/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -.sst -node_modules -.DS_Store -dist -dist-ssr -*.local -count.txt -.env -.nitro -.tanstack -.wrangler -.output -.vinxi -todos.json diff --git a/examples/aws-tanstack-start/.prettierignore b/examples/aws-tanstack-start/.prettierignore deleted file mode 100644 index 5322d7feea..0000000000 --- a/examples/aws-tanstack-start/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -package-lock.json -pnpm-lock.yaml -yarn.lock \ No newline at end of file diff --git a/examples/aws-tanstack-start/.vscode/settings.json b/examples/aws-tanstack-start/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/aws-tanstack-start/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/aws-tanstack-start/components.json b/examples/aws-tanstack-start/components.json deleted file mode 100644 index 6998bdfb97..0000000000 --- a/examples/aws-tanstack-start/components.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "new-york", - "rsc": false, - "tsx": true, - "tailwind": { - "config": "", - "css": "src/styles.css", - "baseColor": "zinc", - "cssVariables": true, - "prefix": "" - }, - "aliases": { - "components": "@/components", - "utils": "@/lib/utils", - "ui": "@/components/ui", - "lib": "@/lib", - "hooks": "@/hooks" - }, - "iconLibrary": "lucide" -} \ No newline at end of file diff --git a/examples/aws-tanstack-start/eslint.config.js b/examples/aws-tanstack-start/eslint.config.js deleted file mode 100644 index 676b32a87f..0000000000 --- a/examples/aws-tanstack-start/eslint.config.js +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import { tanstackConfig } from '@tanstack/eslint-config' - -export default [...tanstackConfig] diff --git a/examples/aws-tanstack-start/package.json b/examples/aws-tanstack-start/package.json deleted file mode 100644 index 854758a5ea..0000000000 --- a/examples/aws-tanstack-start/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "aws-tanstack-start", - "private": true, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "build": "vite build", - "serve": "vite preview", - "test": "vitest run", - "lint": "eslint", - "format": "prettier", - "check": "prettier --write . && eslint --fix" - }, - "dependencies": { - "@radix-ui/react-label": "^2.1.8", - "@radix-ui/react-select": "^2.2.6", - "@radix-ui/react-slider": "^1.3.6", - "@radix-ui/react-slot": "^1.2.4", - "@radix-ui/react-switch": "^1.2.6", - "@tailwindcss/vite": "^4.0.6", - "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-form": "^1.0.0", - "@tanstack/react-query": "^5.66.5", - "@tanstack/react-query-devtools": "^5.84.2", - "@tanstack/react-router": "^1.132.0", - "@tanstack/react-router-devtools": "^1.132.0", - "@tanstack/react-router-ssr-query": "^1.131.7", - "@tanstack/react-start": "^1.132.0", - "@tanstack/router-plugin": "^1.132.0", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "lucide-react": "^0.544.0", - "nitro": "latest", - "react": "^19.2.0", - "react-dom": "^19.2.0", - "sst": "file:../../sdk/js", - "tailwind-merge": "^3.0.2", - "tailwindcss": "^4.0.6", - "tw-animate-css": "^1.3.6", - "vite-tsconfig-paths": "^5.1.4", - "zod": "^4.1.11" - }, - "devDependencies": { - "@tanstack/devtools-vite": "^0.3.11", - "@tanstack/eslint-config": "^0.3.0", - "@testing-library/dom": "^10.4.0", - "@testing-library/react": "^16.2.0", - "@types/node": "^22.10.2", - "@types/react": "^19.2.0", - "@types/react-dom": "^19.2.0", - "@vitejs/plugin-react": "^5.0.4", - "jsdom": "^27.0.0", - "prettier": "^3.5.3", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vitest": "^3.0.5", - "web-vitals": "^5.1.0" - } -} \ No newline at end of file diff --git a/examples/aws-tanstack-start/prettier.config.js b/examples/aws-tanstack-start/prettier.config.js deleted file mode 100644 index aea1c4804b..0000000000 --- a/examples/aws-tanstack-start/prettier.config.js +++ /dev/null @@ -1,10 +0,0 @@ -// @ts-check - -/** @type {import('prettier').Config} */ -const config = { - semi: false, - singleQuote: true, - trailingComma: "all", -}; - -export default config; diff --git a/examples/aws-tanstack-start/public/manifest.json b/examples/aws-tanstack-start/public/manifest.json deleted file mode 100644 index 078ef50116..0000000000 --- a/examples/aws-tanstack-start/public/manifest.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "short_name": "TanStack App", - "name": "Create TanStack App Sample", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - }, - { - "src": "logo192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "logo512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff" -} diff --git a/examples/aws-tanstack-start/public/tanstack-circle-logo.png b/examples/aws-tanstack-start/public/tanstack-circle-logo.png deleted file mode 100644 index 9db3e67bad..0000000000 Binary files a/examples/aws-tanstack-start/public/tanstack-circle-logo.png and /dev/null differ diff --git a/examples/aws-tanstack-start/public/tanstack-word-logo-white.svg b/examples/aws-tanstack-start/public/tanstack-word-logo-white.svg deleted file mode 100644 index b6ec5086c2..0000000000 --- a/examples/aws-tanstack-start/public/tanstack-word-logo-white.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/examples/aws-tanstack-start/src/components/Header.tsx b/examples/aws-tanstack-start/src/components/Header.tsx deleted file mode 100644 index b6e0cd0d4f..0000000000 --- a/examples/aws-tanstack-start/src/components/Header.tsx +++ /dev/null @@ -1,217 +0,0 @@ -import { Link } from '@tanstack/react-router' - -import { useState } from 'react' -import { - ChevronDown, - ChevronRight, - ClipboardType, - Home, - Menu, - Network, - SquareFunction, - StickyNote, - X, -} from 'lucide-react' - -export default function Header() { - const [isOpen, setIsOpen] = useState(false) - const [groupedExpanded, setGroupedExpanded] = useState< - Record - >({}) - - return ( - <> -
- -

- - TanStack Logo - -

-
- - - - ) -} diff --git a/examples/aws-tanstack-start/src/components/demo.FormComponents.tsx b/examples/aws-tanstack-start/src/components/demo.FormComponents.tsx deleted file mode 100644 index 0419620dff..0000000000 --- a/examples/aws-tanstack-start/src/components/demo.FormComponents.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import { useStore } from '@tanstack/react-form' - -import { useFieldContext, useFormContext } from '@/hooks/demo.form-context' - -import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' -import { Textarea as ShadcnTextarea } from '@/components/ui/textarea' -import * as ShadcnSelect from '@/components/ui/select' -import { Slider as ShadcnSlider } from '@/components/ui/slider' -import { Switch as ShadcnSwitch } from '@/components/ui/switch' -import { Label } from '@/components/ui/label' - -export function SubscribeButton({ label }: { label: string }) { - const form = useFormContext() - return ( - state.isSubmitting}> - {(isSubmitting) => ( - - )} - - ) -} - -function ErrorMessages({ - errors, -}: { - errors: Array -}) { - return ( - <> - {errors.map((error) => ( -
- {typeof error === 'string' ? error : error.message} -
- ))} - - ) -} - -export function TextField({ - label, - placeholder, -}: { - label: string - placeholder?: string -}) { - const field = useFieldContext() - const errors = useStore(field.store, (state) => state.meta.errors) - - return ( -
- - field.handleChange(e.target.value)} - /> - {field.state.meta.isTouched && } -
- ) -} - -export function TextArea({ - label, - rows = 3, -}: { - label: string - rows?: number -}) { - const field = useFieldContext() - const errors = useStore(field.store, (state) => state.meta.errors) - - return ( -
- - field.handleChange(e.target.value)} - /> - {field.state.meta.isTouched && } -
- ) -} - -export function Select({ - label, - values, - placeholder, -}: { - label: string - values: Array<{ label: string; value: string }> - placeholder?: string -}) { - const field = useFieldContext() - const errors = useStore(field.store, (state) => state.meta.errors) - - return ( -
- field.handleChange(value)} - > - - - - - - {label} - {values.map((value) => ( - - {value.label} - - ))} - - - - {field.state.meta.isTouched && } -
- ) -} - -export function Slider({ label }: { label: string }) { - const field = useFieldContext() - const errors = useStore(field.store, (state) => state.meta.errors) - - return ( -
- - field.handleChange(value[0])} - /> - {field.state.meta.isTouched && } -
- ) -} - -export function Switch({ label }: { label: string }) { - const field = useFieldContext() - const errors = useStore(field.store, (state) => state.meta.errors) - - return ( -
-
- field.handleChange(checked)} - /> - -
- {field.state.meta.isTouched && } -
- ) -} diff --git a/examples/aws-tanstack-start/src/components/ui/button.tsx b/examples/aws-tanstack-start/src/components/ui/button.tsx deleted file mode 100644 index 21409a0666..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/button.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import * as React from "react" -import { Slot } from "@radix-ui/react-slot" -import { cva, type VariantProps } from "class-variance-authority" - -import { cn } from "@/lib/utils" - -const buttonVariants = cva( - "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", - { - variants: { - variant: { - default: "bg-primary text-primary-foreground hover:bg-primary/90", - destructive: - "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", - outline: - "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", - secondary: - "bg-secondary text-secondary-foreground hover:bg-secondary/80", - ghost: - "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", - link: "text-primary underline-offset-4 hover:underline", - }, - size: { - default: "h-9 px-4 py-2 has-[>svg]:px-3", - sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", - lg: "h-10 rounded-md px-6 has-[>svg]:px-4", - icon: "size-9", - "icon-sm": "size-8", - "icon-lg": "size-10", - }, - }, - defaultVariants: { - variant: "default", - size: "default", - }, - } -) - -function Button({ - className, - variant, - size, - asChild = false, - ...props -}: React.ComponentProps<"button"> & - VariantProps & { - asChild?: boolean - }) { - const Comp = asChild ? Slot : "button" - - return ( - - ) -} - -export { Button, buttonVariants } diff --git a/examples/aws-tanstack-start/src/components/ui/input.tsx b/examples/aws-tanstack-start/src/components/ui/input.tsx deleted file mode 100644 index 89169058d0..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/input.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from "react" - -import { cn } from "@/lib/utils" - -function Input({ className, type, ...props }: React.ComponentProps<"input">) { - return ( - - ) -} - -export { Input } diff --git a/examples/aws-tanstack-start/src/components/ui/label.tsx b/examples/aws-tanstack-start/src/components/ui/label.tsx deleted file mode 100644 index fb5fbc3eee..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/label.tsx +++ /dev/null @@ -1,24 +0,0 @@ -"use client" - -import * as React from "react" -import * as LabelPrimitive from "@radix-ui/react-label" - -import { cn } from "@/lib/utils" - -function Label({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { Label } diff --git a/examples/aws-tanstack-start/src/components/ui/select.tsx b/examples/aws-tanstack-start/src/components/ui/select.tsx deleted file mode 100644 index d34798fafe..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/select.tsx +++ /dev/null @@ -1,185 +0,0 @@ -import * as React from "react" -import * as SelectPrimitive from "@radix-ui/react-select" -import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react" - -import { cn } from "@/lib/utils" - -function Select({ - ...props -}: React.ComponentProps) { - return -} - -function SelectGroup({ - ...props -}: React.ComponentProps) { - return -} - -function SelectValue({ - ...props -}: React.ComponentProps) { - return -} - -function SelectTrigger({ - className, - size = "default", - children, - ...props -}: React.ComponentProps & { - size?: "sm" | "default" -}) { - return ( - - {children} - - - - - ) -} - -function SelectContent({ - className, - children, - position = "popper", - align = "center", - ...props -}: React.ComponentProps) { - return ( - - - - - {children} - - - - - ) -} - -function SelectLabel({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function SelectItem({ - className, - children, - ...props -}: React.ComponentProps) { - return ( - - - - - - - {children} - - ) -} - -function SelectSeparator({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function SelectScrollUpButton({ - className, - ...props -}: React.ComponentProps) { - return ( - - - - ) -} - -function SelectScrollDownButton({ - className, - ...props -}: React.ComponentProps) { - return ( - - - - ) -} - -export { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectLabel, - SelectScrollDownButton, - SelectScrollUpButton, - SelectSeparator, - SelectTrigger, - SelectValue, -} diff --git a/examples/aws-tanstack-start/src/components/ui/slider.tsx b/examples/aws-tanstack-start/src/components/ui/slider.tsx deleted file mode 100644 index 1a1bd735a2..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/slider.tsx +++ /dev/null @@ -1,63 +0,0 @@ -"use client" - -import * as React from "react" -import * as SliderPrimitive from "@radix-ui/react-slider" - -import { cn } from "@/lib/utils" - -function Slider({ - className, - defaultValue, - value, - min = 0, - max = 100, - ...props -}: React.ComponentProps) { - const _values = React.useMemo( - () => - Array.isArray(value) - ? value - : Array.isArray(defaultValue) - ? defaultValue - : [min, max], - [value, defaultValue, min, max] - ) - - return ( - - - - - {Array.from({ length: _values.length }, (_, index) => ( - - ))} - - ) -} - -export { Slider } diff --git a/examples/aws-tanstack-start/src/components/ui/switch.tsx b/examples/aws-tanstack-start/src/components/ui/switch.tsx deleted file mode 100644 index b0363e3f86..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/switch.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import * as React from "react" -import * as SwitchPrimitive from "@radix-ui/react-switch" - -import { cn } from "@/lib/utils" - -function Switch({ - className, - ...props -}: React.ComponentProps) { - return ( - - - - ) -} - -export { Switch } diff --git a/examples/aws-tanstack-start/src/components/ui/textarea.tsx b/examples/aws-tanstack-start/src/components/ui/textarea.tsx deleted file mode 100644 index 7f21b5e78a..0000000000 --- a/examples/aws-tanstack-start/src/components/ui/textarea.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import * as React from "react" - -import { cn } from "@/lib/utils" - -function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { - return ( -