Compare commits
3 commits
6873b87a85
...
0c41ed4279
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c41ed4279 | |||
| 6f78511946 | |||
| 663a8d5bf2 |
22 changed files with 1489 additions and 225 deletions
150
.agent
Normal file
150
.agent
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
# arquivo: .agent
|
||||||
|
# Agente de desenvolvimento para o projeto e-li.nps
|
||||||
|
#
|
||||||
|
# Projeto:
|
||||||
|
# Widget NPS embutível via 1 arquivo JS + API em Go.
|
||||||
|
# Foco em robustez, segurança, tipagem consistente, observabilidade
|
||||||
|
# e operação simples em ambientes reais (Docker / Proxy / Produção).
|
||||||
|
|
||||||
|
agent_name: "quero_nps"
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Descrição do projeto (fonte de verdade)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
project_description:
|
||||||
|
- "Widget NPS carregado via 1 arquivo JavaScript (e-li.nps.js)."
|
||||||
|
- "API HTTP escrita em Go."
|
||||||
|
- "PostgreSQL como banco de dados."
|
||||||
|
- "Painel administrativo opcional protegido por senha."
|
||||||
|
- "Uso por aplicações externas via <script>."
|
||||||
|
- "Fail-closed: se a API falhar, o widget não abre."
|
||||||
|
- "CORS liberado para uso amplo."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Stack
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
project_stack:
|
||||||
|
backend: "Go 1.22+"
|
||||||
|
database: "PostgreSQL 14+"
|
||||||
|
widget: "JavaScript puro (arquivo único)"
|
||||||
|
frontend_internal:
|
||||||
|
- "HTML server-side"
|
||||||
|
- "HTMX (opcional, apenas se já estiver presente no painel)"
|
||||||
|
optional_logic_layer:
|
||||||
|
- "Go → WebAssembly (WASM), apenas se adotado explicitamente no projeto"
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Regras gerais
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
rules:
|
||||||
|
- "Respeitar fielmente o comportamento descrito no README.md."
|
||||||
|
- "Não alterar contratos públicos do widget sem versionamento."
|
||||||
|
- "Evitar mudanças que quebrem widgets já embedados em clientes."
|
||||||
|
- "Mudanças que impactem desenvolvedores OU usuários DEVEM ser documentadas."
|
||||||
|
- "Código deve ser previsível, explícito e fácil de auditar."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Linguagem, nomes e comentários
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
naming_and_language:
|
||||||
|
- "Nomes de variáveis, funções e arquivos preferencialmente em português."
|
||||||
|
- "Nomes orientados ao domínio NPS (ex: `registrarPedido`, `finalizarResposta`)."
|
||||||
|
- "Comentários SEMPRE em português."
|
||||||
|
- "Comentários devem explicar regras de negócio e decisões técnicas."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Contratos e tipagens
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
typing_and_contracts:
|
||||||
|
- "Contratos de API devem ser explícitos e estáveis."
|
||||||
|
- "Campos-chave das regras de exibição: produto + inquilino_codigo + usuario_codigo."
|
||||||
|
- "Normalizações técnicas NÃO alteram valores exibidos ao usuário."
|
||||||
|
- "Tipagens JS/TS são auxiliares e não substituem validação no backend."
|
||||||
|
- "Validação SEMPRE no servidor."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Widget JavaScript
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
widget_policy:
|
||||||
|
- "Widget deve ser carregado via um único <script>."
|
||||||
|
- "Nenhuma dependência externa no cliente."
|
||||||
|
- "Cache controlado exclusivamente pelo servidor via ETag."
|
||||||
|
- "Browser sempre revalida o JS."
|
||||||
|
- "Se a API falhar, o widget NÃO deve abrir (fail-closed)."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Backend Go
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
backend_policy:
|
||||||
|
- "Servidor Go é a autoridade de regras e persistência."
|
||||||
|
- "Tabelas criadas automaticamente por produto: nps_{produto}."
|
||||||
|
- "Normalização de produto SOMENTE para uso técnico."
|
||||||
|
- "Nunca usar dados não normalizados em SQL."
|
||||||
|
- "Painel só habilita se SENHA_PAINEL estiver definida."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Segurança: prevenção de SQL Injection (OBRIGATÓRIO)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
sql_injection_prevention:
|
||||||
|
- "NUNCA concatenar SQL com entrada do usuário."
|
||||||
|
- "Usar queries parametrizadas SEMPRE."
|
||||||
|
- "Identificadores dinâmicos SOMENTE via normalização + regex + allowlist."
|
||||||
|
- "Regex obrigatória: ^[a-z_][a-z0-9_]*$."
|
||||||
|
- "ORDER BY dinâmico apenas com colunas previamente definidas."
|
||||||
|
- "Toda decisão dinâmica de SQL deve ser comentada."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Observabilidade e logs (OBRIGATÓRIO)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
logging_policy:
|
||||||
|
- "Registrar logs relevantes em toda a aplicação."
|
||||||
|
- "Logar: inicialização, rotas, chamadas de API, banco e erros."
|
||||||
|
- "Registrar tempo de execução das requisições."
|
||||||
|
- "Incluir IP real do usuário quando disponível."
|
||||||
|
- "Evitar log excessivo ou redundante."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Proteção de segredos nos logs (CRÍTICO)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
secrets_policy:
|
||||||
|
- "NUNCA logar senhas, tokens, cookies, Authorization, secrets ou DSN."
|
||||||
|
- "Campos sensíveis devem ser omitidos ou mascarados."
|
||||||
|
- "Na dúvida, NÃO LOGAR."
|
||||||
|
- "Usar '[REDACTED]' quando necessário."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Proxy e IP real
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
proxy_policy:
|
||||||
|
- "Respeitar X-Forwarded-For e X-Real-IP."
|
||||||
|
- "Uso de middleware RealIP é obrigatório."
|
||||||
|
- "Persistir IP real para auditoria."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# README.md — regra OBRIGATÓRIA
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
readme_policy:
|
||||||
|
- "O README.md é a fonte de verdade operacional do projeto."
|
||||||
|
- "SE a mudança for IMPORTANTE para o DESENVOLVEDOR, atualizar o README.md."
|
||||||
|
- "SE a mudança for IMPORTANTE para o USUÁRIO, atualizar o README.md."
|
||||||
|
- "Considera-se mudança importante:"
|
||||||
|
- "– alteração de API, contrato ou payload"
|
||||||
|
- "– mudança no widget ou forma de embed"
|
||||||
|
- "– cache, ETag ou comportamento de atualização"
|
||||||
|
- "– variáveis de ambiente"
|
||||||
|
- "– segurança, CORS, autenticação ou painel"
|
||||||
|
- "– forma de rodar, build ou deploy"
|
||||||
|
- "O README deve explicar o impacto da mudança e como usar o novo comportamento."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Checklist final
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
checklist:
|
||||||
|
- "[ ] Compatível com widgets já publicados"
|
||||||
|
- "[ ] SQL 100% parametrizado"
|
||||||
|
- "[ ] Identificadores normalizados e validados"
|
||||||
|
- "[ ] Logs relevantes presentes"
|
||||||
|
- "[ ] Nenhum segredo em logs"
|
||||||
|
- "[ ] Cache do JS controlado por ETag"
|
||||||
|
- "[ ] README.md atualizado se a mudança impacta dev ou usuário"
|
||||||
|
- "[ ] Fluxo principal testado manualmente"
|
||||||
|
|
@ -13,6 +13,13 @@ RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
# Build do WASM do widget (regras de negócio no cliente)
|
||||||
|
# Importante: a compilação do WASM exige GOOS=js/GOARCH=wasm.
|
||||||
|
RUN GOOS=js GOARCH=wasm go build -trimpath -ldflags="-s -w" -o web/static/e-li.nps.wasm ./cmd/widgetwasm
|
||||||
|
|
||||||
|
# Copia o runtime JS do Go para WASM (Go class, polyfills)
|
||||||
|
RUN cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/static/wasm_exec.js
|
||||||
|
|
||||||
# Build do binário
|
# Build do binário
|
||||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||||
go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||||
|
|
|
||||||
47
README.md
47
README.md
|
|
@ -27,6 +27,38 @@ O servidor controla o cache de `/static/e-li.nps.js` via **ETag**.
|
||||||
|
|
||||||
Isso evita problemas de clientes com JS antigo em cache após mudanças.
|
Isso evita problemas de clientes com JS antigo em cache após mudanças.
|
||||||
|
|
||||||
|
### WebAssembly (WASM) — regras do widget em Go
|
||||||
|
|
||||||
|
O widget `e-li.nps.js` carrega um módulo WASM compilado em Go, para concentrar
|
||||||
|
as regras de negócio do cliente (pré-validações, cooldown e decisão de abertura
|
||||||
|
com base na resposta do backend).
|
||||||
|
|
||||||
|
Arquivos servidos:
|
||||||
|
|
||||||
|
- `/static/e-li.nps.js` (arquivo único do widget)
|
||||||
|
- `/static/e-li.nps.wasm` (módulo WASM)
|
||||||
|
- `/static/wasm_exec.js` (runtime do Go para WASM)
|
||||||
|
|
||||||
|
Regras importantes:
|
||||||
|
|
||||||
|
- **Fail-closed**: se o WASM não carregar, o widget não abre.
|
||||||
|
- Cache é controlado por **ETag** e o browser sempre **revalida**.
|
||||||
|
- O backend Go continua sendo a **autoridade** das regras e persistência.
|
||||||
|
|
||||||
|
#### Build local do WASM
|
||||||
|
|
||||||
|
Para (re)gerar os arquivos do WASM localmente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# gera o módulo WASM
|
||||||
|
GOOS=js GOARCH=wasm go build -o web/static/e-li.nps.wasm ./cmd/widgetwasm
|
||||||
|
|
||||||
|
# copia o runtime JS do Go para WASM
|
||||||
|
cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/static/wasm_exec.js
|
||||||
|
```
|
||||||
|
|
||||||
|
> Observação: no build via Docker, esses passos já são executados no `Dockerfile`.
|
||||||
|
|
||||||
### Arquivo `.env`
|
### Arquivo `.env`
|
||||||
|
|
||||||
O servidor carrega automaticamente um arquivo `.env` na raiz do projeto (se existir) usando `godotenv`.
|
O servidor carrega automaticamente um arquivo `.env` na raiz do projeto (se existir) usando `godotenv`.
|
||||||
|
|
@ -341,13 +373,18 @@ curl -sS -X PATCH http://localhost:8080/api/e-li.nps/elicencie_gov/<id> \
|
||||||
- O nome **exibido ao usuário** é o original informado e fica salvo em `produto_nome` na tabela do produto.
|
- O nome **exibido ao usuário** é o original informado e fica salvo em `produto_nome` na tabela do produto.
|
||||||
- O controle de exibição (regras 45 dias / 10 dias) é baseado em: **produto + inquilino_codigo + usuario_codigo**.
|
- O controle de exibição (regras 45 dias / 10 dias) é baseado em: **produto + inquilino_codigo + usuario_codigo**.
|
||||||
|
|
||||||
## Recomendações (para prompts / manutenção)
|
### Observabilidade (logs)
|
||||||
|
|
||||||
Alguns cuidados:
|
O servidor registra **uma linha por requisição** com:
|
||||||
|
|
||||||
|
- `metodo`, `path`, `status`
|
||||||
|
- `dur_ms` (tempo de execução)
|
||||||
|
- `request_id` (quando disponível)
|
||||||
|
- `ip_real` (após `middleware.RealIP`)
|
||||||
|
|
||||||
|
Regra importante (segurança): o projeto **não** deve logar segredos (senha, tokens,
|
||||||
|
cookies, Authorization, DSN).
|
||||||
|
|
||||||
- Nomes de variáveis ou arquivos preferencialmente em português
|
|
||||||
- Sempre adicionar comentários em português que ajudem humanos e IAs na manutenção
|
|
||||||
- Se a mudança for importante, atualizar `README.md`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
|
@ -20,8 +21,13 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Load .env if present (convenience for local dev). Environment variables
|
// Logger estruturado (stdout). Mantemos log.Printf apenas para logs muito
|
||||||
// explicitly set in the OS take precedence.
|
// iniciais/críticos e para compatibilidade; o restante deve usar slog.
|
||||||
|
logger := elinps.LoggerPadrao()
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
|
||||||
|
// Carrega .env se existir (conveniência para dev local).
|
||||||
|
// Variáveis definidas no SO têm precedência.
|
||||||
_ = godotenv.Load()
|
_ = godotenv.Load()
|
||||||
|
|
||||||
cfg := mustLoadConfig()
|
cfg := mustLoadConfig()
|
||||||
|
|
@ -35,7 +41,7 @@ func main() {
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Ensures required extensions exist.
|
// Garante extensões necessárias.
|
||||||
if err := db.EnsurePgcrypto(ctx, pool); err != nil {
|
if err := db.EnsurePgcrypto(ctx, pool); err != nil {
|
||||||
log.Fatalf("ensure pgcrypto: %v", err)
|
log.Fatalf("ensure pgcrypto: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -44,23 +50,24 @@ func main() {
|
||||||
r.Use(middleware.RequestID)
|
r.Use(middleware.RequestID)
|
||||||
r.Use(middleware.RealIP)
|
r.Use(middleware.RealIP)
|
||||||
r.Use(middleware.Recoverer)
|
r.Use(middleware.Recoverer)
|
||||||
|
r.Use(elinps.MiddlewareLogRequisicao(logger))
|
||||||
r.Use(middleware.Timeout(15 * time.Second))
|
r.Use(middleware.Timeout(15 * time.Second))
|
||||||
r.Use(middleware.Compress(5))
|
r.Use(middleware.Compress(5))
|
||||||
|
|
||||||
// CORS wildcard + preflight
|
// CORS liberado + preflight.
|
||||||
r.Use(elinps.CORSMiddleware())
|
r.Use(elinps.CORSMiddleware())
|
||||||
|
|
||||||
// Basic limits
|
// Limites básicos.
|
||||||
r.Use(elinps.MaxBodyBytesMiddleware(64 * 1024))
|
r.Use(elinps.MaxBodyBytesMiddleware(64 * 1024))
|
||||||
|
|
||||||
// Health
|
// Health.
|
||||||
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||||
|
|
||||||
// Home: renderiza README.md
|
// Home: renderiza README.md
|
||||||
// Público (sem senha), para facilitar documentação do serviço.
|
// Público (sem senha), para facilitar documentação do serviço.
|
||||||
r.Get("/", elinps.NewReadmePage("README.md").ServeHTTP)
|
r.Get("/", elinps.NewReadmePage("README.md").ServeHTTP)
|
||||||
|
|
||||||
// Static widget
|
// Widget estático.
|
||||||
fileServer := http.FileServer(http.Dir("web/static"))
|
fileServer := http.FileServer(http.Dir("web/static"))
|
||||||
// Versão do widget para controle de cache.
|
// Versão do widget para controle de cache.
|
||||||
//
|
//
|
||||||
|
|
@ -85,14 +92,52 @@ func main() {
|
||||||
|
|
||||||
http.ServeFile(w, r, "web/static/e-li.nps.js")
|
http.ServeFile(w, r, "web/static/e-li.nps.js")
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// WASM do widget.
|
||||||
|
// Regra: cache controlado por ETag e revalidação obrigatória.
|
||||||
|
// Importante: mantemos o MESMO ETag da inicialização (versaoWidget)
|
||||||
|
// para JS e WASM, garantindo que ambos "andem juntos".
|
||||||
|
r.Get("/e-li.nps.wasm", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
etag := fmt.Sprintf("\"%s\"", versaoWidget)
|
||||||
|
w.Header().Set("ETag", etag)
|
||||||
|
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
|
||||||
|
w.Header().Set("Content-Type", "application/wasm")
|
||||||
|
|
||||||
|
if r.Header.Get("If-None-Match") == etag {
|
||||||
|
w.WriteHeader(http.StatusNotModified)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.ServeFile(w, r, "web/static/e-li.nps.wasm")
|
||||||
|
})
|
||||||
|
|
||||||
|
// Runtime JS do Go para WASM.
|
||||||
|
// Também fica sob ETag + revalidação.
|
||||||
|
r.Get("/wasm_exec.js", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
etag := fmt.Sprintf("\"%s\"", versaoWidget)
|
||||||
|
w.Header().Set("ETag", etag)
|
||||||
|
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
|
||||||
|
w.Header().Set("Content-Type", "application/javascript")
|
||||||
|
|
||||||
|
if r.Header.Get("If-None-Match") == etag {
|
||||||
|
w.WriteHeader(http.StatusNotModified)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.ServeFile(w, r, "web/static/wasm_exec.js")
|
||||||
|
})
|
||||||
r.Handle("/*", http.StripPrefix("/static/", fileServer))
|
r.Handle("/*", http.StripPrefix("/static/", fileServer))
|
||||||
})
|
})
|
||||||
// Convenience: allow /teste.html
|
// Conveniência: permitir /teste.html
|
||||||
r.Get("/teste.html", func(w http.ResponseWriter, r *http.Request) {
|
r.Get("/teste.html", func(w http.ResponseWriter, r *http.Request) {
|
||||||
http.ServeFile(w, r, "web/static/teste.html")
|
http.ServeFile(w, r, "web/static/teste.html")
|
||||||
})
|
})
|
||||||
|
|
||||||
// NPS routes
|
// Conveniência: favicon.
|
||||||
|
// O arquivo fica em web/static/favicon.ico.
|
||||||
|
r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.ServeFile(w, r, "web/static/favicon.ico")
|
||||||
|
})
|
||||||
|
|
||||||
|
// Rotas NPS.
|
||||||
h := elinps.NewHandlers(pool)
|
h := elinps.NewHandlers(pool)
|
||||||
r.Route("/api/e-li.nps", func(r chi.Router) {
|
r.Route("/api/e-li.nps", func(r chi.Router) {
|
||||||
r.Post("/pedido", h.PostPedido)
|
r.Post("/pedido", h.PostPedido)
|
||||||
|
|
@ -103,7 +148,7 @@ func main() {
|
||||||
r.Get("/{produto}/{id}/form", h.GetForm)
|
r.Get("/{produto}/{id}/form", h.GetForm)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Painel (dashboard)
|
// Painel.
|
||||||
// Protegido por SENHA_PAINEL.
|
// Protegido por SENHA_PAINEL.
|
||||||
// Se SENHA_PAINEL estiver vazia, o painel fica desabilitado.
|
// Se SENHA_PAINEL estiver vazia, o painel fica desabilitado.
|
||||||
painel := elinps.NewPainelHandlers(pool, cfg.SenhaPainel)
|
painel := elinps.NewPainelHandlers(pool, cfg.SenhaPainel)
|
||||||
|
|
@ -116,7 +161,7 @@ func main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
log.Printf("listening on %s", cfg.Addr)
|
logger.Info("servidor_iniciado", "addr", cfg.Addr)
|
||||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
log.Fatalf("listen: %v", err)
|
log.Fatalf("listen: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -126,9 +171,9 @@ func main() {
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||||
log.Printf("shutdown: %v", err)
|
logger.Error("erro_no_shutdown", "err", err)
|
||||||
}
|
}
|
||||||
log.Printf("bye")
|
logger.Info("servidor_finalizado")
|
||||||
}
|
}
|
||||||
|
|
||||||
type config struct {
|
type config struct {
|
||||||
|
|
|
||||||
241
cmd/widgetwasm/main.go
Normal file
241
cmd/widgetwasm/main.go
Normal file
|
|
@ -0,0 +1,241 @@
|
||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"syscall/js"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IMPORTANTE (.agent): o backend Go continua sendo a autoridade das regras.
|
||||||
|
// Este WASM existe para concentrar regras de negócio do widget (cliente) em Go,
|
||||||
|
// mantendo o arquivo JS pequeno e fácil de auditar.
|
||||||
|
|
||||||
|
var dataISORe = regexp.MustCompile(`^([0-9]{4})-([0-9]{2})-([0-9]{2})$`)
|
||||||
|
|
||||||
|
type cfgWidget = contratos.ConfigWidget
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
js.Global().Set("__eli_nps_wasm_preflight", js.FuncOf(preflight))
|
||||||
|
js.Global().Set("__eli_nps_wasm_decidir", js.FuncOf(decidir))
|
||||||
|
js.Global().Set("__eli_nps_wasm_cooldown_ativo", js.FuncOf(cooldownAtivo))
|
||||||
|
js.Global().Set("__eli_nps_wasm_set_cooldown", js.FuncOf(setCooldown))
|
||||||
|
js.Global().Set("__eli_nps_wasm_ready", true)
|
||||||
|
|
||||||
|
// Mantém o módulo vivo.
|
||||||
|
select {}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cooldownAtivo(this js.Value, args []js.Value) any {
|
||||||
|
if len(args) < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
chave := strings.TrimSpace(args[0].String())
|
||||||
|
if chave == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best-effort: se der erro, tratamos como não ativo.
|
||||||
|
storage := js.Global().Get("localStorage")
|
||||||
|
if storage.IsUndefined() || storage.IsNull() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
v := storage.Call("getItem", chave)
|
||||||
|
if v.IsNull() || v.IsUndefined() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed := js.Global().Get("JSON").Call("parse", v)
|
||||||
|
until := parsed.Get("until")
|
||||||
|
if until.IsUndefined() || until.IsNull() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
agora := js.Global().Get("Date").Call("now").Int()
|
||||||
|
return int64(agora) < int64(until.Int())
|
||||||
|
}
|
||||||
|
|
||||||
|
func setCooldown(this js.Value, args []js.Value) any {
|
||||||
|
if len(args) < 2 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
chave := strings.TrimSpace(args[0].String())
|
||||||
|
if chave == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ateMs := int64(args[1].Int())
|
||||||
|
if ateMs <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
storage := js.Global().Get("localStorage")
|
||||||
|
if storage.IsUndefined() || storage.IsNull() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
obj := js.Global().Get("Object").New()
|
||||||
|
obj.Set("until", ateMs)
|
||||||
|
json := js.Global().Get("JSON").Call("stringify", obj)
|
||||||
|
storage.Call("setItem", chave, json)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func preflight(this js.Value, args []js.Value) any {
|
||||||
|
if len(args) < 1 {
|
||||||
|
return map[string]any{"ok": false, "motivo": "sem_cfg"}
|
||||||
|
}
|
||||||
|
cfg := lerCfg(args[0])
|
||||||
|
|
||||||
|
// Bloqueio por data mínima.
|
||||||
|
if antesDaDataMinima(cfg.DataMinimaAbertura) {
|
||||||
|
return map[string]any{"ok": false, "motivo": "antes_da_data_minima"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// controle de exibição: produto + inquilino_codigo + usuario_codigo
|
||||||
|
if cfg.ProdutoNome == "" || cfg.InquilinoCodigo == "" || cfg.UsuarioCodigo == "" {
|
||||||
|
return map[string]any{"ok": false, "motivo": "contexto_incompleto"}
|
||||||
|
}
|
||||||
|
|
||||||
|
chaveCooldown := chaveCooldown(cfg.ProdutoNome, cfg.InquilinoCodigo, cfg.UsuarioCodigo)
|
||||||
|
untilMs := calcularCooldownAteMs(cfg.CooldownHours)
|
||||||
|
|
||||||
|
// Enviamos exatamente o produto_nome informado.
|
||||||
|
payload := map[string]any{
|
||||||
|
"produto_nome": cfg.ProdutoNome,
|
||||||
|
"inquilino_codigo": cfg.InquilinoCodigo,
|
||||||
|
"inquilino_nome": cfg.InquilinoNome,
|
||||||
|
"usuario_codigo": cfg.UsuarioCodigo,
|
||||||
|
"usuario_nome": cfg.UsuarioNome,
|
||||||
|
"usuario_telefone": cfg.UsuarioTelefone,
|
||||||
|
"usuario_email": normalizarEmail(cfg.UsuarioEmail),
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]any{
|
||||||
|
"ok": true,
|
||||||
|
"chave_cooldown": chaveCooldown,
|
||||||
|
"cooldown_ate_ms": untilMs,
|
||||||
|
"payload": payload,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decidir(this js.Value, args []js.Value) any {
|
||||||
|
// Entrada:
|
||||||
|
// - args[0] = cfg (para cooldownHours)
|
||||||
|
// - args[1] = resposta JSON do servidor (obj)
|
||||||
|
if len(args) < 2 {
|
||||||
|
return map[string]any{"abrir": false, "motivo": "sem_dados"}
|
||||||
|
}
|
||||||
|
cfg := lerCfg(args[0])
|
||||||
|
data := args[1]
|
||||||
|
|
||||||
|
untilMs := calcularCooldownAteMs(cfg.CooldownHours)
|
||||||
|
|
||||||
|
// Fail-closed.
|
||||||
|
if data.IsUndefined() || data.IsNull() {
|
||||||
|
return map[string]any{"abrir": false, "motivo": "resposta_invalida", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Esperado: {pode_abrir:bool, id:string, produto:string}
|
||||||
|
podeAbrir := data.Get("pode_abrir")
|
||||||
|
if !podeAbrir.Truthy() {
|
||||||
|
return map[string]any{"abrir": false, "motivo": "nao_pode_abrir", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs}
|
||||||
|
}
|
||||||
|
id := strings.TrimSpace(data.Get("id").String())
|
||||||
|
produtoRota := strings.TrimSpace(data.Get("produto").String())
|
||||||
|
if id == "" || produtoRota == "" {
|
||||||
|
// Não dá para montar URL segura.
|
||||||
|
return map[string]any{"abrir": false, "motivo": "sem_produto_ou_id", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs}
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]any{
|
||||||
|
"abrir": true,
|
||||||
|
"id": id,
|
||||||
|
"produto_rota": produtoRota,
|
||||||
|
"aplicar_cooldown": true,
|
||||||
|
"cooldown_ate_ms": untilMs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func lerCfg(v js.Value) cfgWidget {
|
||||||
|
// Leitura defensiva: tudo é best-effort.
|
||||||
|
getStr := func(k string) string {
|
||||||
|
if v.Type() != js.TypeObject {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
vv := v.Get(k)
|
||||||
|
if vv.IsUndefined() || vv.IsNull() {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(vv.String())
|
||||||
|
}
|
||||||
|
getNum := func(k string) float64 {
|
||||||
|
if v.Type() != js.TypeObject {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
vv := v.Get(k)
|
||||||
|
if vv.IsUndefined() || vv.IsNull() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return vv.Float()
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfgWidget{
|
||||||
|
ProdutoNome: getStr("produto_nome"),
|
||||||
|
InquilinoCodigo: getStr("inquilino_codigo"),
|
||||||
|
InquilinoNome: getStr("inquilino_nome"),
|
||||||
|
UsuarioCodigo: getStr("usuario_codigo"),
|
||||||
|
UsuarioNome: getStr("usuario_nome"),
|
||||||
|
UsuarioTelefone: getStr("usuario_telefone"),
|
||||||
|
UsuarioEmail: getStr("usuario_email"),
|
||||||
|
CooldownHours: getNum("cooldownHours"),
|
||||||
|
DataMinimaAbertura: getStr("data_minima_abertura"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizarEmail(email string) string {
|
||||||
|
return strings.ToLower(strings.TrimSpace(email))
|
||||||
|
}
|
||||||
|
|
||||||
|
func chaveCooldown(produto, inquilino, usuarioCodigo string) string {
|
||||||
|
// Prefixo de storage atualizado para o novo nome do projeto.
|
||||||
|
return "eli-nps:cooldown:" + produto + ":" + inquilino + ":" + usuarioCodigo
|
||||||
|
}
|
||||||
|
|
||||||
|
func calcularCooldownAteMs(hours float64) int64 {
|
||||||
|
if hours <= 0 {
|
||||||
|
hours = 24
|
||||||
|
}
|
||||||
|
agora := js.Global().Get("Date").Call("now").Int()
|
||||||
|
return int64(agora) + int64(hours*3600*1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
func antesDaDataMinima(s string) bool {
|
||||||
|
// Aceita somente ISO (data) YYYY-MM-DD.
|
||||||
|
v := strings.TrimSpace(s)
|
||||||
|
if v == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
m := dataISORe.FindStringSubmatch(v)
|
||||||
|
if m == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// new Date(ano, mes-1, dia, 0, 0, 0, 0)
|
||||||
|
ano := m[1]
|
||||||
|
mes := m[2]
|
||||||
|
dia := m[3]
|
||||||
|
|
||||||
|
// Converte para números via JS (simplifica validação e compatibilidade de timezone).
|
||||||
|
nAno := js.Global().Get("Number").Invoke(ano).Int()
|
||||||
|
nMes := js.Global().Get("Number").Invoke(mes).Int()
|
||||||
|
nDia := js.Global().Get("Number").Invoke(dia).Int()
|
||||||
|
if nAno <= 0 || nMes < 1 || nMes > 12 || nDia < 1 || nDia > 31 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
dataMin := js.Global().Get("Date").New(nAno, nMes-1, nDia, 0, 0, 0, 0)
|
||||||
|
agora := js.Global().Get("Date").New()
|
||||||
|
return agora.Call("getTime").Int() < dataMin.Call("getTime").Int()
|
||||||
|
}
|
||||||
128
internal/contratos/tipos.go
Normal file
128
internal/contratos/tipos.go
Normal file
|
|
@ -0,0 +1,128 @@
|
||||||
|
package contratos
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// Tipos centralizados do projeto.
|
||||||
|
//
|
||||||
|
// Regra: este arquivo concentra as tipagens (structs) usadas como contratos de
|
||||||
|
// dados entre camadas (backend, painel e widget/WASM), para manter consistência
|
||||||
|
// e facilitar auditoria.
|
||||||
|
|
||||||
|
// ------------------------------
|
||||||
|
// API do widget
|
||||||
|
// ------------------------------
|
||||||
|
|
||||||
|
type PedidoInput struct {
|
||||||
|
ProdutoNome string `json:"produto_nome"`
|
||||||
|
InquilinoCodigo string `json:"inquilino_codigo"`
|
||||||
|
InquilinoNome string `json:"inquilino_nome"`
|
||||||
|
UsuarioCodigo string `json:"usuario_codigo"`
|
||||||
|
UsuarioNome string `json:"usuario_nome"`
|
||||||
|
UsuarioTelefone string `json:"usuario_telefone"`
|
||||||
|
UsuarioEmail string `json:"usuario_email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PedidoResponse struct {
|
||||||
|
PodeAbrir bool `json:"pode_abrir"`
|
||||||
|
Motivo string `json:"motivo,omitempty"`
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
// Produto normalizado retornado pelo backend para montar URL segura.
|
||||||
|
Produto string `json:"produto,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PatchInput struct {
|
||||||
|
Nota *int `json:"nota,omitempty"`
|
||||||
|
Justificativa *string `json:"justificativa,omitempty"`
|
||||||
|
Finalizar bool `json:"finalizar,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Registro struct {
|
||||||
|
// ProdutoNome é o nome original do produto como enviado pela integração/widget.
|
||||||
|
// Ele existe apenas para exibição ao usuário.
|
||||||
|
//
|
||||||
|
// Importante: a normalização (remoção de acentos/símbolos) é usada apenas
|
||||||
|
// para formar o nome da tabela no Postgres e o parâmetro {produto} da rota.
|
||||||
|
ProdutoNome string
|
||||||
|
ID string
|
||||||
|
Status string
|
||||||
|
Nota *int
|
||||||
|
Justificativa *string
|
||||||
|
PedidoCriadoEm time.Time
|
||||||
|
RespondidoEm *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormPageData é o payload para renderização do formulário no iframe.
|
||||||
|
type FormPageData struct {
|
||||||
|
Produto string
|
||||||
|
ID string
|
||||||
|
Reg Registro
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------
|
||||||
|
// Painel
|
||||||
|
// ------------------------------
|
||||||
|
|
||||||
|
// NPSMensal representa o cálculo do NPS agregado por mês.
|
||||||
|
type NPSMensal struct {
|
||||||
|
Mes string
|
||||||
|
Detratores int
|
||||||
|
Neutros int
|
||||||
|
Promotores int
|
||||||
|
Total int
|
||||||
|
NPS int
|
||||||
|
}
|
||||||
|
|
||||||
|
// RespostaPainel representa uma resposta para listagem no painel.
|
||||||
|
type RespostaPainel struct {
|
||||||
|
ID string
|
||||||
|
RespondidoEm *time.Time
|
||||||
|
PedidoCriadoEm time.Time
|
||||||
|
UsuarioCodigo *string
|
||||||
|
UsuarioNome string
|
||||||
|
UsuarioEmail *string
|
||||||
|
Nota *int
|
||||||
|
Justificativa *string
|
||||||
|
}
|
||||||
|
|
||||||
|
type PainelDados struct {
|
||||||
|
Produto string
|
||||||
|
Produtos []string
|
||||||
|
Meses []NPSMensal
|
||||||
|
Respostas []RespostaPainel
|
||||||
|
Pagina int
|
||||||
|
SomenteBaixas bool
|
||||||
|
MsgErro string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListarRespostasFiltro struct {
|
||||||
|
SomenteNotasBaixas bool
|
||||||
|
Pagina int
|
||||||
|
PorPagina int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *ListarRespostasFiltro) Normalizar() {
|
||||||
|
if f.Pagina <= 0 {
|
||||||
|
f.Pagina = 1
|
||||||
|
}
|
||||||
|
if f.PorPagina <= 0 || f.PorPagina > 200 {
|
||||||
|
f.PorPagina = 50
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------
|
||||||
|
// Widget/WASM
|
||||||
|
// ------------------------------
|
||||||
|
|
||||||
|
// ConfigWidget representa as opções passadas para window.ELiNPS.init(...).
|
||||||
|
// No WASM lemos via syscall/js; aqui fica apenas a tipagem centralizada.
|
||||||
|
type ConfigWidget struct {
|
||||||
|
ProdutoNome string
|
||||||
|
InquilinoCodigo string
|
||||||
|
InquilinoNome string
|
||||||
|
UsuarioCodigo string
|
||||||
|
UsuarioNome string
|
||||||
|
UsuarioTelefone string
|
||||||
|
UsuarioEmail string
|
||||||
|
CooldownHours float64
|
||||||
|
DataMinimaAbertura string
|
||||||
|
}
|
||||||
|
|
@ -14,7 +14,7 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||||
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reasonable defaults
|
// Defaults razoáveis para um serviço pequeno/médio.
|
||||||
cfg.MaxConns = 10
|
cfg.MaxConns = 10
|
||||||
cfg.MinConns = 0
|
cfg.MinConns = 0
|
||||||
cfg.MaxConnLifetime = 60 * time.Minute
|
cfg.MaxConnLifetime = 60 * time.Minute
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,22 @@ import (
|
||||||
|
|
||||||
var produtoRe = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
|
var produtoRe = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
|
||||||
|
|
||||||
|
// TableNameValido valida se o nome de tabela está no formato esperado do projeto:
|
||||||
|
// "nps_" + produto normalizado.
|
||||||
|
//
|
||||||
|
// Motivação (segurança): identificadores não podem ser parametrizados em SQL.
|
||||||
|
// Então, sempre que precisarmos interpolar um nome de tabela, validamos aqui
|
||||||
|
// para evitar SQL injection via identificador.
|
||||||
|
func TableNameValido(tableName string) bool {
|
||||||
|
if !strings.HasPrefix(tableName, "nps_") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
produto := strings.TrimPrefix(tableName, "nps_")
|
||||||
|
// produtoRe já garante: ^[a-z_][a-z0-9_]*$
|
||||||
|
// (e a normalização limita tamanho em NormalizeProduto).
|
||||||
|
return produtoRe.MatchString(produto)
|
||||||
|
}
|
||||||
|
|
||||||
// NormalizeProduto normaliza e valida um nome de produto para uso em:
|
// NormalizeProduto normaliza e valida um nome de produto para uso em:
|
||||||
// - nomes de tabela no Postgres (prefixo nps_)
|
// - nomes de tabela no Postgres (prefixo nps_)
|
||||||
// - rotas/URLs (parâmetro {produto})
|
// - rotas/URLs (parâmetro {produto})
|
||||||
|
|
@ -80,11 +96,14 @@ func EnsurePgcrypto(ctx context.Context, pool *pgxpool.Pool) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnsureNPSTable creates the per-product table + indexes if they do not exist.
|
// EnsureNPSTable cria a tabela por produto + índices se não existirem.
|
||||||
// IMPORTANT: tableName must be created from a sanitized product name.
|
// Importante: tableName deve ser criada a partir de um produto normalizado.
|
||||||
func EnsureNPSTable(ctx context.Context, pool *pgxpool.Pool, tableName string) error {
|
func EnsureNPSTable(ctx context.Context, pool *pgxpool.Pool, tableName string) error {
|
||||||
// Identifiers cannot be passed as $1 parameters, so we must interpolate.
|
// Identifiers cannot be passed as $1 parameters, so we must interpolate.
|
||||||
// Safety: tableName is strictly derived from NormalizeProduto + prefix.
|
// Segurança: tableName deve ser estritamente derivada de NormalizeProduto + prefix.
|
||||||
|
if !TableNameValido(tableName) {
|
||||||
|
return fmt.Errorf("nome de tabela invalido")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
CREATE TABLE IF NOT EXISTS %s (
|
CREATE TABLE IF NOT EXISTS %s (
|
||||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,11 @@ package elinps
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
"e-li.nps/internal/db"
|
"e-li.nps/internal/db"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
@ -28,7 +30,7 @@ func NewHandlers(pool *pgxpool.Pool) *Handlers {
|
||||||
func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
|
|
||||||
var in PedidoInput
|
var in contratos.PedidoInput
|
||||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "json_invalido"})
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "json_invalido"})
|
||||||
return
|
return
|
||||||
|
|
@ -38,42 +40,45 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure per-product table exists (also normalizes produto).
|
// Garante a tabela do produto (e normaliza o identificador técnico).
|
||||||
table, err := h.store.EnsureTableForProduto(ctx, in.ProdutoNome)
|
table, err := h.store.EnsureTableForProduto(ctx, in.ProdutoNome)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep normalized form for the widget to build URLs safely.
|
// Mantemos a forma normalizada para o widget montar URLs com segurança.
|
||||||
// table = "nps_" + produto_normalizado
|
// table = "nps_" + produto_normalizado
|
||||||
produtoNormalizado := strings.TrimPrefix(table, "nps_")
|
produtoNormalizado := strings.TrimPrefix(table, "nps_")
|
||||||
|
|
||||||
// Rules
|
// Regras.
|
||||||
respRecente, err := h.store.HasRespostaValidaRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
respRecente, err := h.store.HasRespostaValidaRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Fail-closed
|
slog.Error("erro ao checar resposta recente", "err", err)
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
// Fail-closed.
|
||||||
|
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if respRecente {
|
if respRecente {
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "resposta_recente"})
|
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "resposta_recente"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
pedidoAberto, err := h.store.HasPedidoEmAbertoRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
pedidoAberto, err := h.store.HasPedidoEmAbertoRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
slog.Error("erro ao checar pedido em aberto", "err", err)
|
||||||
|
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if pedidoAberto {
|
if pedidoAberto {
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "pedido_em_aberto"})
|
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "pedido_em_aberto"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
id, err := h.store.CreatePedido(ctx, table, in, r)
|
id, err := h.store.CreatePedido(ctx, table, in, r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
slog.Error("erro ao criar pedido", "err", err)
|
||||||
|
writeJSON(w, http.StatusOK, contratos.PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -85,7 +90,7 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
||||||
produtoParam := chi.URLParam(r, "produto")
|
produtoParam := chi.URLParam(r, "produto")
|
||||||
id := chi.URLParam(r, "id")
|
id := chi.URLParam(r, "id")
|
||||||
|
|
||||||
// produtoParam already in path; sanitize again.
|
// produtoParam já está no path; sanitizamos novamente por segurança.
|
||||||
prod, err := db.NormalizeProduto(produtoParam)
|
prod, err := db.NormalizeProduto(produtoParam)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
||||||
|
|
@ -93,11 +98,12 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
table := db.TableNameForProduto(prod)
|
table := db.TableNameForProduto(prod)
|
||||||
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
||||||
|
slog.Error("erro ao garantir tabela", "err", err)
|
||||||
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var in PatchInput
|
var in contratos.PatchInput
|
||||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "json_invalido"})
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "json_invalido"})
|
||||||
return
|
return
|
||||||
|
|
@ -113,19 +119,21 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.store.PatchRegistro(ctx, table, id, in); err != nil {
|
if err := h.store.PatchRegistro(ctx, table, id, in); err != nil {
|
||||||
|
slog.Error("erro ao atualizar registro", "err", err)
|
||||||
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// If called via HTMX, respond with refreshed HTML fragment.
|
// Se chamado via HTMX, respondemos com fragmento HTML atualizado.
|
||||||
if r.Header.Get("HX-Request") == "true" {
|
if r.Header.Get("HX-Request") == "true" {
|
||||||
reg, err := h.store.GetRegistro(ctx, table, id)
|
reg, err := h.store.GetRegistro(ctx, table, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
slog.Error("erro ao buscar registro", "err", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte("db"))
|
w.Write([]byte("db"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
data := FormPageData{Produto: prod, ID: id, Reg: reg}
|
data := contratos.FormPageData{Produto: prod, ID: id, Reg: reg}
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
h.tpl.Render(w, "form_inner.html", data)
|
h.tpl.Render(w, "form_inner.html", data)
|
||||||
return
|
return
|
||||||
|
|
@ -147,6 +155,7 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
table := db.TableNameForProduto(prod)
|
table := db.TableNameForProduto(prod)
|
||||||
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
||||||
|
slog.Error("erro ao garantir tabela", "err", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte("db"))
|
w.Write([]byte("db"))
|
||||||
return
|
return
|
||||||
|
|
@ -159,19 +168,20 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("nao encontrado"))
|
w.Write([]byte("nao encontrado"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
slog.Error("erro ao buscar registro", "err", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte("db"))
|
w.Write([]byte("db"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
data := FormPageData{
|
data := contratos.FormPageData{
|
||||||
Produto: prod,
|
Produto: prod,
|
||||||
ID: id,
|
ID: id,
|
||||||
Reg: reg,
|
Reg: reg,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always return a standalone HTML page so the widget can use iframe.
|
// Sempre retornamos uma página HTML completa para o widget usar iframe.
|
||||||
// But the inner container is also HTMX-friendly (it swaps itself).
|
// Porém o container interno também é compatível com HTMX (swap de si mesmo).
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
h.tpl.Render(w, "form_page.html", data)
|
h.tpl.Render(w, "form_page.html", data)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
91
internal/elinps/logging.go
Normal file
91
internal/elinps/logging.go
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
package elinps
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LoggerPadrao cria um logger simples (stdout) adequado para Docker.
|
||||||
|
//
|
||||||
|
// Regras do projeto:
|
||||||
|
// - logs relevantes (rotas, tempo de execução, erros)
|
||||||
|
// - NUNCA logar segredos (Authorization/cookies/senha/DSN)
|
||||||
|
func LoggerPadrao() *slog.Logger {
|
||||||
|
return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||||
|
}
|
||||||
|
|
||||||
|
type responseWriterComStatus struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
bytes int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *responseWriterComStatus) WriteHeader(status int) {
|
||||||
|
w.status = status
|
||||||
|
w.ResponseWriter.WriteHeader(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *responseWriterComStatus) Write(b []byte) (int, error) {
|
||||||
|
if w.status == 0 {
|
||||||
|
w.status = http.StatusOK
|
||||||
|
}
|
||||||
|
n, err := w.ResponseWriter.Write(b)
|
||||||
|
w.bytes += n
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MiddlewareLogRequisicao registra uma linha por requisição com:
|
||||||
|
// - método, path, status, duração
|
||||||
|
// - request_id (se existir)
|
||||||
|
// - ip_real (após chi/middleware.RealIP)
|
||||||
|
func MiddlewareLogRequisicao(logger *slog.Logger) func(http.Handler) http.Handler {
|
||||||
|
if logger == nil {
|
||||||
|
logger = slog.Default()
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ini := time.Now()
|
||||||
|
ww := &responseWriterComStatus{ResponseWriter: w}
|
||||||
|
next.ServeHTTP(ww, r)
|
||||||
|
|
||||||
|
dur := time.Since(ini)
|
||||||
|
attrs := []any{
|
||||||
|
"metodo", r.Method,
|
||||||
|
"path", r.URL.Path,
|
||||||
|
"status", ww.status,
|
||||||
|
"dur_ms", dur.Milliseconds(),
|
||||||
|
"bytes", ww.bytes,
|
||||||
|
"ip_real", ipSomenteHost(r.RemoteAddr),
|
||||||
|
}
|
||||||
|
if reqID := requestIDFromContext(r.Context()); reqID != "" {
|
||||||
|
attrs = append(attrs, "request_id", reqID)
|
||||||
|
}
|
||||||
|
logger.Info("http_request", attrs...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ipSomenteHost retorna apenas o IP (sem porta). Se o valor não parecer um IP,
|
||||||
|
// devolve string vazia.
|
||||||
|
func ipSomenteHost(remoteAddr string) string {
|
||||||
|
ip := remoteAddr
|
||||||
|
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
|
||||||
|
ip = host
|
||||||
|
}
|
||||||
|
if net.ParseIP(ip) == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestIDFromContext(ctx context.Context) string {
|
||||||
|
// O chi/middleware.RequestID coloca o ID no context.
|
||||||
|
return middleware.GetReqID(ctx)
|
||||||
|
}
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
package elinps
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type PedidoInput struct {
|
|
||||||
ProdutoNome string `json:"produto_nome"`
|
|
||||||
InquilinoCodigo string `json:"inquilino_codigo"`
|
|
||||||
InquilinoNome string `json:"inquilino_nome"`
|
|
||||||
UsuarioCodigo string `json:"usuario_codigo"`
|
|
||||||
UsuarioNome string `json:"usuario_nome"`
|
|
||||||
UsuarioTelefone string `json:"usuario_telefone"`
|
|
||||||
UsuarioEmail string `json:"usuario_email"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PedidoResponse struct {
|
|
||||||
PodeAbrir bool `json:"pode_abrir"`
|
|
||||||
Motivo string `json:"motivo,omitempty"`
|
|
||||||
ID string `json:"id,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PatchInput struct {
|
|
||||||
Nota *int `json:"nota,omitempty"`
|
|
||||||
Justificativa *string `json:"justificativa,omitempty"`
|
|
||||||
Finalizar bool `json:"finalizar,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Registro struct {
|
|
||||||
// ProdutoNome é o nome original do produto como enviado pela integração/widget.
|
|
||||||
// Ele existe apenas para exibição ao usuário.
|
|
||||||
//
|
|
||||||
// Importante: a normalização (remoção de acentos/símbolos) é usada apenas
|
|
||||||
// para formar o nome da tabela no Postgres e o parâmetro {produto} da rota.
|
|
||||||
ProdutoNome string
|
|
||||||
ID string
|
|
||||||
Status string
|
|
||||||
Nota *int
|
|
||||||
Justificativa *string
|
|
||||||
PedidoCriadoEm time.Time
|
|
||||||
RespondidoEm *time.Time
|
|
||||||
}
|
|
||||||
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
"e-li.nps/internal/db"
|
"e-li.nps/internal/db"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
@ -57,37 +58,11 @@ func (a AuthPainel) handlerLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||||
http.Redirect(w, r, "/painel", http.StatusFound)
|
http.Redirect(w, r, "/painel", http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NPSMensal representa o cálculo do NPS agregado por mês.
|
type NPSMensal = contratos.NPSMensal
|
||||||
type NPSMensal struct {
|
|
||||||
Mes string
|
|
||||||
Detratores int
|
|
||||||
Neutros int
|
|
||||||
Promotores int
|
|
||||||
Total int
|
|
||||||
NPS int
|
|
||||||
}
|
|
||||||
|
|
||||||
// RespostaPainel representa uma resposta para listagem no painel.
|
type RespostaPainel = contratos.RespostaPainel
|
||||||
type RespostaPainel struct {
|
|
||||||
ID string
|
|
||||||
RespondidoEm *time.Time
|
|
||||||
PedidoCriadoEm time.Time
|
|
||||||
UsuarioCodigo *string
|
|
||||||
UsuarioNome string
|
|
||||||
UsuarioEmail *string
|
|
||||||
Nota *int
|
|
||||||
Justificativa *string
|
|
||||||
}
|
|
||||||
|
|
||||||
type PainelDados struct {
|
type PainelDados = contratos.PainelDados
|
||||||
Produto string
|
|
||||||
Produtos []string
|
|
||||||
Meses []NPSMensal
|
|
||||||
Respostas []RespostaPainel
|
|
||||||
Pagina int
|
|
||||||
SomenteBaixas bool
|
|
||||||
MsgErro string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a AuthPainel) handlerPainel(w http.ResponseWriter, r *http.Request, store *Store) {
|
func (a AuthPainel) handlerPainel(w http.ResponseWriter, r *http.Request, store *Store) {
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
|
|
@ -145,7 +120,7 @@ func (a AuthPainel) handlerPainel(w http.ResponseWriter, r *http.Request, store
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Se a tabela ainda não tem coluna ip_real/ etc, EnsureNPSTable deveria ajustar.
|
// Se a tabela ainda não tem coluna ip_real/ etc, EnsureNPSTable deveria ajustar.
|
||||||
if err == pgx.ErrNoRows {
|
if err == pgx.ErrNoRows {
|
||||||
respostas = []RespostaPainel{}
|
respostas = []contratos.RespostaPainel{}
|
||||||
} else {
|
} else {
|
||||||
dados.MsgErro = "erro ao listar respostas"
|
dados.MsgErro = "erro ao listar respostas"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,9 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
|
"e-li.nps/internal/db"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -41,8 +44,11 @@ ORDER BY tablename`)
|
||||||
// - 1–6 detratores
|
// - 1–6 detratores
|
||||||
// - 7–8 neutros
|
// - 7–8 neutros
|
||||||
// - 9–10 promotores
|
// - 9–10 promotores
|
||||||
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]NPSMensal, error) {
|
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]contratos.NPSMensal, error) {
|
||||||
// Segurança: tabela deve ser derivada de NormalizeProduto + prefixo.
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(tabela) {
|
||||||
|
return nil, fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
WITH base AS (
|
WITH base AS (
|
||||||
SELECT
|
SELECT
|
||||||
|
|
@ -70,9 +76,9 @@ ORDER BY mes ASC`, tabela)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
out := []NPSMensal{}
|
out := []contratos.NPSMensal{}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var m NPSMensal
|
var m contratos.NPSMensal
|
||||||
if err := rows.Scan(&m.Mes, &m.Detratores, &m.Neutros, &m.Promotores, &m.Total); err != nil {
|
if err := rows.Scan(&m.Mes, &m.Detratores, &m.Neutros, &m.Promotores, &m.Total); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -92,17 +98,15 @@ type ListarRespostasFiltro struct {
|
||||||
PorPagina int
|
PorPagina int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *ListarRespostasFiltro) normalizar() {
|
func (f *ListarRespostasFiltro) normalizar() { (*contratos.ListarRespostasFiltro)(f).Normalizar() }
|
||||||
if f.Pagina <= 0 {
|
|
||||||
f.Pagina = 1
|
|
||||||
}
|
|
||||||
if f.PorPagina <= 0 || f.PorPagina > 200 {
|
|
||||||
f.PorPagina = 50
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
|
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
|
||||||
func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro ListarRespostasFiltro) ([]RespostaPainel, error) {
|
func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro ListarRespostasFiltro) ([]contratos.RespostaPainel, error) {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(tabela) {
|
||||||
|
return nil, fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
|
|
||||||
filtro.normalizar()
|
filtro.normalizar()
|
||||||
offset := (filtro.Pagina - 1) * filtro.PorPagina
|
offset := (filtro.Pagina - 1) * filtro.PorPagina
|
||||||
|
|
||||||
|
|
@ -111,6 +115,9 @@ func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro Lista
|
||||||
cond += " AND nota BETWEEN 1 AND 6"
|
cond += " AND nota BETWEEN 1 AND 6"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Importante (segurança): apesar do cond ser construído em string, ele NÃO usa
|
||||||
|
// entrada do usuário diretamente. O filtro "SomenteNotasBaixas" é booleano.
|
||||||
|
// A tabela também é validada por regex (TableNameValido).
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
SELECT
|
SELECT
|
||||||
id,
|
id,
|
||||||
|
|
@ -132,9 +139,9 @@ LIMIT $1 OFFSET $2`, tabela, cond)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
respostas := []RespostaPainel{}
|
respostas := []contratos.RespostaPainel{}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var r RespostaPainel
|
var r contratos.RespostaPainel
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&r.ID,
|
&r.ID,
|
||||||
&r.RespondidoEm,
|
&r.RespondidoEm,
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
"e-li.nps/internal/db"
|
"e-li.nps/internal/db"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
@ -52,6 +53,10 @@ func (s *Store) EnsureTableForProduto(ctx context.Context, produtoNome string) (
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) HasRespostaValidaRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
func (s *Store) HasRespostaValidaRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(table) {
|
||||||
|
return false, fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM %s
|
FROM %s
|
||||||
|
|
@ -72,6 +77,10 @@ LIMIT 1`, table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) HasPedidoEmAbertoRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
func (s *Store) HasPedidoEmAbertoRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(table) {
|
||||||
|
return false, fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM %s
|
FROM %s
|
||||||
|
|
@ -90,7 +99,11 @@ LIMIT 1`, table)
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) CreatePedido(ctx context.Context, table string, in PedidoInput, r *http.Request) (string, error) {
|
func (s *Store) CreatePedido(ctx context.Context, table string, in contratos.PedidoInput, r *http.Request) (string, error) {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(table) {
|
||||||
|
return "", fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
INSERT INTO %s (
|
INSERT INTO %s (
|
||||||
produto_nome,
|
produto_nome,
|
||||||
|
|
@ -110,20 +123,28 @@ RETURNING id`, table)
|
||||||
return id, err
|
return id, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) GetRegistro(ctx context.Context, table, id string) (Registro, error) {
|
func (s *Store) GetRegistro(ctx context.Context, table, id string) (contratos.Registro, error) {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(table) {
|
||||||
|
return contratos.Registro{}, fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
SELECT id, produto_nome, status, nota, justificativa, pedido_criado_em, respondido_em
|
SELECT id, produto_nome, status, nota, justificativa, pedido_criado_em, respondido_em
|
||||||
FROM %s
|
FROM %s
|
||||||
WHERE id=$1`, table)
|
WHERE id=$1`, table)
|
||||||
|
|
||||||
var reg Registro
|
var reg contratos.Registro
|
||||||
err := s.pool.QueryRow(ctx, q, id).Scan(
|
err := s.pool.QueryRow(ctx, q, id).Scan(
|
||||||
®.ID, ®.ProdutoNome, ®.Status, ®.Nota, ®.Justificativa, ®.PedidoCriadoEm, ®.RespondidoEm,
|
®.ID, ®.ProdutoNome, ®.Status, ®.Nota, ®.Justificativa, ®.PedidoCriadoEm, ®.RespondidoEm,
|
||||||
)
|
)
|
||||||
return reg, err
|
return reg, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) PatchRegistro(ctx context.Context, table, id string, in PatchInput) error {
|
func (s *Store) PatchRegistro(ctx context.Context, table, id string, in contratos.PatchInput) error {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(table) {
|
||||||
|
return fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
// UPDATE único com campos opcionais.
|
// UPDATE único com campos opcionais.
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
UPDATE %s
|
UPDATE %s
|
||||||
|
|
@ -140,12 +161,16 @@ WHERE id=$1`, table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) TouchAtualizadoEm(ctx context.Context, table, id string) error {
|
func (s *Store) TouchAtualizadoEm(ctx context.Context, table, id string) error {
|
||||||
|
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
|
||||||
|
if !db.TableNameValido(table) {
|
||||||
|
return fmt.Errorf("tabela invalida")
|
||||||
|
}
|
||||||
q := fmt.Sprintf(`UPDATE %s SET atualizado_em=now() WHERE id=$1`, table)
|
q := fmt.Sprintf(`UPDATE %s SET atualizado_em=now() WHERE id=$1`, table)
|
||||||
_, err := s.pool.Exec(ctx, q, id)
|
_, err := s.pool.Exec(ctx, q, id)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) CooldownSuggested(reg Registro) time.Duration {
|
func (s *Store) CooldownSuggested(reg contratos.Registro) time.Duration {
|
||||||
// Não é usado pelo servidor hoje; fica como helper se precisarmos.
|
// Não é usado pelo servidor hoje; fica como helper se precisarmos.
|
||||||
if reg.Status == "respondido" {
|
if reg.Status == "respondido" {
|
||||||
return 45 * 24 * time.Hour
|
return 45 * 24 * time.Hour
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,10 @@ package elinps
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"html/template"
|
"html/template"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TemplateRenderer struct {
|
type TemplateRenderer struct {
|
||||||
|
|
@ -12,11 +15,15 @@ type TemplateRenderer struct {
|
||||||
func NewTemplateRenderer(t *template.Template) *TemplateRenderer { return &TemplateRenderer{t: t} }
|
func NewTemplateRenderer(t *template.Template) *TemplateRenderer { return &TemplateRenderer{t: t} }
|
||||||
|
|
||||||
func (r *TemplateRenderer) Render(w http.ResponseWriter, name string, data any) {
|
func (r *TemplateRenderer) Render(w http.ResponseWriter, name string, data any) {
|
||||||
_ = r.t.ExecuteTemplate(w, name, data)
|
if err := r.t.ExecuteTemplate(w, name, data); err != nil {
|
||||||
|
// Não expomos detalhes do erro para o usuário (pode conter paths/etc).
|
||||||
|
// Mas registramos para depuração.
|
||||||
|
slog.Error("erro ao renderizar template", "template", name, "err", err)
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
w.Write([]byte("erro ao renderizar"))
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormPageData struct {
|
// Alias para manter as chamadas concisas dentro do pacote elinps.
|
||||||
Produto string
|
type FormPageData = contratos.FormPageData
|
||||||
ID string
|
|
||||||
Reg Registro
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,8 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func mustParseTemplates() *template.Template {
|
func mustParseTemplates() *template.Template {
|
||||||
// Local filesystem parsing (keeps the repo simple).
|
// Parse de templates via filesystem local (mantém o repositório simples).
|
||||||
// If you want a single-binary deploy, we can switch to go:embed by moving
|
// Se precisarmos de deploy single-binary, podemos migrar para go:embed.
|
||||||
// templates into internal/elinps and embedding without "..".
|
|
||||||
funcs := template.FuncMap{
|
funcs := template.FuncMap{
|
||||||
"seq": func(start, end int) []int {
|
"seq": func(start, end int) []int {
|
||||||
if end < start {
|
if end < start {
|
||||||
|
|
@ -25,7 +24,7 @@ func mustParseTemplates() *template.Template {
|
||||||
return ptr != nil && *ptr == v
|
return ptr != nil && *ptr == v
|
||||||
},
|
},
|
||||||
"produtoLabel": func(produto string) string {
|
"produtoLabel": func(produto string) string {
|
||||||
// Best-effort label from normalized produto.
|
// Label "amigável" a partir do produto normalizado.
|
||||||
p := strings.ReplaceAll(produto, "_", " ")
|
p := strings.ReplaceAll(produto, "_", " ")
|
||||||
parts := strings.Fields(p)
|
parts := strings.Fields(p)
|
||||||
for i := range parts {
|
for i := range parts {
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"e-li.nps/internal/contratos"
|
||||||
)
|
)
|
||||||
|
|
||||||
var emailRe = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
var emailRe = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
||||||
|
|
@ -12,7 +14,7 @@ func normalizeEmail(s string) string {
|
||||||
return strings.ToLower(strings.TrimSpace(s))
|
return strings.ToLower(strings.TrimSpace(s))
|
||||||
}
|
}
|
||||||
|
|
||||||
func ValidatePedidoInput(in *PedidoInput) error {
|
func ValidatePedidoInput(in *contratos.PedidoInput) error {
|
||||||
in.ProdutoNome = strings.TrimSpace(in.ProdutoNome)
|
in.ProdutoNome = strings.TrimSpace(in.ProdutoNome)
|
||||||
in.InquilinoCodigo = strings.TrimSpace(in.InquilinoCodigo)
|
in.InquilinoCodigo = strings.TrimSpace(in.InquilinoCodigo)
|
||||||
in.InquilinoNome = strings.TrimSpace(in.InquilinoNome)
|
in.InquilinoNome = strings.TrimSpace(in.InquilinoNome)
|
||||||
|
|
@ -49,7 +51,7 @@ func ValidatePedidoInput(in *PedidoInput) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ValidatePatchInput(in *PatchInput) error {
|
func ValidatePatchInput(in *contratos.PatchInput) error {
|
||||||
if in.Nota != nil {
|
if in.Nota != nil {
|
||||||
if *in.Nota < 1 || *in.Nota > 10 {
|
if *in.Nota < 1 || *in.Nota > 10 {
|
||||||
return errors.New("nota invalida")
|
return errors.New("nota invalida")
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,14 @@
|
||||||
(function(){
|
(function(){
|
||||||
|
// Widget NPS (arquivo único).
|
||||||
|
//
|
||||||
|
// Regras do projeto (.agent):
|
||||||
|
// - sem dependências externas
|
||||||
|
// - fail-closed
|
||||||
|
// - contratos públicos estáveis
|
||||||
|
//
|
||||||
|
// Evolução: regras de negócio do cliente foram movidas para WASM (Go)
|
||||||
|
// sempre que possível. O backend continua sendo a autoridade.
|
||||||
|
|
||||||
const DEFAULTS = {
|
const DEFAULTS = {
|
||||||
apiBase: '',
|
apiBase: '',
|
||||||
cooldownHours: 24,
|
cooldownHours: 24,
|
||||||
|
|
@ -8,51 +18,55 @@
|
||||||
data_minima_abertura: '',
|
data_minima_abertura: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseDataMinima(s){
|
|
||||||
// Aceita somente ISO (data) YYYY-MM-DD.
|
|
||||||
// Retorna um Date no início do dia (00:00) no horário local.
|
|
||||||
const v = String(s || '').trim();
|
|
||||||
if(!v) return null;
|
|
||||||
const m = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(v);
|
|
||||||
if(!m) return null;
|
|
||||||
const ano = Number(m[1]);
|
|
||||||
const mes = Number(m[2]);
|
|
||||||
const dia = Number(m[3]);
|
|
||||||
if(!ano || mes < 1 || mes > 12 || dia < 1 || dia > 31) return null;
|
|
||||||
return new Date(ano, mes-1, dia, 0, 0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
function antesDaDataMinima(cfg){
|
|
||||||
const d = parseDataMinima(cfg.data_minima_abertura);
|
|
||||||
if(!d) return false;
|
|
||||||
return new Date() < d;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeEmail(email){
|
|
||||||
return String(email || '').trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function cooldownKey(produto, inquilino, usuarioCodigo){
|
function cooldownKey(produto, inquilino, usuarioCodigo){
|
||||||
// Prefixo de storage atualizado para o novo nome do projeto.
|
// Prefixo de storage atualizado para o novo nome do projeto.
|
||||||
return `eli-nps:cooldown:${produto}:${inquilino}:${usuarioCodigo}`;
|
return `eli-nps:cooldown:${produto}:${inquilino}:${usuarioCodigo}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function nowMs(){ return Date.now(); }
|
// ------------------------------------------------------------------
|
||||||
|
// WASM (Go)
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
function withinCooldown(key){
|
async function carregarWasm(apiBase){
|
||||||
|
// fail-closed: se o WASM não carregar, o widget não abre.
|
||||||
|
if(window.__eli_nps_wasm_ready) return true;
|
||||||
|
if(window.__eli_nps_wasm_loading) return window.__eli_nps_wasm_loading;
|
||||||
|
|
||||||
|
window.__eli_nps_wasm_loading = (async function(){
|
||||||
try{
|
try{
|
||||||
const v = localStorage.getItem(key);
|
// wasm_exec.js expõe global `Go`.
|
||||||
if(!v) return false;
|
if(!window.Go){
|
||||||
const obj = JSON.parse(v);
|
await carregarScript(`${apiBase}/static/wasm_exec.js`);
|
||||||
return obj && obj.until && nowMs() < obj.until;
|
|
||||||
}catch(e){ return false; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function setCooldown(key, hours){
|
const go = new Go();
|
||||||
|
const res = await fetch(`${apiBase}/static/e-li.nps.wasm`, {cache: 'no-cache'});
|
||||||
|
if(!res.ok) return false;
|
||||||
|
const bytes = await res.arrayBuffer();
|
||||||
|
const {instance} = await WebAssembly.instantiate(bytes, go.importObject);
|
||||||
|
go.run(instance);
|
||||||
|
return !!window.__eli_nps_wasm_ready;
|
||||||
|
}catch(e){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return window.__eli_nps_wasm_loading;
|
||||||
|
}
|
||||||
|
|
||||||
|
function carregarScript(src){
|
||||||
|
return new Promise(function(resolve, reject){
|
||||||
try{
|
try{
|
||||||
const until = nowMs() + hours*3600*1000;
|
const s = document.createElement('script');
|
||||||
localStorage.setItem(key, JSON.stringify({until}));
|
s.src = src;
|
||||||
}catch(e){}
|
s.async = true;
|
||||||
|
s.onload = function(){ resolve(); };
|
||||||
|
s.onerror = function(){ reject(new Error('script_fail')); };
|
||||||
|
document.head.appendChild(s);
|
||||||
|
}catch(e){
|
||||||
|
reject(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function createModal(){
|
function createModal(){
|
||||||
|
|
@ -133,71 +147,43 @@
|
||||||
init: async function(opts){
|
init: async function(opts){
|
||||||
const cfg = Object.assign({}, DEFAULTS, opts || {});
|
const cfg = Object.assign({}, DEFAULTS, opts || {});
|
||||||
|
|
||||||
// Bloqueio por data mínima (feature flag simples).
|
// Carrega WASM (Go). Sem WASM, não abrimos o widget (fail-closed).
|
||||||
// Ex.: não abrir modal antes de 2026-01-01.
|
const okWasm = await carregarWasm(cfg.apiBase);
|
||||||
if(antesDaDataMinima(cfg)){
|
if(!okWasm) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// produto_nome pode ser qualquer string (ex.: "e-licencie", "Cachaça & Churras").
|
// Pré-validação e preparação do payload no WASM.
|
||||||
// Regra do projeto: o tratamento/normalização de caracteres deve ser feito
|
const pre = window.__eli_nps_wasm_preflight(cfg);
|
||||||
// apenas no backend, exclusivamente para nome de tabela/rotas.
|
if(!pre || !pre.ok) return;
|
||||||
const produtoNome = String(cfg.produto_nome || '').trim();
|
|
||||||
const inquilino = String(cfg.inquilino_codigo || '').trim();
|
|
||||||
const usuarioCodigo = String(cfg.usuario_codigo || '').trim();
|
|
||||||
const email = normalizeEmail(cfg.usuario_email);
|
|
||||||
|
|
||||||
// controle de exibição: produto + inquilino_codigo + usuario_codigo
|
// Cooldown visual no browser (WASM faz storage best-effort).
|
||||||
if(!produtoNome || !inquilino || !usuarioCodigo){
|
// A chave do cooldown é best-effort e não participa de regra de segurança.
|
||||||
return; // missing required context
|
if(window.__eli_nps_wasm_cooldown_ativo(pre.chave_cooldown)) return;
|
||||||
}
|
|
||||||
|
|
||||||
// A chave do cooldown é “best-effort” e não participa de nenhuma regra
|
|
||||||
// de segurança. Mantemos o produto como foi informado.
|
|
||||||
const chaveCooldown = cooldownKey(produtoNome, inquilino, usuarioCodigo);
|
|
||||||
if(withinCooldown(chaveCooldown)) return;
|
|
||||||
|
|
||||||
// Enviamos exatamente o produto_nome informado.
|
|
||||||
const payload = {
|
|
||||||
produto_nome: produtoNome,
|
|
||||||
inquilino_codigo: inquilino,
|
|
||||||
inquilino_nome: String(cfg.inquilino_nome || '').trim(),
|
|
||||||
usuario_codigo: usuarioCodigo,
|
|
||||||
usuario_nome: String(cfg.usuario_nome || '').trim(),
|
|
||||||
usuario_telefone: String(cfg.usuario_telefone || '').trim(),
|
|
||||||
usuario_email: email,
|
|
||||||
};
|
|
||||||
|
|
||||||
let data;
|
let data;
|
||||||
try{
|
try{
|
||||||
const res = await postJSON(`${cfg.apiBase}/api/e-li.nps/pedido`, payload);
|
const res = await postJSON(`${cfg.apiBase}/api/e-li.nps/pedido`, pre.payload);
|
||||||
if(!res.ok) return; // fail-closed
|
if(!res.ok) return; // fail-closed
|
||||||
data = await res.json();
|
data = await res.json();
|
||||||
}catch(e){
|
}catch(e){
|
||||||
return; // fail-closed
|
return; // fail-closed
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!data || !data.pode_abrir || !data.id){
|
const dec = window.__eli_nps_wasm_decidir(cfg, data);
|
||||||
// small cooldown to avoid flicker if backend keeps rejecting
|
if(!dec || !dec.abrir){
|
||||||
setCooldown(chaveCooldown, cfg.cooldownHours);
|
// cooldown para evitar flicker se o backend seguir rejeitando.
|
||||||
return;
|
if(dec && dec.aplicar_cooldown){
|
||||||
|
window.__eli_nps_wasm_set_cooldown(pre.chave_cooldown, dec.cooldown_ate_ms);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Backend can return normalized product; use it for building iframe URL.
|
|
||||||
const produtoRota = data.produto;
|
|
||||||
if(!produtoRota){
|
|
||||||
// fail-closed (não dá pra montar URL segura)
|
|
||||||
setCooldown(chaveCooldown, cfg.cooldownHours);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const modal = createModal();
|
const modal = createModal();
|
||||||
const iframe = document.createElement('iframe');
|
const iframe = document.createElement('iframe');
|
||||||
iframe.src = `${cfg.apiBase}/e-li.nps/${produtoRota}/${data.id}/form`;
|
iframe.src = `${cfg.apiBase}/e-li.nps/${dec.produto_rota}/${dec.id}/form`;
|
||||||
modal.panel.appendChild(iframe);
|
modal.panel.appendChild(iframe);
|
||||||
|
|
||||||
// Visual cooldown so it doesn't keep popping (even if user closes).
|
// Visual cooldown so it doesn't keep popping (even if user closes).
|
||||||
setCooldown(chaveCooldown, cfg.cooldownHours);
|
window.__eli_nps_wasm_set_cooldown(pre.chave_cooldown, dec.cooldown_ate_ms);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
|
|
|
||||||
BIN
web/static/e-li.nps.wasm
Executable file
BIN
web/static/e-li.nps.wasm
Executable file
Binary file not shown.
BIN
web/static/favicon.ico
Normal file
BIN
web/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
575
web/static/wasm_exec.js
Normal file
575
web/static/wasm_exec.js
Normal file
|
|
@ -0,0 +1,575 @@
|
||||||
|
// Copyright 2018 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
(() => {
|
||||||
|
const enosys = () => {
|
||||||
|
const err = new Error("not implemented");
|
||||||
|
err.code = "ENOSYS";
|
||||||
|
return err;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!globalThis.fs) {
|
||||||
|
let outputBuf = "";
|
||||||
|
globalThis.fs = {
|
||||||
|
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
|
||||||
|
writeSync(fd, buf) {
|
||||||
|
outputBuf += decoder.decode(buf);
|
||||||
|
const nl = outputBuf.lastIndexOf("\n");
|
||||||
|
if (nl != -1) {
|
||||||
|
console.log(outputBuf.substring(0, nl));
|
||||||
|
outputBuf = outputBuf.substring(nl + 1);
|
||||||
|
}
|
||||||
|
return buf.length;
|
||||||
|
},
|
||||||
|
write(fd, buf, offset, length, position, callback) {
|
||||||
|
if (offset !== 0 || length !== buf.length || position !== null) {
|
||||||
|
callback(enosys());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const n = this.writeSync(fd, buf);
|
||||||
|
callback(null, n);
|
||||||
|
},
|
||||||
|
chmod(path, mode, callback) { callback(enosys()); },
|
||||||
|
chown(path, uid, gid, callback) { callback(enosys()); },
|
||||||
|
close(fd, callback) { callback(enosys()); },
|
||||||
|
fchmod(fd, mode, callback) { callback(enosys()); },
|
||||||
|
fchown(fd, uid, gid, callback) { callback(enosys()); },
|
||||||
|
fstat(fd, callback) { callback(enosys()); },
|
||||||
|
fsync(fd, callback) { callback(null); },
|
||||||
|
ftruncate(fd, length, callback) { callback(enosys()); },
|
||||||
|
lchown(path, uid, gid, callback) { callback(enosys()); },
|
||||||
|
link(path, link, callback) { callback(enosys()); },
|
||||||
|
lstat(path, callback) { callback(enosys()); },
|
||||||
|
mkdir(path, perm, callback) { callback(enosys()); },
|
||||||
|
open(path, flags, mode, callback) { callback(enosys()); },
|
||||||
|
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
|
||||||
|
readdir(path, callback) { callback(enosys()); },
|
||||||
|
readlink(path, callback) { callback(enosys()); },
|
||||||
|
rename(from, to, callback) { callback(enosys()); },
|
||||||
|
rmdir(path, callback) { callback(enosys()); },
|
||||||
|
stat(path, callback) { callback(enosys()); },
|
||||||
|
symlink(path, link, callback) { callback(enosys()); },
|
||||||
|
truncate(path, length, callback) { callback(enosys()); },
|
||||||
|
unlink(path, callback) { callback(enosys()); },
|
||||||
|
utimes(path, atime, mtime, callback) { callback(enosys()); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.process) {
|
||||||
|
globalThis.process = {
|
||||||
|
getuid() { return -1; },
|
||||||
|
getgid() { return -1; },
|
||||||
|
geteuid() { return -1; },
|
||||||
|
getegid() { return -1; },
|
||||||
|
getgroups() { throw enosys(); },
|
||||||
|
pid: -1,
|
||||||
|
ppid: -1,
|
||||||
|
umask() { throw enosys(); },
|
||||||
|
cwd() { throw enosys(); },
|
||||||
|
chdir() { throw enosys(); },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.path) {
|
||||||
|
globalThis.path = {
|
||||||
|
resolve(...pathSegments) {
|
||||||
|
return pathSegments.join("/");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.crypto) {
|
||||||
|
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.performance) {
|
||||||
|
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.TextEncoder) {
|
||||||
|
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.TextDecoder) {
|
||||||
|
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const encoder = new TextEncoder("utf-8");
|
||||||
|
const decoder = new TextDecoder("utf-8");
|
||||||
|
|
||||||
|
globalThis.Go = class {
|
||||||
|
constructor() {
|
||||||
|
this.argv = ["js"];
|
||||||
|
this.env = {};
|
||||||
|
this.exit = (code) => {
|
||||||
|
if (code !== 0) {
|
||||||
|
console.warn("exit code:", code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this._exitPromise = new Promise((resolve) => {
|
||||||
|
this._resolveExitPromise = resolve;
|
||||||
|
});
|
||||||
|
this._pendingEvent = null;
|
||||||
|
this._scheduledTimeouts = new Map();
|
||||||
|
this._nextCallbackTimeoutID = 1;
|
||||||
|
|
||||||
|
const setInt64 = (addr, v) => {
|
||||||
|
this.mem.setUint32(addr + 0, v, true);
|
||||||
|
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const setInt32 = (addr, v) => {
|
||||||
|
this.mem.setUint32(addr + 0, v, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getInt64 = (addr) => {
|
||||||
|
const low = this.mem.getUint32(addr + 0, true);
|
||||||
|
const high = this.mem.getInt32(addr + 4, true);
|
||||||
|
return low + high * 4294967296;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadValue = (addr) => {
|
||||||
|
const f = this.mem.getFloat64(addr, true);
|
||||||
|
if (f === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (!isNaN(f)) {
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = this.mem.getUint32(addr, true);
|
||||||
|
return this._values[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeValue = (addr, v) => {
|
||||||
|
const nanHead = 0x7FF80000;
|
||||||
|
|
||||||
|
if (typeof v === "number" && v !== 0) {
|
||||||
|
if (isNaN(v)) {
|
||||||
|
this.mem.setUint32(addr + 4, nanHead, true);
|
||||||
|
this.mem.setUint32(addr, 0, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.mem.setFloat64(addr, v, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v === undefined) {
|
||||||
|
this.mem.setFloat64(addr, 0, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = this._ids.get(v);
|
||||||
|
if (id === undefined) {
|
||||||
|
id = this._idPool.pop();
|
||||||
|
if (id === undefined) {
|
||||||
|
id = this._values.length;
|
||||||
|
}
|
||||||
|
this._values[id] = v;
|
||||||
|
this._goRefCounts[id] = 0;
|
||||||
|
this._ids.set(v, id);
|
||||||
|
}
|
||||||
|
this._goRefCounts[id]++;
|
||||||
|
let typeFlag = 0;
|
||||||
|
switch (typeof v) {
|
||||||
|
case "object":
|
||||||
|
if (v !== null) {
|
||||||
|
typeFlag = 1;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "string":
|
||||||
|
typeFlag = 2;
|
||||||
|
break;
|
||||||
|
case "symbol":
|
||||||
|
typeFlag = 3;
|
||||||
|
break;
|
||||||
|
case "function":
|
||||||
|
typeFlag = 4;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
|
||||||
|
this.mem.setUint32(addr, id, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadSlice = (addr) => {
|
||||||
|
const array = getInt64(addr + 0);
|
||||||
|
const len = getInt64(addr + 8);
|
||||||
|
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadSliceOfValues = (addr) => {
|
||||||
|
const array = getInt64(addr + 0);
|
||||||
|
const len = getInt64(addr + 8);
|
||||||
|
const a = new Array(len);
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
a[i] = loadValue(array + i * 8);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadString = (addr) => {
|
||||||
|
const saddr = getInt64(addr + 0);
|
||||||
|
const len = getInt64(addr + 8);
|
||||||
|
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
|
||||||
|
}
|
||||||
|
|
||||||
|
const testCallExport = (a, b) => {
|
||||||
|
this._inst.exports.testExport0();
|
||||||
|
return this._inst.exports.testExport(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeOrigin = Date.now() - performance.now();
|
||||||
|
this.importObject = {
|
||||||
|
_gotest: {
|
||||||
|
add: (a, b) => a + b,
|
||||||
|
callExport: testCallExport,
|
||||||
|
},
|
||||||
|
gojs: {
|
||||||
|
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
|
||||||
|
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
|
||||||
|
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
|
||||||
|
// This changes the SP, thus we have to update the SP used by the imported function.
|
||||||
|
|
||||||
|
// func wasmExit(code int32)
|
||||||
|
"runtime.wasmExit": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const code = this.mem.getInt32(sp + 8, true);
|
||||||
|
this.exited = true;
|
||||||
|
delete this._inst;
|
||||||
|
delete this._values;
|
||||||
|
delete this._goRefCounts;
|
||||||
|
delete this._ids;
|
||||||
|
delete this._idPool;
|
||||||
|
this.exit(code);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
||||||
|
"runtime.wasmWrite": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const fd = getInt64(sp + 8);
|
||||||
|
const p = getInt64(sp + 16);
|
||||||
|
const n = this.mem.getInt32(sp + 24, true);
|
||||||
|
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func resetMemoryDataView()
|
||||||
|
"runtime.resetMemoryDataView": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func nanotime1() int64
|
||||||
|
"runtime.nanotime1": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func walltime() (sec int64, nsec int32)
|
||||||
|
"runtime.walltime": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const msec = (new Date).getTime();
|
||||||
|
setInt64(sp + 8, msec / 1000);
|
||||||
|
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func scheduleTimeoutEvent(delay int64) int32
|
||||||
|
"runtime.scheduleTimeoutEvent": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const id = this._nextCallbackTimeoutID;
|
||||||
|
this._nextCallbackTimeoutID++;
|
||||||
|
this._scheduledTimeouts.set(id, setTimeout(
|
||||||
|
() => {
|
||||||
|
this._resume();
|
||||||
|
while (this._scheduledTimeouts.has(id)) {
|
||||||
|
// for some reason Go failed to register the timeout event, log and try again
|
||||||
|
// (temporary workaround for https://github.com/golang/go/issues/28975)
|
||||||
|
console.warn("scheduleTimeoutEvent: missed timeout event");
|
||||||
|
this._resume();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
getInt64(sp + 8),
|
||||||
|
));
|
||||||
|
this.mem.setInt32(sp + 16, id, true);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func clearTimeoutEvent(id int32)
|
||||||
|
"runtime.clearTimeoutEvent": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const id = this.mem.getInt32(sp + 8, true);
|
||||||
|
clearTimeout(this._scheduledTimeouts.get(id));
|
||||||
|
this._scheduledTimeouts.delete(id);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func getRandomData(r []byte)
|
||||||
|
"runtime.getRandomData": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
crypto.getRandomValues(loadSlice(sp + 8));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func finalizeRef(v ref)
|
||||||
|
"syscall/js.finalizeRef": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const id = this.mem.getUint32(sp + 8, true);
|
||||||
|
this._goRefCounts[id]--;
|
||||||
|
if (this._goRefCounts[id] === 0) {
|
||||||
|
const v = this._values[id];
|
||||||
|
this._values[id] = null;
|
||||||
|
this._ids.delete(v);
|
||||||
|
this._idPool.push(id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func stringVal(value string) ref
|
||||||
|
"syscall/js.stringVal": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
storeValue(sp + 24, loadString(sp + 8));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueGet(v ref, p string) ref
|
||||||
|
"syscall/js.valueGet": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 32, result);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueSet(v ref, p string, x ref)
|
||||||
|
"syscall/js.valueSet": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueDelete(v ref, p string)
|
||||||
|
"syscall/js.valueDelete": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueIndex(v ref, i int) ref
|
||||||
|
"syscall/js.valueIndex": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
||||||
|
},
|
||||||
|
|
||||||
|
// valueSetIndex(v ref, i int, x ref)
|
||||||
|
"syscall/js.valueSetIndex": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueCall(v ref, m string, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueCall": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const m = Reflect.get(v, loadString(sp + 16));
|
||||||
|
const args = loadSliceOfValues(sp + 32);
|
||||||
|
const result = Reflect.apply(m, v, args);
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 56, result);
|
||||||
|
this.mem.setUint8(sp + 64, 1);
|
||||||
|
} catch (err) {
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 56, err);
|
||||||
|
this.mem.setUint8(sp + 64, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueInvoke(v ref, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueInvoke": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const args = loadSliceOfValues(sp + 16);
|
||||||
|
const result = Reflect.apply(v, undefined, args);
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, result);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
} catch (err) {
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, err);
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueNew(v ref, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueNew": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const args = loadSliceOfValues(sp + 16);
|
||||||
|
const result = Reflect.construct(v, args);
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, result);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
} catch (err) {
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, err);
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueLength(v ref) int
|
||||||
|
"syscall/js.valueLength": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
||||||
|
},
|
||||||
|
|
||||||
|
// valuePrepareString(v ref) (ref, int)
|
||||||
|
"syscall/js.valuePrepareString": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const str = encoder.encode(String(loadValue(sp + 8)));
|
||||||
|
storeValue(sp + 16, str);
|
||||||
|
setInt64(sp + 24, str.length);
|
||||||
|
},
|
||||||
|
|
||||||
|
// valueLoadString(v ref, b []byte)
|
||||||
|
"syscall/js.valueLoadString": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const str = loadValue(sp + 8);
|
||||||
|
loadSlice(sp + 16).set(str);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueInstanceOf(v ref, t ref) bool
|
||||||
|
"syscall/js.valueInstanceOf": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
||||||
|
"syscall/js.copyBytesToGo": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const dst = loadSlice(sp + 8);
|
||||||
|
const src = loadValue(sp + 32);
|
||||||
|
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toCopy = src.subarray(0, dst.length);
|
||||||
|
dst.set(toCopy);
|
||||||
|
setInt64(sp + 40, toCopy.length);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
||||||
|
"syscall/js.copyBytesToJS": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const dst = loadValue(sp + 8);
|
||||||
|
const src = loadSlice(sp + 16);
|
||||||
|
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toCopy = src.subarray(0, dst.length);
|
||||||
|
dst.set(toCopy);
|
||||||
|
setInt64(sp + 40, toCopy.length);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
"debug": (value) => {
|
||||||
|
console.log(value);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(instance) {
|
||||||
|
if (!(instance instanceof WebAssembly.Instance)) {
|
||||||
|
throw new Error("Go.run: WebAssembly.Instance expected");
|
||||||
|
}
|
||||||
|
this._inst = instance;
|
||||||
|
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||||
|
this._values = [ // JS values that Go currently has references to, indexed by reference id
|
||||||
|
NaN,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
globalThis,
|
||||||
|
this,
|
||||||
|
];
|
||||||
|
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
|
||||||
|
this._ids = new Map([ // mapping from JS values to reference ids
|
||||||
|
[0, 1],
|
||||||
|
[null, 2],
|
||||||
|
[true, 3],
|
||||||
|
[false, 4],
|
||||||
|
[globalThis, 5],
|
||||||
|
[this, 6],
|
||||||
|
]);
|
||||||
|
this._idPool = []; // unused ids that have been garbage collected
|
||||||
|
this.exited = false; // whether the Go program has exited
|
||||||
|
|
||||||
|
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
|
||||||
|
let offset = 4096;
|
||||||
|
|
||||||
|
const strPtr = (str) => {
|
||||||
|
const ptr = offset;
|
||||||
|
const bytes = encoder.encode(str + "\0");
|
||||||
|
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
|
||||||
|
offset += bytes.length;
|
||||||
|
if (offset % 8 !== 0) {
|
||||||
|
offset += 8 - (offset % 8);
|
||||||
|
}
|
||||||
|
return ptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
const argc = this.argv.length;
|
||||||
|
|
||||||
|
const argvPtrs = [];
|
||||||
|
this.argv.forEach((arg) => {
|
||||||
|
argvPtrs.push(strPtr(arg));
|
||||||
|
});
|
||||||
|
argvPtrs.push(0);
|
||||||
|
|
||||||
|
const keys = Object.keys(this.env).sort();
|
||||||
|
keys.forEach((key) => {
|
||||||
|
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
|
||||||
|
});
|
||||||
|
argvPtrs.push(0);
|
||||||
|
|
||||||
|
const argv = offset;
|
||||||
|
argvPtrs.forEach((ptr) => {
|
||||||
|
this.mem.setUint32(offset, ptr, true);
|
||||||
|
this.mem.setUint32(offset + 4, 0, true);
|
||||||
|
offset += 8;
|
||||||
|
});
|
||||||
|
|
||||||
|
// The linker guarantees global data starts from at least wasmMinDataAddr.
|
||||||
|
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
|
||||||
|
const wasmMinDataAddr = 4096 + 8192;
|
||||||
|
if (offset >= wasmMinDataAddr) {
|
||||||
|
throw new Error("total length of command line and environment variables exceeds limit");
|
||||||
|
}
|
||||||
|
|
||||||
|
this._inst.exports.run(argc, argv);
|
||||||
|
if (this.exited) {
|
||||||
|
this._resolveExitPromise();
|
||||||
|
}
|
||||||
|
await this._exitPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
_resume() {
|
||||||
|
if (this.exited) {
|
||||||
|
throw new Error("Go program has already exited");
|
||||||
|
}
|
||||||
|
this._inst.exports.resume();
|
||||||
|
if (this.exited) {
|
||||||
|
this._resolveExitPromise();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_makeFuncWrapper(id) {
|
||||||
|
const go = this;
|
||||||
|
return function () {
|
||||||
|
const event = { id: id, this: this, args: arguments };
|
||||||
|
go._pendingEvent = event;
|
||||||
|
go._resume();
|
||||||
|
return event.result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
{{define "form_inner.html"}}
|
{{define "form_inner.html"}}
|
||||||
{{/* This block can be swapped by HTMX (target #eli-nps-modal-body) */}}
|
{{/* Este bloco pode ser trocado pelo HTMX (target #eli-nps-modal-body) */}}
|
||||||
{{if eq .Reg.Status "respondido"}}
|
{{if eq .Reg.Status "respondido"}}
|
||||||
<div class="eli-nps-ok">
|
<div class="eli-nps-ok">
|
||||||
<p class="eli-nps-title">Obrigado!</p>
|
<p class="eli-nps-title">Obrigado!</p>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue