Modelo do encurtador em Express

Gerado a partir de deploy-templates/express (dado.cloud 4c2a882).
This commit is contained in:
dado.cloud
2026-10-21 12:27:02 +00:00
commit c9e3d2ac7f
8 changed files with 1460 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
node_modules/
.env
.DS_Store
+81
View File
@@ -0,0 +1,81 @@
# Encurtador de links em Express
Um encurtador de links pronto para publicar na [Dado](https://dado.cloud): cole um link
comprido, receba um endereço curto e acompanhe quantas vezes ele foi aberto.
Este repositório nasceu de um modelo da Dado. Cada `git push` na branch `main` publica
uma versão nova do seu app, sozinho.
## O que tem aqui
- `server.js`: o servidor — página, API (`POST/GET /api/links`) e o redirecionamento `GET /<código>` (302).
- `links.js`: onde os links ficam guardados (na memória) e a validação dos endereços.
- `paginas/index.html`: a página (HTML, CSS e o JavaScript do formulário). Mude à vontade.
- `paginas/nao-encontrado.html`: a página de link que não existe.
Não tem banco de dados: os links ficam na memória do app e **somem quando ele é publicado
de novo**. Veja no fim como guardar de vez.
## Rodar no seu computador
Precisa de Node.js 20 ou mais novo.
```bash
git clone https://git.dado.cloud/<sua-conta>/encurtador-express.git
cd encurtador-express
npm install
npm run dev
```
Abra http://localhost:3000.
Quando o `git clone` pedir usuário e senha, use o usuário da sua conta de Repositórios e,
como senha, o **token de Repositórios** (no painel da Dado, em Repositórios). O comando
certinho do seu app aparece no painel, em Deploys, na visão geral do app.
## Mudar e publicar
Edite o que quiser e mande para a Dado:
```bash
git add .
git commit -m "Minha primeira mudança"
git push
```
O push na branch `main` publica uma versão nova. Dá para acompanhar o andamento em
Deploys, no painel.
## Variável de ambiente de exemplo
A mensagem em "Sobre este deploy" vem da variável `MENSAGEM_BOAS_VINDAS`. Para trocar,
abra Deploys no painel, clique em "Variáveis de ambiente" no seu app, salve e publique de
novo. No seu computador:
```bash
MENSAGEM_BOAS_VINDAS="Oi, mundo" npm run dev
```
## API
```bash
# Encurtar
curl -X POST https://<endereço-do-seu-app>/api/links \
-H 'Content-Type: application/json' \
-d '{"url": "https://exemplo.com.br/uma-pagina"}'
# 201 {"codigo":"a1b2c3","url":"https://exemplo.com.br/uma-pagina","curto":"https://<endereço-do-seu-app>/a1b2c3","cliques":0,"criadoEm":"..."}
# Últimos 20 links
curl https://<endereço-do-seu-app>/api/links
# 200 {"links":[...]}
```
`GET /<código>` redireciona (302) para o link original e soma um clique. A API aceita
chamadas de qualquer site (CORS aberto só em `/api/*`), então outro app seu pode usá-la.
Para evitar abuso, cada IP cria no máximo 30 links a cada 10 minutos.
## Guardar os links de vez
Para os links sobreviverem a uma nova publicação, ligue um Postgres no app (painel, em
Deploys, aba "Banco de dados" do app). A conexão chega ao app na variável `DATABASE_URL`;
aí é trocar o que está em `links.js` por consultas ao banco.
+69
View File
@@ -0,0 +1,69 @@
import { randomInt } from 'node:crypto';
// Os links ficam num Map na memória do processo: simples e sem banco, mas
// somem toda vez que o app reinicia ou é publicado de novo. Para guardar de
// vez, troque este arquivo por consultas a um Postgres.
const ALFABETO = 'abcdefghijklmnopqrstuvwxyz0123456789';
const TAMANHO_CODIGO = 6;
const TAMANHO_MAXIMO_URL = 2048;
// Teto de links guardados: passou disso, o mais antigo sai (protege a memória).
const MAXIMO_DE_LINKS = 1000;
const LINKS_NA_LISTA = 20;
// Caminhos do próprio app que nunca podem virar código.
const RESERVADOS = new Set(['api']);
export const FORMATO_CODIGO = /^[a-z0-9]{6}$/;
const links = new Map();
export class ErroDeValidacao extends Error {}
function gerarCodigo() {
for (;;) {
let codigo = '';
for (let i = 0; i < TAMANHO_CODIGO; i += 1) codigo += ALFABETO[randomInt(ALFABETO.length)];
if (!links.has(codigo) && !RESERVADOS.has(codigo)) return codigo;
}
}
function validarUrl(valor) {
if (typeof valor !== 'string' || valor.trim() === '') {
throw new ErroDeValidacao('Envie o campo "url" com o link que você quer encurtar.');
}
const texto = valor.trim();
if (texto.length > TAMANHO_MAXIMO_URL) {
throw new ErroDeValidacao(`Esse link é comprido demais (máximo de ${TAMANHO_MAXIMO_URL} caracteres).`);
}
let url;
try {
url = new URL(texto);
} catch {
url = null;
}
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
throw new ErroDeValidacao('Esse não parece um link válido. Use um endereço que comece com http:// ou https://.');
}
return url.href;
}
export function criarLink(valor) {
const url = validarUrl(valor);
const link = { codigo: gerarCodigo(), url, cliques: 0, criadoEm: new Date().toISOString() };
links.set(link.codigo, link);
if (links.size > MAXIMO_DE_LINKS) links.delete(links.keys().next().value);
return link;
}
/** Os últimos links criados, do mais novo para o mais antigo. */
export function listarLinks() {
return [...links.values()].slice(-LINKS_NA_LISTA).reverse();
}
/** Soma um clique e devolve o link, ou null se o código não existe. */
export function registrarClique(codigo) {
const link = links.get(codigo);
if (!link) return null;
link.cliques += 1;
return link;
}
+857
View File
@@ -0,0 +1,857 @@
{
"name": "encurtador-express",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "encurtador-express",
"version": "1.0.0",
"dependencies": {
"express": "5.3.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/accepts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
"integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
"license": "MIT",
"dependencies": {
"mime-types": "^3.0.0",
"negotiator": "^1.0.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/body-parser": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
"integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
"license": "MIT",
"dependencies": {
"bytes": "^3.1.2",
"content-type": "^2.0.0",
"debug": "^4.4.3",
"http-errors": "^2.0.1",
"iconv-lite": "^0.7.2",
"on-finished": "^2.4.1",
"qs": "^6.15.2",
"raw-body": "^3.0.2",
"type-is": "^2.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz",
"integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/content-type": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
"integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
"license": "MIT",
"engines": {
"node": ">=6.6.0"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz",
"integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==",
"license": "MIT",
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.3.0",
"content-disposition": "^2.0.1",
"content-type": "^2.0.0",
"cookie": "^0.7.1",
"cookie-signature": "^1.2.1",
"debug": "^4.4.0",
"depd": "^2.0.0",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"finalhandler": "^2.1.0",
"fresh": "^2.0.0",
"http-errors": "^2.0.0",
"merge-descriptors": "^2.0.0",
"mime-types": "^3.0.0",
"on-finished": "^2.4.1",
"once": "^1.4.0",
"parseurl": "^1.3.3",
"proxy-addr": "^2.0.8",
"qs": "^6.16.0",
"range-parser": "^1.2.1",
"router": "^2.2.0",
"send": "^1.1.0",
"serve-static": "^2.2.0",
"statuses": "^2.0.1",
"type-is": "^2.1.0",
"vary": "^1.1.2"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
"integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"on-finished": "^2.4.1",
"parseurl": "^1.3.3",
"statuses": "^2.0.1"
},
"engines": {
"node": ">= 18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
"integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/is-promise": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz",
"integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/merge-descriptors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
"integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/mime-db": {
"version": "1.54.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
"integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
"integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
"license": "MIT",
"dependencies": {
"mime-db": "^1.54.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz",
"integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==",
"license": "MIT",
"dependencies": {
"content-type": "^2.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
"integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/proxy-addr": {
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/qs": {
"version": "6.16.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz",
"integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
"integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/raw-body": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
"integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.7.0",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/router": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
"integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"depd": "^2.0.0",
"is-promise": "^4.0.0",
"parseurl": "^1.3.3",
"path-to-regexp": "^8.0.0"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
"integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.3",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"fresh": "^2.0.0",
"http-errors": "^2.0.1",
"mime-types": "^3.0.2",
"ms": "^2.1.3",
"on-finished": "^2.4.1",
"range-parser": "^1.2.1",
"statuses": "^2.0.2"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/serve-static": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
"integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
"license": "MIT",
"dependencies": {
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"parseurl": "^1.3.3",
"send": "^1.2.0"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
"integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
"license": "MIT",
"dependencies": {
"content-type": "^2.0.0",
"media-typer": "^1.1.0",
"mime-types": "^3.0.0"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "encurtador-express",
"version": "1.0.0",
"private": true,
"description": "Encurtador de links em Express, pronto para publicar na Dado.",
"type": "module",
"main": "server.js",
"scripts": {
"dev": "node --watch server.js",
"start": "node server.js"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"express": "5.3.0"
}
}
+278
View File
@@ -0,0 +1,278 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Encurtador de links</title>
<meta name="description" content="Encurte links e acompanhe quantas vezes cada um foi aberto." />
<link
rel="icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%233b5bdb'/%3E%3Cpath d='M13.5 18.5l5-5M12 15l-2 2a3.5 3.5 0 005 5l2-2M20 17l2-2a3.5 3.5 0 00-5-5l-2 2' stroke='white' stroke-width='2.2' fill='none' stroke-linecap='round'/%3E%3C/svg%3E"
/>
<style>
/* Mesmo visual nos modelos Next.js, Express e FastAPI. Mude à vontade. */
:root {
--fundo: #f6f7f9;
--cartao: #ffffff;
--texto: #14161a;
--suave: #5b6270;
--borda: #e3e6eb;
--destaque: #3b5bdb;
--destaque-texto: #ffffff;
--destaque-suave: #edf1ff;
--erro: #c92a2a;
--raio: 14px;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--fundo: #0f1115;
--cartao: #171a21;
--texto: #eceef2;
--suave: #9aa1ad;
--borda: #2a2f3a;
--destaque: #8299ff;
--destaque-texto: #0f1115;
--destaque-suave: #1e2540;
--erro: #ff8787;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: var(--fundo);
color: var(--texto);
line-height: 1.5;
-webkit-text-size-adjust: 100%;
}
.pagina { max-width: 640px; margin: 0 auto; padding: 56px 16px 32px; }
.topo { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
.marca {
flex: none; width: 40px; height: 40px; border-radius: 10px;
background: var(--destaque); color: var(--destaque-texto);
display: grid; place-items: center;
}
h1 { font-size: 28px; line-height: 1.2; margin: 0; letter-spacing: -0.02em; }
h2 { font-size: 16px; margin: 32px 0 12px; }
.lead { color: var(--suave); margin: 0 0 24px; }
.cartao { background: var(--cartao); border: 1px solid var(--borda); border-radius: var(--raio); padding: 20px; }
.formulario { display: flex; gap: 8px; }
.formulario input {
flex: 1; min-width: 0; font: inherit; padding: 12px 14px;
border: 1px solid var(--borda); border-radius: 10px;
background: var(--fundo); color: var(--texto);
}
.formulario input:focus { outline: 2px solid var(--destaque); outline-offset: 1px; }
button {
font: inherit; font-weight: 600; padding: 12px 20px; border: 0; border-radius: 10px;
background: var(--destaque); color: var(--destaque-texto); cursor: pointer; white-space: nowrap;
}
button:disabled { opacity: 0.6; cursor: progress; }
button:focus-visible, a:focus-visible { outline: 2px solid var(--destaque); outline-offset: 2px; }
.secundario { background: var(--cartao); color: var(--destaque); border: 1px solid var(--borda); padding: 8px 14px; }
.erro { color: var(--erro); margin: 10px 0 0; font-size: 14px; }
.resultado {
margin-top: 16px; display: flex; align-items: center; gap: 12px;
padding: 12px 14px; border-radius: 10px; background: var(--destaque-suave);
}
.resultado a {
flex: 1; min-width: 0; font-family: var(--mono); font-weight: 600;
color: var(--destaque); text-decoration: none; overflow-wrap: anywhere;
}
.lista { list-style: none; margin: 0; padding: 0; }
.lista li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-top: 1px solid var(--borda); }
.lista li:first-child { border-top: 0; padding-top: 0; }
.lista li:last-child { padding-bottom: 0; }
.link-info { flex: 1; min-width: 0; }
.link-info a { font-family: var(--mono); font-weight: 600; color: var(--texto); text-decoration: none; overflow-wrap: anywhere; }
.link-info a:hover { color: var(--destaque); }
.destino { display: block; color: var(--suave); font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cliques { font-family: var(--mono); font-size: 14px; color: var(--suave); white-space: nowrap; }
.vazio { color: var(--suave); margin: 0; }
.aviso {
margin: 16px 0 0; font-size: 14px; color: var(--suave);
border: 1px dashed var(--borda); border-radius: var(--raio); padding: 14px 16px;
}
.aviso a { color: var(--destaque); font-weight: 600; }
.sobre { margin-top: 32px; }
.sobre h2 { margin-top: 0; }
.sobre dl { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; font-size: 14px; }
.sobre dt { color: var(--suave); }
.sobre dd { margin: 0; overflow-wrap: anywhere; }
.dica { font-size: 13px; color: var(--suave); margin: 14px 0 0; }
code { font-family: var(--mono); font-size: 0.92em; }
.rodape { margin-top: 32px; text-align: center; font-size: 13px; color: var(--suave); }
.rodape a { color: inherit; }
.so-leitor {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
@media (max-width: 480px) {
.pagina { padding-top: 32px; }
h1 { font-size: 24px; }
.formulario { flex-direction: column; }
.resultado { flex-direction: column; align-items: stretch; }
.sobre dl { grid-template-columns: 1fr; gap: 0; }
.sobre dd { margin-bottom: 8px; }
}
</style>
</head>
<body>
<main class="pagina">
<header class="topo">
<span class="marca" aria-hidden="true">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M10 14l4-4M8.5 11.5l-1.8 1.8a3.2 3.2 0 004.5 4.5l1.8-1.8M15.5 12.5l1.8-1.8a3.2 3.2 0 00-4.5-4.5l-1.8 1.8" />
</svg>
</span>
<h1>Encurtador de links</h1>
</header>
<p class="lead">Cole um link comprido e receba um endereço curto, pronto para compartilhar.</p>
<section class="cartao">
<form id="formulario" class="formulario" novalidate>
<label for="url" class="so-leitor">Link para encurtar</label>
<input id="url" name="url" type="url" inputmode="url" maxlength="2048" placeholder="Cole seu link aqui" autocomplete="off" required />
<button type="submit" id="encurtar">Encurtar</button>
</form>
<p id="erro" class="erro" role="alert" hidden></p>
<div id="resultado" class="resultado" hidden>
<a id="curto" href="#" target="_blank" rel="noopener"></a>
<button type="button" id="copiar" class="secundario">Copiar</button>
</div>
</section>
<h2>Últimos links</h2>
<section class="cartao">
<ul id="lista" class="lista"></ul>
<p id="vazio" class="vazio">Nenhum link ainda. Encurte o primeiro aí em cima.</p>
</section>
<p class="aviso">
Os links ficam na memória do app e somem quando ele é publicado de novo.
Para guardar os links de vez, <a href="https://app.dado.cloud/deploys" target="_blank" rel="noopener">ligue um Postgres</a>.
</p>
<section class="sobre cartao" aria-labelledby="sobre-titulo">
<h2 id="sobre-titulo">Sobre este deploy</h2>
<dl>
<dt>Runtime</dt>
<dd>{{RUNTIME}}</dd>
<dt>Região</dt>
<dd>Rodando em São Paulo</dd>
<dt>No ar desde</dt>
<dd><time datetime="{{INICIO_ISO}}">{{INICIO}}</time></dd>
<dt>Mensagem</dt>
<dd>{{MENSAGEM}}</dd>
</dl>
<p class="dica">
A mensagem vem da variável <code>MENSAGEM_BOAS_VINDAS</code>. Troque o valor nas
configurações do app, no painel, e publique de novo.
</p>
</section>
<footer class="rodape">Publicado na <a href="https://dado.cloud" target="_blank" rel="noopener">Dado</a></footer>
</main>
<script>
const formulario = document.getElementById('formulario');
const campo = document.getElementById('url');
const botao = document.getElementById('encurtar');
const erro = document.getElementById('erro');
const resultado = document.getElementById('resultado');
const curto = document.getElementById('curto');
const copiar = document.getElementById('copiar');
const lista = document.getElementById('lista');
const vazio = document.getElementById('vazio');
const semProtocolo = (url) => url.replace(/^https?:\/\//, '');
function itemDaLista(link) {
const li = document.createElement('li');
const info = document.createElement('div');
info.className = 'link-info';
const a = document.createElement('a');
a.href = link.curto;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = semProtocolo(link.curto);
const destino = document.createElement('span');
destino.className = 'destino';
destino.textContent = link.url;
destino.title = link.url;
info.append(a, destino);
const cliques = document.createElement('span');
cliques.className = 'cliques';
cliques.textContent = link.cliques === 1 ? '1 clique' : `${link.cliques} cliques`;
li.append(info, cliques);
return li;
}
async function carregarLinks() {
try {
const resposta = await fetch('/api/links', { cache: 'no-store' });
if (!resposta.ok) return;
const { links } = await resposta.json();
lista.replaceChildren(...links.map(itemDaLista));
vazio.hidden = links.length > 0;
} catch {
// Sem rede: a lista fica como estava.
}
}
function mostrarErro(mensagem) {
erro.textContent = mensagem;
erro.hidden = false;
}
formulario.addEventListener('submit', async (evento) => {
evento.preventDefault();
erro.hidden = true;
let url = campo.value.trim();
if (!url) return mostrarErro('Cole um link para encurtar.');
// Quem digita "exemplo.com.br" quer dizer https://exemplo.com.br.
if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) url = `https://${url}`;
botao.disabled = true;
try {
const resposta = await fetch('/api/links', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
});
const dados = await resposta.json().catch(() => ({}));
if (!resposta.ok) return mostrarErro(dados.erro || 'Não deu para encurtar esse link. Tente de novo.');
curto.href = dados.curto;
curto.textContent = semProtocolo(dados.curto);
copiar.textContent = 'Copiar';
resultado.hidden = false;
campo.value = '';
await carregarLinks();
} catch {
mostrarErro('Sem conexão com o servidor. Tente de novo.');
} finally {
botao.disabled = false;
}
});
copiar.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(curto.href);
copiar.textContent = 'Copiado!';
} catch {
// Navegador sem permissão de área de transferência: seleciona o link.
getSelection().selectAllChildren(curto);
}
});
// Voltou para a aba depois de testar um link? Atualiza a contagem de cliques.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') carregarLinks();
});
carregarLinks();
</script>
</body>
</html>
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Link não encontrado</title>
<style>
:root { color-scheme: light dark; }
body {
margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: #f6f7f9; color: #14161a; line-height: 1.5;
}
main { max-width: 420px; text-align: center; }
h1 { font-size: 24px; margin: 0 0 8px; }
p { color: #5b6270; margin: 0 0 20px; }
a { color: #3b5bdb; font-weight: 600; }
@media (prefers-color-scheme: dark) {
body { background: #0f1115; color: #eceef2; }
p { color: #9aa1ad; }
a { color: #8299ff; }
}
</style>
</head>
<body>
<main>
<h1>Link não encontrado</h1>
<p>Esse link curto não existe ou sumiu quando o app foi publicado de novo.</p>
<a href="/">Encurtar um link</a>
</main>
</body>
</html>
+122
View File
@@ -0,0 +1,122 @@
import { readFileSync } from 'node:fs';
import express from 'express';
import { criarLink, ErroDeValidacao, FORMATO_CODIGO, listarLinks, registrarClique } from './links.js';
const PORTA = Number(process.env.PORT) || 3000;
// Variável de ambiente de exemplo: na Dado, ela se configura no painel do app.
const MENSAGEM = process.env.MENSAGEM_BOAS_VINDAS || 'Defina a variável MENSAGEM_BOAS_VINDAS para trocar este texto.';
const INICIO = new Date();
const pacote = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
const lerPagina = (nome) => readFileSync(new URL(`./paginas/${nome}`, import.meta.url), 'utf8');
const escaparHtml = (texto) =>
String(texto).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const fusoBrasilia = { timeZone: 'America/Sao_Paulo' };
const inicioFormatado = `${INICIO.toLocaleDateString('pt-BR', fusoBrasilia)} às ${INICIO.toLocaleTimeString('pt-BR', {
...fusoBrasilia,
hour: '2-digit',
minute: '2-digit',
})} (horário de Brasília)`;
// A página é montada uma vez só: nada nela muda enquanto o processo vive.
const paginaInicial = lerPagina('index.html')
.replace('{{RUNTIME}}', escaparHtml(`Express ${pacote.dependencies.express} · Node.js ${process.versions.node}`))
.replace('{{INICIO_ISO}}', INICIO.toISOString())
.replace('{{INICIO}}', escaparHtml(inicioFormatado))
.replace('{{MENSAGEM}}', escaparHtml(MENSAGEM));
const paginaNaoEncontrada = lerPagina('nao-encontrado.html');
// Freio simples contra abuso: no máximo 30 links novos a cada 10 minutos por IP.
const LIMITE_POR_IP = 30;
const JANELA_MS = 10 * 60 * 1000;
const tentativas = new Map();
function passouDoLimite(ip) {
const agora = Date.now();
if (tentativas.size > 10_000) tentativas.clear();
const atual = tentativas.get(ip);
if (!atual || atual.expiraEm <= agora) {
tentativas.set(ip, { total: 1, expiraEm: agora + JANELA_MS });
return false;
}
atual.total += 1;
return atual.total > LIMITE_POR_IP;
}
const app = express();
app.disable('x-powered-by');
// O app roda atrás de um proxy HTTPS: confia nos cabeçalhos X-Forwarded-*.
app.set('trust proxy', true);
const enderecoBase = (req) => `${req.protocol}://${req.get('host')}`;
const paraJson = (link, req) => ({
codigo: link.codigo,
url: link.url,
curto: `${enderecoBase(req)}/${link.codigo}`,
cliques: link.cliques,
criadoEm: link.criadoEm,
});
// CORS aberto só na API: qualquer site (ou outro app seu) pode chamar /api/*.
app.use('/api', (req, res, next) => {
res.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
});
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
app.use('/api', express.json({ limit: '10kb' }));
app.get('/', (req, res) => {
res.type('html').send(paginaInicial);
});
app.get('/api/links', (req, res) => {
res.set('Cache-Control', 'no-store');
res.json({ links: listarLinks().map((link) => paraJson(link, req)) });
});
app.post('/api/links', (req, res) => {
const ip = req.get('cf-connecting-ip') || req.ip;
if (passouDoLimite(ip)) {
return res.status(429).json({ erro: 'Muitos links em pouco tempo. Espere alguns minutos e tente de novo.' });
}
try {
const link = criarLink(req.body?.url);
res.status(201).json(paraJson(link, req));
} catch (erro) {
if (erro instanceof ErroDeValidacao) return res.status(400).json({ erro: erro.message });
throw erro;
}
});
// O redirecionamento é feito pelo servidor: GET /<código> → 302 para o link.
app.get('/:codigo', (req, res, next) => {
if (!FORMATO_CODIGO.test(req.params.codigo)) return next();
const link = registrarClique(req.params.codigo);
if (!link) return res.status(404).type('html').send(paginaNaoEncontrada);
res.set('Cache-Control', 'no-store');
res.redirect(302, link.url);
});
app.use((req, res) => {
res.status(404).type('html').send(paginaNaoEncontrada);
});
// JSON malformado no corpo vira 400 com mensagem, não página de erro.
app.use((erro, req, res, next) => {
if (erro.type === 'entity.parse.failed' || erro.type === 'entity.too.large') {
return res.status(400).json({ erro: 'Corpo inválido. Envie JSON no formato {"url": "https://..."}.' });
}
next(erro);
});
app.listen(PORTA, () => {
console.log(`Encurtador no ar em http://localhost:${PORTA}`);
});