Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support export jit in the frontend (#20491)
ecmadao34295a257f23
diff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.goindex 9c455853ed..72add37de6 100644--- a/backend/api/v1/access_grant_service.go+++ b/backend/api/v1/access_grant_service.go@@ -430,6 +430,7 @@ func convertToAccessGrant(msg *store.AccessGrantMessage) *v1pb.AccessGrant {ag.Query = p.Queryag.Unmask = p.Unmaskag.Export = p.Export+ ag.Reason = p.Reasonif p.IssueId != 0 {ag.Issue = common.FormatIssue(msg.ProjectID, p.IssueId)}diff --git a/backend/api/v1/access_grant_service_test.go b/backend/api/v1/access_grant_service_test.goindex 74ce4956ad..9f3aa4fa8c 100644--- a/backend/api/v1/access_grant_service_test.go+++ b/backend/api/v1/access_grant_service_test.go@@ -3,10 +3,12 @@ package v1import ("context""testing"+ "time""github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store")func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineWriteStatements(t *testing.T) {@@ -78,3 +80,54 @@ func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineInvalidStatementsrequire.Error(t, err)require.False(t, readOnly)}++// TestConvertToAccessGrantPropagatesPayloadFields pins the fix that+// `Reason` (alongside the existing Targets / Query / Unmask / Export)+// must be copied from the store payload onto the v1 message — otherwise+// frontend tooltips and audit displays that depend on the user-typed+// reason silently render empty.+func TestConvertToAccessGrantPropagatesPayloadFields(t *testing.T) {+ expire := time.Date(2026, 6, 30, 12, 0, 0, 0, time.UTC)+ msg := &store.AccessGrantMessage{+ ProjectID: "proj",+ ID: "ag1",+ Creator: "[email protected]",+ Status: storepb.AccessGrant_ACTIVE,+ ExpireTime: &expire,+ Payload: &storepb.AccessGrantPayload{+ Targets: []string{"instances/inst/databases/db"},+ Query: "SELECT * FROM t",+ Unmask: true,+ Export: true,+ Reason: "investigating PR-1234",+ },+ }++ ag := convertToAccessGrant(msg)++ require.Equal(t, []string{"instances/inst/databases/db"}, ag.Targets)+ require.Equal(t, "SELECT * FROM t", ag.Query)+ require.True(t, ag.Unmask)+ require.True(t, ag.Export)+ require.Equal(t, "investigating PR-1234", ag.Reason)+}++// TestConvertToAccessGrantNilPayloadIsSafe guards the `if p := msg.Payload; p != nil`+// branch — a nil payload must not panic and payload-sourced fields stay zero.+func TestConvertToAccessGrantNilPayloadIsSafe(t *testing.T) {+ msg := &store.AccessGrantMessage{+ ProjectID: "proj",+ ID: "ag1",+ Creator: "[email protected]",+ Status: storepb.AccessGrant_ACTIVE,+ Payload: nil,+ }++ ag := convertToAccessGrant(msg)++ require.Empty(t, ag.Targets)+ require.Empty(t, ag.Query)+ require.False(t, ag.Unmask)+ require.False(t, ag.Export)+ require.Empty(t, ag.Reason)+}diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 2e53406a96..6f4575e450 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -184,28 +184,15 @@ func buildExportQueryContext(restriction *store.EffectiveQueryDataPolicy, userEmreturn qc}-// accessOperation distinguishes between Query and Export so preCheckAccess can pick-// a grant whose capabilities actually authorize the operation in question.-type accessOperation int--const (- accessOperationQuery accessOperation = iota- accessOperationExport-)--// preCheckAccess finds and returns the best matching active access grant for the-// requested operation. It lists active grants filtered by project, creator,-// statement, target database, and expiry, then narrows and ranks them per-// operation:-//-// - Query: any matching grant confers ACL bypass; among them, prefer Unmask=true-// so SkipMasking can be turned on when the user is entitled to unmasked data.-// - Export: only grants with Export=true authorize the export, so filter to-// those first; among them, prefer Unmask=true to also skip masking.+// preCheckAccess returns the user's most capable active access grant matching+// the given query, or nil if none. When `requireExport` is true the CEL+// filter is narrowed to grants with `export == true`, so an unmask-only+// grant on the same statement can't shadow a separately-active export+// grant via slice-order ties (see PR #20491 review).//-// The returned grant is guaranteed to have a non-nil Payload — callers may-// deref Payload.Unmask / Payload.Export without an additional check.-func (s *SQLService) preCheckAccess(ctx context.Context, statement string, instance *store.InstanceMessage, database *store.DatabaseMessage, operation accessOperation) *store.AccessGrantMessage {+// The returned grant has a non-nil Payload — callers may deref+// `Payload.Unmask` / `Payload.Export` without an additional check.+func (s *SQLService) preCheckAccess(ctx context.Context, statement string, instance *store.InstanceMessage, database *store.DatabaseMessage, requireExport bool) *store.AccessGrantMessage {project, err := s.store.GetProject(ctx, &store.FindProjectMessage{Workspace: common.GetWorkspaceIDFromContext(ctx),ResourceID: &database.ProjectID,@@ -237,6 +224,9 @@ func (s *SQLService) preCheckAccess(ctx context.Context, statement string, instanow,strings.TrimSpace(statement),)+ if requireExport {+ filter += ` && export == true`+ }filterQ, err := store.GetListAccessGrantFilter(filter)if err != nil {slog.Warn("failed to build access grant filter", log.BBError(err))@@ -266,32 +256,45 @@ func (s *SQLService) preCheckAccess(ctx context.Context, statement string, instaslog.Warn("skip access grant for non-read-only query", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))return nil}- // Narrow to grants whose capabilities actually authorize this operation,- // then prefer Unmask=true so the caller can set SkipMasking when the- // user is entitled to unmasked data. Filtering keeps Query from ever- // being "covered" by an export-only grant (which would still bypass the- // ACL check) when an unmask grant exists in the same set — see the- // review note that the old combined score conflated the two dimensions.- var candidates []*store.AccessGrantMessage+ return selectBestAccessGrant(grants)+}++// selectBestAccessGrant picks the highest-ranked grant by capability count+// (Unmask + Export). A grant with both wins outright; otherwise the first+// single-capability grant in slice order wins (ties resolve to the input+// ordering). Nil-payload grants are skipped so callers can deref+// `Payload.Unmask` / `Payload.Export` without an additional check.+//+// This auto-find ranking is inherently ambiguous when two grants tie on+// score — for deterministic selection callers should pass an explicit+// `access_grant` in the request (see `resolveExplicitAccessGrant`).+func selectBestAccessGrant(grants []*store.AccessGrantMessage) *store.AccessGrantMessage {+ var best *store.AccessGrantMessage+ bestScore := -1for _, grant := range grants {if grant.Payload == nil {- // Defensive: a nil payload means we can't read Unmask/Export- // anyway, so it can't authorize anything beyond raw ACL bypass.- // Skipping here also lets downstream callers deref Payload safely.- continue- }- if operation == accessOperationExport && !grant.Payload.Export {continue}- candidates = append(candidates, grant)- }- if len(candidates) == 0 {- return nil- }- best := candidates[0]- for _, grant := range candidates[1:] {- if !best.Payload.Unmask && grant.Payload.Unmask {+ // Rank by Unmask only — Export plays no role in selection:+ //+ // - Export callers pass `requireExport=true`, which pushes+ // `&& export == true` into the CEL filter, so every grant in+ // this slice already has `Export=true` and a per-grant Export+ // bump would just be a uniform constant.+ // - Query callers don't read `Payload.Export` from the returned+ // grant — they only consume `Payload.Unmask` for+ // `SkipMasking`.+ //+ // So preferring Unmask=true is the only ranking signal that+ // affects observable behavior, and matches PR #20491 bot review+ // (#3349086819) requesting Unmask wins ties for Query.+ score := 0+ if grant.Payload.Unmask {+ score+++ }+ if score > bestScore {best = grant+ bestScore = score}}return best@@ -305,7 +308,7 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRreturn nil, err}- accessGrant := s.preCheckAccess(ctx, request.Statement, instance, database, accessOperationQuery)+ accessGrant := s.preCheckAccess(ctx, request.Statement, instance, database, false /* requireExport */)statement := request.Statement// In Redshift datashare, Rewrite query used for parser.@@ -953,11 +956,10 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Exporstatement = strings.ReplaceAll(statement, fmt.Sprintf("%s.", database.DatabaseName), "")}- // When an active access grant covers this export request, the user is already- // authorized and we skip the regular ACL check, just like the Query request.- // `preCheckAccess(..., accessOperationExport)` only returns grants with- // Export=true, so the presence of a grant here is sufficient to bypass ACL.- accessGrant := s.preCheckAccess(ctx, request.Statement, instance, database, accessOperationExport)+ // requireExport=true narrows the CEL filter to grants with export=true,+ // so a tied unmask-only grant can't shadow a separately-active export+ // grant via slice order (PR #20491 bot review).+ accessGrant := s.preCheckAccess(ctx, request.Statement, instance, database, true /* requireExport */)// Validate the request.// New query ACL experience.diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.goindex e6de5ace43..d0dd4fead6 100644--- a/backend/api/v1/sql_service_test.go+++ b/backend/api/v1/sql_service_test.go@@ -10,6 +10,70 @@ import ("github.com/bytebase/bytebase/backend/store")+// TestSelectBestAccessGrantPrefersUnmask covers the Unmask-only ranking:+// Export plays no role (Export callers already filtered the pool via the+// `requireExport` CEL filter, and Query never reads `Payload.Export`).+// Preferring Unmask=true is what addresses PR #20491 bot review+// (#3349086819) — a user with an active unmask grant should never be+// masked by Query when an export-only grant shares the slice.+func TestSelectBestAccessGrantPrefersUnmask(t *testing.T) {+ grantOf := func(unmask, export bool) *store.AccessGrantMessage {+ return &store.AccessGrantMessage{+ Payload: &storepb.AccessGrantPayload{Unmask: unmask, Export: export},+ }+ }++ t.Run("returns nil for empty input", func(t *testing.T) {+ require.Nil(t, selectBestAccessGrant(nil))+ require.Nil(t, selectBestAccessGrant([]*store.AccessGrantMessage{}))+ })++ t.Run("skips nil-payload grants and returns nil when none remain", func(t *testing.T) {+ got := selectBestAccessGrant([]*store.AccessGrantMessage{+ {Payload: nil},+ {Payload: nil},+ })+ require.Nil(t, got)+ })++ t.Run("returns the only valid grant when others have nil payloads", func(t *testing.T) {+ valid := grantOf(true, false)+ got := selectBestAccessGrant([]*store.AccessGrantMessage{+ {Payload: nil},+ valid,+ {Payload: nil},+ })+ require.Same(t, valid, got)+ })++ t.Run("unmask grant wins over export-only grant regardless of slice order", func(t *testing.T) {+ unmaskGrant := grantOf(true, false)+ exportOnly := grantOf(false, true)+ // Put exportOnly first to prove the win isn't due to position —+ // Unmask scoring is what selects unmaskGrant.+ got := selectBestAccessGrant([]*store.AccessGrantMessage{exportOnly, unmaskGrant})+ require.Same(t, unmaskGrant, got)+ })++ t.Run("among multiple unmask grants the first in slice order wins", func(t *testing.T) {+ first := grantOf(true, false)+ second := grantOf(true, true)+ // Both have Unmask=true → tied score (Export plays no role). First+ // in slice wins via strict ">". Equivalent for Query callers+ // since both grants yield the same SkipMasking=true.+ got := selectBestAccessGrant([]*store.AccessGrantMessage{first, second})+ require.Same(t, first, got)+ })++ t.Run("returns a no-unmask grant when none have unmask", func(t *testing.T) {+ // All-zero-score case: a no-unmask grant is still returned (it+ // confers ACL bypass for Query, even if it can't unmask).+ exportOnly := grantOf(false, true)+ got := selectBestAccessGrant([]*store.AccessGrantMessage{exportOnly})+ require.Same(t, exportOnly, got)+ })+}+// TestBuildExportQueryContextPropagatesSkipMasking pins the bug fix from PR// #20487: when an export is authorized by a JIT grant with unmask=true,// SkipMasking must reach db.QueryContext so the driver doesn't mask rows atdiff --git a/backend/component/export/formatter_goldens_test.go b/backend/component/export/formatter_goldens_test.godeleted file mode 100644index 2bdce23e04..0000000000--- a/backend/component/export/formatter_goldens_test.go+++ /dev/null@@ -1,132 +0,0 @@-package export--import (- "bufio"- "encoding/hex"- "math"- "os"- "path/filepath"- "strconv"- "strings"- "testing"-- "google.golang.org/protobuf/types/known/timestamppb"-- v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"-)--// goldensFormatterDir locates the shared TSV fixtures both Go and TS read from.-func goldensFormatterDir(t *testing.T) string {- t.Helper()- wd, err := os.Getwd()- if err != nil {- t.Fatalf("getwd: %v", err)- }- for dir := wd; dir != "/"; dir = filepath.Dir(dir) {- candidate := filepath.Join(dir, "frontend", "src", "utils", "sql-download", "__tests__", "goldens", "formatters")- if info, err := os.Stat(candidate); err == nil && info.IsDir() {- return candidate- }- }- t.Fatal("could not locate frontend/src/utils/sql-download/__tests__/goldens/formatters")- return ""-}--func readTSVLines(t *testing.T, path string) [][]string {- t.Helper()- f, err := os.Open(path)- if err != nil {- t.Fatalf("open %s: %v", path, err)- }- defer f.Close()- var out [][]string- s := bufio.NewScanner(f)- for s.Scan() {- line := s.Text()- if line == "" || strings.HasPrefix(line, "#") {- continue- }- out = append(out, strings.Split(line, "\t"))- }- if err := s.Err(); err != nil {- t.Fatalf("scan %s: %v", path, err)- }- return out-}--func TestFloat32FormatterGolden(t *testing.T) {- t.Parallel()- for _, row := range readTSVLines(t, filepath.Join(goldensFormatterDir(t), "float32.tsv")) {- if len(row) != 2 {- t.Fatalf("float32.tsv malformed row: %v", row)- }- bits, err := hex.DecodeString(row[0])- if err != nil || len(bits) != 4 {- t.Fatalf("invalid hex %q: %v", row[0], err)- }- u := uint32(bits[0])<<24 | uint32(bits[1])<<16 | uint32(bits[2])<<8 | uint32(bits[3])- f := math.Float32frombits(u)- got := strconv.FormatFloat(float64(f), 'f', -1, 32)- if got != row[1] {- t.Errorf("bits=%s: got %q, want %q", row[0], got, row[1])- }- }-}--func TestTimestampFormatterGolden(t *testing.T) {- t.Parallel()- for _, row := range readTSVLines(t, filepath.Join(goldensFormatterDir(t), "timestamp.tsv")) {- if len(row) != 3 {- t.Fatalf("timestamp.tsv malformed row: %v", row)- }- sec, err := strconv.ParseInt(row[0], 10, 64)- if err != nil {- t.Fatalf("parse seconds %q: %v", row[0], err)- }- nanos, err := strconv.ParseInt(row[1], 10, 32)- if err != nil {- t.Fatalf("parse nanos %q: %v", row[1], err)- }- ts := &v1pb.RowValue_Timestamp{- GoogleTimestamp: ×tamppb.Timestamp{Seconds: sec, Nanos: int32(nanos)},- }- got := formatTimestamp(ts)- if got != row[2] {- t.Errorf("seconds=%d nanos=%d: got %q, want %q", sec, nanos, got, row[2])- }- }-}--func TestTimestampTZFormatterGolden(t *testing.T) {- t.Parallel()- for _, row := range readTSVLines(t, filepath.Join(goldensFormatterDir(t), "timestamptz.tsv")) {- if len(row) != 5 {- t.Fatalf("timestamptz.tsv malformed row: %v", row)- }- sec, err := strconv.ParseInt(row[0], 10, 64)- if err != nil {- t.Fatalf("parse seconds %q: %v", row[0], err)- }- nanos, err := strconv.ParseInt(row[1], 10, 32)- if err != nil {- t.Fatalf("parse nanos %q: %v", row[1], err)- }- zone := row[2]- if zone == "-" {- zone = ""- }- offset, err := strconv.ParseInt(row[3], 10, 32)- if err != nil {- t.Fatalf("parse offset %q: %v", row[3], err)- }- ts := &v1pb.RowValue_TimestampTZ{- GoogleTimestamp: ×tamppb.Timestamp{Seconds: sec, Nanos: int32(nanos)},- Zone: zone,- Offset: int32(offset),- }- got := formatTimestampTz(ts)- if got != row[4] {- t.Errorf("seconds=%d nanos=%d zone=%q offset=%d: got %q, want %q", sec, nanos, zone, offset, got, row[4])- }- }-}diff --git a/backend/store/access_grant_filter_test.go b/backend/store/access_grant_filter_test.goindex 95c9efb0d6..fecf451727 100644--- a/backend/store/access_grant_filter_test.go+++ b/backend/store/access_grant_filter_test.go@@ -106,6 +106,49 @@ func TestGetListAccessGrantFilter(t *testing.T) {wantArgs: []any{"SELECT 1 FROM t"},wantErr: false,},+ // unmask / export boolean filters — COALESCE so missing-key rows+ // (legacy payloads predating the field) compare as false instead+ // of NULL, which would silently drop them from `== false` results.+ {+ name: "unmask equals true",+ filter: `unmask == true`,+ wantSQL: "(COALESCE((access_grant.payload->>'unmask')::boolean, false) = $1)",+ wantArgs: []any{true},+ wantErr: false,+ },+ {+ name: "unmask equals false",+ filter: `unmask == false`,+ wantSQL: "(COALESCE((access_grant.payload->>'unmask')::boolean, false) = $1)",+ wantArgs: []any{false},+ wantErr: false,+ },+ {+ name: "export equals true",+ filter: `export == true`,+ wantSQL: "(COALESCE((access_grant.payload->>'export')::boolean, false) = $1)",+ wantArgs: []any{true},+ wantErr: false,+ },+ {+ name: "export equals false",+ filter: `export == false`,+ wantSQL: "(COALESCE((access_grant.payload->>'export')::boolean, false) = $1)",+ wantArgs: []any{false},+ wantErr: false,+ },+ {+ name: "unmask rejects non-boolean",+ filter: `unmask == "true"`,+ wantErr: true,+ errContains: "unmask value must be a boolean",+ },+ {+ name: "export rejects non-boolean",+ filter: `export == 1`,+ wantErr: true,+ errContains: "export value must be a boolean",+ },}for _, tt := range tests {diff --git a/frontend/biome.json b/frontend/biome.jsonindex dcfe19ebc9..b69227aa3b 100644--- a/frontend/biome.json+++ b/frontend/biome.json@@ -3,12 +3,7 @@"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },"files": {"ignoreUnknown": true,- "includes": [- "src/**/*",- "!!src/bbkit/BBUtil.ts",- "!!src/types/proto-es/**",- "!!src/utils/sql-download/__tests__/goldens/**"- ]+ "includes": ["src/**/*", "!!src/bbkit/BBUtil.ts", "!!src/types/proto-es/**"]},"formatter": {"enabled": true,diff --git a/frontend/package.json b/frontend/package.jsonindex 6bf3222aae..03285cbf17 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -42,7 +42,6 @@"@markdoc/markdoc": "0.5.7","@tanstack/react-virtual": "^3.13.24","@vueuse/core": "14.3.0",- "@zip.js/zip.js": "^2.8.26","bootstrap": "5.3.8","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -54,7 +53,6 @@"elkjs": "^0.11.0","emittery": "^1.2.0","events": "^3.3.0",- "exceljs": "^4.4.0","file-saver": "^2.0.5","highlight.js": "11.11.1","html-query-plan": "^2.6.1",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex fc776bb4d3..471d45f6d8 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -4,12 +4,6 @@ settings:autoInstallPeers: trueexcludeLinksFromLockfile: false-overrides:- readdir-glob>minimatch: ^9.0.7- tmp: ^0.2.5- exceljs>archiver: ^7.0.0- exceljs>unzipper: ^0.12.0-pnpmfileChecksum: sha256-D+Oiltjq0mI5+T73et/+VdZYEDWjB/193i1+mwbpq0Y=importers:@@ -70,9 +64,6 @@ importers:'@vueuse/core':specifier: 14.3.0version: 14.3.0([email protected]([email protected]))- '@zip.js/zip.js':- specifier: ^2.8.26- version: 2.8.26bootstrap:specifier: 5.3.8version: 5.3.8(@popperjs/[email protected])@@ -106,9 +97,6 @@ importers:events:specifier: ^3.3.0version: 3.3.0- exceljs:- specifier: ^4.4.0- version: 4.4.0file-saver:specifier: ^2.0.5version: 2.0.5@@ -1691,12 +1679,6 @@ packages:'@noble/hashes':optional: true- '@fast-csv/[email protected]':- resolution: {integrity: sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==}-- '@fast-csv/[email protected]':- resolution: {integrity: sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==}-'@floating-ui/[email protected]':resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}@@ -2397,9 +2379,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}- '@types/[email protected]':- resolution: {integrity: sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==}-'@types/[email protected]':resolution: {integrity: sha512-8oljBDGun9cIsZRJR6fkihn0TSXJI0UDOOhncYaERq6M0JMDoPLxyscwruJcb4GKS6dvK/d8xebYBg27h/duaQ==}@@ -2725,18 +2704,10 @@ packages:peerDependencies:vue: ^3.5.0- '@zip.js/[email protected]':- resolution: {integrity: sha512-RQ4h9F6DOiHxpdocUDrOl6xBM+yOtz+LkUol47AVWcfebGBDpZ7w7Xvz9PS24JgXvLGiXXzSAfdCdVy1tPlaFA==}- engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'}-resolution: {integrity: sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==}engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}- resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}- engines: {node: '>=6.5'}-resolution: {integrity: sha512-BsLm5vFMRUrrLeCcRc+G0t2qOaTzpoJQLOubq2XM72eNpjF5UdU5o/5NvlNhx95XHcAvcl8OMXr4mlg/fRgUXQ==}engines: {node: '>=6'}@@ -2796,14 +2767,6 @@ packages:resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}engines: {node: '>=12'}- resolution: {integrity: sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA==}- engines: {node: '>= 14'}-- resolution: {integrity: sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ==}- engines: {node: '>= 14'}-resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==}@@ -2831,14 +2794,6 @@ packages:peerDependencies:postcss: ^8.1.0- resolution: {integrity: sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==}- peerDependencies:- react-native-b4a: '*'- peerDependenciesMeta:- react-native-b4a:- optional: true-resolution: {integrity: sha512-Co2Y9wX854ts6U8gAAPXfn0GmAyctHuK8n0Yhfjd6t30g7yvKjspvvOo9yG+z52PZRgFErt7Ka2pYnXCjLKEpg==}peerDependencies:@@ -2864,47 +2819,6 @@ packages:resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}engines: {node: 18 || 20 || >=22}- resolution: {integrity: sha512-HdUm8EMQBLaJvGUdidNNbqpA1kYkwNcb+MYxkxCLAPJGQzlv9J0C24h8V65Z4c5GLd/JEALDvpFCQgpLJqc0zw==}- peerDependencies:- bare-abort-controller: '*'- peerDependenciesMeta:- bare-abort-controller:- optional: true-- resolution: {integrity: sha512-WDRsyVN52eAx/lBamKD6uyw8H4228h/x0sGGGegOamM2cd7Pag88GfMQalobXI+HaEUxpCkbKQUDOQqt9wawRw==}- engines: {bare: '>=1.16.0'}- peerDependencies:- bare-buffer: '*'- peerDependenciesMeta:- bare-buffer:- optional: true-- resolution: {integrity: sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ==}- engines: {bare: '>=1.14.0'}-- resolution: {integrity: sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==}-- resolution: {integrity: sha512-Vp0cnjYyrEC4whYTymQ+YZi6pBpfiICZO3cfRG8sy67ZNWe951urv1x4eW1BKNngw3U+3fPYb5JQvHbCtxH7Ow==}- peerDependencies:- bare-abort-controller: '*'- bare-buffer: '*'- bare-events: '*'- peerDependenciesMeta:- bare-abort-controller:- optional: true- bare-buffer:- optional: true- bare-events:- optional: true-- resolution: {integrity: sha512-Kccpc7ACfXaxfeInfqKcZtW4pT5YBn1mesc4sCsun6sRwtbJ4h+sNOaksUpYEJUKfN65YWC6Bw2OJEFiKxq8nQ==}-resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}@@ -2919,9 +2833,6 @@ packages:resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==}- resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}-resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}@@ -2956,10 +2867,6 @@ packages:engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}hasBin: true- resolution: {integrity: sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==}- engines: {node: '>=8.0.0'}-resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}@@ -3057,10 +2964,6 @@ packages:resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==}engines: {node: '>= 10'}- resolution: {integrity: sha512-6FqVXeETqWPoGcfzrXb37E50NP0LXT8kAMu5ooZayhWWdgEY4lBEEcbQNXtkuKQsGduxiIcI4gOTsxTmuq/bSg==}- engines: {node: '>= 14'}-resolution: {integrity: sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==}@@ -3092,15 +2995,6 @@ packages:resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}- resolution: {integrity: sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==}- engines: {node: '>=0.8'}- hasBin: true-- resolution: {integrity: sha512-piICUB6ei4IlTv1+653yq5+KoqfBYmj9bw6LqXoOneTMDXk5nM1qt12mFW1caG3LlJXEKW1Bp0WggEmIfQB34g==}- engines: {node: '>= 14'}-resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}@@ -3357,9 +3251,6 @@ packages:resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}-resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}@@ -3542,21 +3433,10 @@ packages:resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}engines: {node: '>=0.10.0'}- resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}-resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}- resolution: {integrity: sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==}- engines: {node: '>=8.3.0'}-resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}engines: {node: '>=12.0.0'}@@ -3567,16 +3447,9 @@ packages:resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}- resolution: {integrity: sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==}- engines: {node: '>=10.0.0'}-resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}- resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==}-resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}engines: {node: '>=8.6.0'}@@ -3645,10 +3518,6 @@ packages:react-dom:optional: true- resolution: {integrity: sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==}- engines: {node: '>=14.14'}-resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}@@ -3882,10 +3751,6 @@ packages:resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}- resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}- engines: {node: '>=8'}-resolution: {integrity: sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==}engines: {node: '>=18'}@@ -3967,9 +3832,6 @@ packages:resolution: {integrity: sha512-WYDyuc/uFcGp6YtM2H0uKmUwieOuzeE/5YocFJLnLfclZ4inf3mRn8ZVy1s7Hxji7Jxm6Ss8gqpexD/GlKoGgg==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}- resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==}-resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}@@ -3979,10 +3841,6 @@ packages:resolution: {integrity: sha512-v2xMAarJOFy51kuesYEIIx5r4WHvsV+VLMU49K24bdiRZGUpo1ZulO1DRrLozM5BMbXUfRfrUTM2PbBfYCeA4Q==}- resolution: {integrity: sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==}- engines: {node: '>= 0.6.3'}-resolution: {integrity: sha512-UyIwNb1lJBChJnGfjmO0OR+ezh2iVu1Kas3nvBS/BzGnx79dv6g7unpKIDNPMhfdTEGoc7mC8uAu51XEtX+FHQ==}engines: {node: '>=6'}@@ -4144,31 +4002,6 @@ packages:resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}- resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}-- resolution: {integrity: sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==}-- resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==}-- resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}- deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.-- resolution: {integrity: sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==}-- resolution: {integrity: sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==}-- resolution: {integrity: sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==}-- resolution: {integrity: sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==}-resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==}@@ -4483,9 +4316,6 @@ packages:resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==}hasBin: true- resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}-resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==}@@ -4494,10 +4324,6 @@ packages:engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}hasBin: true- resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}- engines: {node: '>=0.10.0'}-resolution: {integrity: sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==}@@ -4675,10 +4501,6 @@ packages:resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}- resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==}- engines: {node: '>= 0.6.0'}-resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}@@ -4811,13 +4633,6 @@ packages:resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}engines: {node: '>= 6'}- resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==}- engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}-- resolution: {integrity: sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==}-resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==}engines: {node: '>= 20.19.0'}@@ -4943,10 +4758,6 @@ packages:resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}- resolution: {integrity: sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==}- engines: {node: '>=10'}-resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}engines: {node: '>=v12.22.7'}@@ -5053,9 +4864,6 @@ packages:resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}- resolution: {integrity: sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg==}-resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}engines: {node: '>=8'}@@ -5130,20 +4938,11 @@ packages:resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}engines: {node: '>=6'}- resolution: {integrity: sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==}-- resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}-resolution: {integrity: sha512-LBAhFyLho16harJoWMg/nZsQYgTrg5jXOn2nCYjRUcZZEdE3qa2zb8QEDRUGVZBW4rlazf2fxkg8tztybTaqWw==}engines: {node: '>=10'}hasBin: true- resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}-resolution: {integrity: sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==}@@ -5294,10 +5093,6 @@ packages:resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}engines: {node: '>= 4.0.0'}- resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}- engines: {node: '>= 10.0.0'}-resolution: {integrity: sha512-5lWVjgi6vuHhJ526bI4nlCOmkCIF3nnfXkCMDeMJrtdvxTs6ZFCM8oNufGTsDbKv/tJ/xj8RpvXjRuPBZJuJog==}engines: {node: '>=20.19.0'}@@ -5316,9 +5111,6 @@ packages:resolution: {integrity: sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==}engines: {node: '>=18.12.0'}- resolution: {integrity: sha512-PZ8hTS+AqcGxsaQntl3IRBw65QrBI6lxzqDEL7IAo/XCEqRTKGfOX56Vea5TH9SZczRVxuzk1re04z/YjuYCJA==}-resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}hasBin: true@@ -5644,10 +5436,6 @@ packages:resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}engines: {node: '>=10'}- resolution: {integrity: sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==}- engines: {node: '>= 14'}-resolution: {integrity: sha512-efI2tVaVQPqtOh114loML/Z80Y4NP3yc+Ff0fYiZJPauNeWZeIp/bRFD7I9bfmCOYBh/PHxlglQ9+wvlwnPikQ==}engines: {node: '>=12.20.0'}@@ -7028,25 +6816,6 @@ snapshots:'@exodus/[email protected]': {}- '@fast-csv/[email protected]':- dependencies:- '@types/node': 14.18.63- lodash.escaperegexp: 4.1.2- lodash.isboolean: 3.0.3- lodash.isequal: 4.5.0- lodash.isfunction: 3.0.9- lodash.isnil: 4.0.0-- '@fast-csv/[email protected]':- dependencies:- '@types/node': 14.18.63- lodash.escaperegexp: 4.1.2- lodash.groupby: 4.6.0- lodash.isfunction: 3.0.9- lodash.isnil: 4.0.0- lodash.isundefined: 3.0.1- lodash.uniq: 4.5.0-'@floating-ui/[email protected]':dependencies:'@floating-ui/utils': 0.2.11@@ -7622,8 +7391,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]':dependencies:undici-types: 7.16.0@@ -8092,14 +7859,8 @@ snapshots:dependencies:vue: 3.5.34([email protected])- '@zip.js/[email protected]': {}-- dependencies:- event-target-shim: 5.0.1-dependencies:buffer: 5.7.1@@ -8158,30 +7919,6 @@ snapshots:- dependencies:- glob: 10.5.0- graceful-fs: 4.2.11- is-stream: 2.0.1- lazystream: 1.0.1- lodash: 4.17.23- normalize-path: 3.0.0- readable-stream: 4.7.0-- dependencies:- archiver-utils: 5.0.2- async: 3.2.6- buffer-crc32: 1.0.0- readable-stream: 4.7.0- readdir-glob: 1.1.3- tar-stream: 3.2.0- zip-stream: 6.0.1- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - react-native-b4a-@@ -8205,8 +7942,6 @@ snapshots:postcss: 8.5.14postcss-value-parser: 4.2.0- [email protected]: {}-[email protected](@babel/[email protected]):dependencies:'@babel/compat-data': 7.29.0@@ -8237,38 +7972,6 @@ snapshots:- [email protected]: {}-- dependencies:- bare-events: 2.8.3- bare-path: 3.0.0- bare-stream: 2.13.1([email protected])- bare-url: 2.4.3- fast-fifo: 1.3.2- transitivePeerDependencies:- - bare-abort-controller- - react-native-b4a-- [email protected]: {}-- dependencies:- bare-os: 3.9.1-- dependencies:- streamx: 2.25.0- teex: 1.0.1- optionalDependencies:- bare-events: 2.8.3- transitivePeerDependencies:- - react-native-b4a-- dependencies:- bare-path: 3.0.0-@@ -8279,8 +7982,6 @@ snapshots:- [email protected]: {}-[email protected](@popperjs/[email protected]):@@ -8317,8 +8018,6 @@ snapshots:node-releases: 2.0.38update-browserslist-db: 1.2.3([email protected])- [email protected]: {}-@@ -8414,14 +8113,6 @@ snapshots:- dependencies:- crc-32: 1.2.2- crc32-stream: 6.0.0- is-stream: 2.0.1- normalize-path: 3.0.0- readable-stream: 4.7.0-@@ -8449,13 +8140,6 @@ snapshots:- [email protected]: {}-- dependencies:- crc-32: 1.2.2- readable-stream: 4.7.0-@@ -8722,10 +8406,6 @@ snapshots:es-errors: 1.3.0gopd: 1.2.0- dependencies:- readable-stream: 2.3.8-@@ -8961,47 +8641,16 @@ snapshots:- [email protected]: {}-- dependencies:- bare-events: 2.8.3- transitivePeerDependencies:- - bare-abort-controller-- dependencies:- archiver: 7.0.1- dayjs: 1.11.20- fast-csv: 4.3.6- jszip: 3.10.1- readable-stream: 3.6.2- saxes: 5.0.1- tmp: 0.2.5- unzipper: 0.12.3- uuid: 8.3.2- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - react-native-b4a-- dependencies:- '@fast-csv/format': 4.3.5- '@fast-csv/parse': 4.3.6-- [email protected]: {}-dependencies:'@nodelib/fs.stat': 2.0.5@@ -9065,12 +8714,6 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])- dependencies:- graceful-fs: 4.2.11- jsonfile: 6.2.1- universalify: 2.0.1-optional: true@@ -9287,8 +8930,6 @@ snapshots:- [email protected]: {}-@@ -9374,12 +9015,6 @@ snapshots:espree: 9.6.1semver: 7.8.0- dependencies:- universalify: 2.0.1- optionalDependencies:- graceful-fs: 4.2.11-dependencies:lie: 3.3.0@@ -9396,10 +9031,6 @@ snapshots:chalk: 4.1.1dotenv: 16.6.1- dependencies:- readable-stream: 2.3.8-dependencies:buffer: 5.7.1@@ -9544,22 +9175,6 @@ snapshots:- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-@@ -10081,16 +9696,12 @@ snapshots:- [email protected]: {}-dependencies:abbrev: 2.0.0- [email protected]: {}-@@ -10337,8 +9948,6 @@ snapshots:- [email protected]: {}-@@ -10481,18 +10090,6 @@ snapshots:string_decoder: 1.3.0util-deprecate: 1.0.2- dependencies:- abort-controller: 3.0.0- buffer: 6.0.3- events: 3.3.0- process: 0.11.10- string_decoder: 1.3.0-- dependencies:- minimatch: 9.0.9-@@ -10664,10 +10261,6 @@ snapshots:- dependencies:- xmlchars: 2.2.0-dependencies:xmlchars: 2.2.0@@ -10760,15 +10353,6 @@ snapshots:- dependencies:- events-universal: 1.0.1- fast-fifo: 1.3.2- text-decoder: 1.2.7- transitivePeerDependencies:- - bare-abort-controller- - react-native-b4a-dependencies:emoji-regex: 8.0.0@@ -10842,24 +10426,6 @@ snapshots:- dependencies:- b4a: 1.8.1- bare-fs: 4.7.1- fast-fifo: 1.3.2- streamx: 2.25.0- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - react-native-b4a-- dependencies:- streamx: 2.25.0- transitivePeerDependencies:- - bare-abort-controller- - react-native-b4a-dependencies:'@jridgewell/source-map': 0.3.11@@ -10867,12 +10433,6 @@ snapshots:commander: 2.20.3source-map-support: 0.5.21- dependencies:- b4a: 1.8.1- transitivePeerDependencies:- - react-native-b4a-dependencies:inherits: 2.0.4@@ -11023,8 +10583,6 @@ snapshots:- [email protected]: {}-dependencies:pathe: 2.0.3@@ -11050,14 +10608,6 @@ snapshots:picomatch: 4.0.4webpack-virtual-modules: 0.6.2- dependencies:- bluebird: 3.7.2- duplexer2: 0.1.4- fs-extra: 11.3.5- graceful-fs: 4.2.11- node-int64: 0.4.0-dependencies:browserslist: 4.28.2@@ -11322,12 +10872,6 @@ snapshots:- dependencies:- archiver-utils: 5.0.2- compress-commons: 6.0.2- readable-stream: 4.7.0-[email protected](@types/[email protected])([email protected])([email protected])([email protected]([email protected])):optionalDependencies:'@types/react': 19.2.14diff --git a/frontend/pnpm-workspace.yaml b/frontend/pnpm-workspace.yamlindex bf25c612c2..fd42c05fc4 100644--- a/frontend/pnpm-workspace.yaml+++ b/frontend/pnpm-workspace.yaml@@ -2,31 +2,6 @@ peerDependencyRules:allowedVersions:typescript: '6'-overrides:- # Patch transitive minimatch <5.1.8 reached through exceljs > archiver >- # readdir-glob. The 5.x line has three high-severity ReDoS advisories- # (GHSA-3ppc-4f35-3m26, GHSA-7r86-cg39-jmmj, GHSA-3vr3-vh78-x7vq) fixed- # in 5.1.8+. exceljs's internal use is not user-controllable but the- # advisory still trips Snyk. Scoped via parent so we don't disturb- # archiver-utils' [email protected] chain.- readdir-glob>minimatch: ^9.0.7- # Patch transitive [email protected] reached through exceljs. The 0.2.3 line is- # vulnerable to a symlink attack via the `dir` parameter; fixed in 0.2.4+.- # exceljs's internal use of tmp is for creating XLSX shared-strings temp- # files on disk; in our browser bundle the temp paths are managed by- # exceljs itself and not user-influenced, but the advisory still trips- # Snyk. 0.2.x is API-stable, so the bump is drop-in.- tmp: ^0.2.5- # Force exceljs's archiver + unzipper to versions that drop the- # glob@7 → [email protected] transitive chain. inflight is unmaintained- # with no published fix for its memory-leak advisory (CVSS 6.2).- # archiver@7 uses archiver-utils@5 → glob@10 (no inflight); [email protected]- # uses fs-extra (no fstream/rimraf/glob@7 chain). Both retain the same- # outer API exceljs consumes (Archiver.pipe / Open.file), so the bump- # is drop-in — verified by the serializeXLSX tests.- exceljs>archiver: ^7.0.0- exceljs>unzipper: ^0.12.0-allowBuilds:core-js: trueesbuild: truediff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjsindex 63633ef88f..8afbfb21d1 100644--- a/frontend/scripts/check-react-i18n.mjs+++ b/frontend/scripts/check-react-i18n.mjs@@ -32,14 +32,6 @@ const DYNAMIC_PREFIXES = ["settings.sensitive-data.algorithms.","instance.selected-n-instances","settings.sidebar.",- // Referenced via error.i18n.key on a thrown DownloadError, not as a literal- // `t("…")` call in source. See sql-download/error-messages.ts and the- // throw sites in sql-download/index.ts / formats/{sql,xlsx}.ts.- "sql-editor.download-too-large-bytes",- "sql-editor.download-too-large-cells",- "sql-editor.download-too-large-xlsx-columns",- "sql-editor.download-too-large-xlsx-rows",- "sql-editor.sql-download-engine-unsupported",// Returned from getReviewBadge as labelKey string literals, not invoked// via t("…") in source. See frontend/src/react/pages/project/utils/reviewBadge.ts."common.bypassed",@@ -61,13 +53,7 @@ const LOCALES_DIR = resolve(REACT_DIR, "locales");// keeps its React tree co-located with its framework-agnostic logic at// `src/plugins/ai/react/`; include those files when scanning for `t(...)`// usage so its i18n keys don't read as "unused".-const EXTRA_REACT_DIRS = [- resolve(ROOT, "src/plugins/ai/react"),- // sql-download lives outside src/react/ as a framework-neutral module- // but its `t(...)` calls (e.g. in error-messages.ts) consume keys from- // src/react/locales — include it so those keys don't read as "unused".- resolve(ROOT, "src/utils/sql-download"),-];+const EXTRA_REACT_DIRS = [resolve(ROOT, "src/plugins/ai/react")];const LOCALES = ["en-US", "zh-CN", "es-ES", "ja-JP", "vi-VN"];let errors = 0;diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex b9abd627b8..0fa6e3f932 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -277,12 +277,8 @@"readonly": "Read-only"}},- "download-encryption-failed": "Failed to encrypt download.",- "download-failed": "Download failed.",- "download-too-large": "Result is too large for download. Reduce the row count or use Export.","expired": "Expired",- "self": "SQL Editor",- "sql-download-unavailable": "SQL download is unavailable for this connection."+ "self": "SQL Editor"},"sql-review": {"create": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex c64d0b9d25..e940b41439 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -277,12 +277,8 @@"readonly": "Sólo lectura"}},- "download-encryption-failed": "Error al cifrar la descarga.",- "download-failed": "Error en la descarga.",- "download-too-large": "El resultado es demasiado grande para descargar. Reduzca el número de filas o use Exportar.","expired": "Expirado",- "self": "Editor de SQL",- "sql-download-unavailable": "La descarga SQL no está disponible para esta conexión."+ "self": "Editor de SQL"},"sql-review": {"create": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 6bc05aefaf..7860fe1723 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -277,12 +277,8 @@"readonly": "読み取り専用"}},- "download-encryption-failed": "ダウンロードの暗号化に失敗しました。",- "download-failed": "ダウンロードに失敗しました。",- "download-too-large": "ダウンロードするには結果が大きすぎます。行数を減らすか、エクスポートを使用してください。","expired": "期限切れ",- "self": "SQLエディタ",- "sql-download-unavailable": "この接続では SQL ダウンロードを利用できません。"+ "self": "SQLエディタ"},"sql-review": {"create": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex c8bec61c6c..9d9b1e4b44 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -277,12 +277,8 @@"readonly": "Chỉ đọc"}},- "download-encryption-failed": "Không thể mã hóa bản tải xuống.",- "download-failed": "Tải xuống thất bại.",- "download-too-large": "Kết quả quá lớn để tải xuống. Hãy giảm số dòng hoặc sử dụng Xuất.","expired": "Đã hết hạn",- "self": "Trình soạn thảo SQL",- "sql-download-unavailable": "Tải xuống SQL không khả dụng cho kết nối này."+ "self": "Trình soạn thảo SQL"},"sql-review": {"create": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 5f2de3174d..88e7737c79 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -277,12 +277,8 @@"readonly": "只读数据源"}},- "download-encryption-failed": "下载加密失败。",- "download-failed": "下载失败。",- "download-too-large": "结果过大,无法下载。请减少行数或使用导出。","expired": "已过期",- "self": "SQL 编辑器",- "sql-download-unavailable": "当前连接不支持 SQL 下载。"+ "self": "SQL 编辑器"},"sql-review": {"create": {diff --git a/frontend/src/plugins/cel/types/factor.ts b/frontend/src/plugins/cel/types/factor.tsindex 0942ecf20e..6ce603a3b1 100644--- a/frontend/src/plugins/cel/types/factor.ts+++ b/frontend/src/plugins/cel/types/factor.ts@@ -1,5 +1,6 @@import {CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS,+ CEL_ATTRIBUTE_REQUEST_EXPORT,CEL_ATTRIBUTE_REQUEST_ROLE,CEL_ATTRIBUTE_REQUEST_TIME,CEL_ATTRIBUTE_REQUEST_UNMASK,@@ -57,7 +58,10 @@ export const StringFactorList = [] as const;export type StringFactor = (typeof StringFactorList)[number];-export const BooleanFactorList = [CEL_ATTRIBUTE_REQUEST_UNMASK] as const;+export const BooleanFactorList = [+ CEL_ATTRIBUTE_REQUEST_UNMASK,+ CEL_ATTRIBUTE_REQUEST_EXPORT,+] as const;export type BooleanFactor = (typeof BooleanFactorList)[number];export const TimestampFactorList = [CEL_ATTRIBUTE_REQUEST_TIME] as const;diff --git a/frontend/src/plugins/cel/types/operator.ts b/frontend/src/plugins/cel/types/operator.tsindex 2b04935e54..ab9fb0d6cf 100644--- a/frontend/src/plugins/cel/types/operator.ts+++ b/frontend/src/plugins/cel/types/operator.ts@@ -1,6 +1,7 @@import { uniq } from "lodash-es";import {CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS,+ CEL_ATTRIBUTE_REQUEST_EXPORT,CEL_ATTRIBUTE_REQUEST_ROLE,CEL_ATTRIBUTE_REQUEST_TIME,CEL_ATTRIBUTE_REQUEST_UNMASK,@@ -178,6 +179,7 @@ const OperatorList: Record<Factor, Operator[]> = {// Boolean factors[CEL_ATTRIBUTE_REQUEST_UNMASK]: uniq([...EqualityOperatorList]),+ [CEL_ATTRIBUTE_REQUEST_EXPORT]: uniq([...EqualityOperatorList]),// These factors don't have operator candidates for user selection.[CEL_ATTRIBUTE_RESOURCE_DATABASE]: [],diff --git a/frontend/src/react/components/AuditLogTable.tsx b/frontend/src/react/components/AuditLogTable.tsxindex f4f0593a9f..38ce20c827 100644--- a/frontend/src/react/components/AuditLogTable.tsx+++ b/frontend/src/react/components/AuditLogTable.tsx@@ -124,6 +124,50 @@ function buildAuditLogFilter(params: SearchParams): AuditLogFilter {// View link helper// ============================================================+// AuditLogViewCell renders the "View" external-link icon for an audit log row.+// Falls back to the JIT access grant's associated issue when the row has no+// static link (e.g. ad-hoc Query/Export not driven by a rollout) but the+// response was authorized by an access grant — gives users a trail to the+// grant's approval issue.+function AuditLogViewCell({ log }: { log: AuditLog }) {+ const staticLink = getViewLink(log);++ // Only attempt the grant fallback when no static link is available.+ const grantName = useMemo(() => {+ if (staticLink) return null;+ try {+ const response = JSON.parse(log.response || "{}") as Record<+ string,+ unknown+ >;+ const value = response["appliedAccessGrant"];+ return typeof value === "string" && value ? value : null;+ } catch {+ return null;+ }+ }, [staticLink, log.response]);++ const fetchAccessGrant = useAppStore((s) => s.fetchAccessGrant);+ const grantIssue = useAppStore((s) =>+ grantName ? (s.accessGrantsByName[grantName]?.issue ?? "") : ""+ );++ useEffect(() => {+ if (grantName && !grantIssue) {+ void fetchAccessGrant(grantName);+ }+ }, [grantName, grantIssue, fetchAccessGrant]);++ const target = staticLink || grantIssue || null;+ if (!target) return null;+ const href = target.startsWith("/") ? target : `/${target}`;+ return (+ <a href={href} target="_blank" rel="noreferrer">+ <ExternalLink className="size-4 text-accent" />+ </a>+ );+}+function getViewLink(auditLog: AuditLog): string | null {let parsedRequest: Record<string, unknown>;let parsedResponse: Record<string, unknown>;@@ -430,16 +474,7 @@ function useColumnDefs(): ColumnDef[] {key: "view",title: t("common.view"),defaultWidth: 50,- render: (log: AuditLog) => {- let link = getViewLink(log);- if (!link) return null;- if (!link.startsWith("/")) link = `/${link}`;- return (- <a href={link} target="_blank" rel="noreferrer">- <ExternalLink className="size-4 text-accent" />- </a>- );- },+ render: (log: AuditLog) => <AuditLogViewCell log={log} />,},],[t]diff --git a/frontend/src/react/components/CustomApproval/utils.ts b/frontend/src/react/components/CustomApproval/utils.tsindex 618de4db35..96799ce811 100644--- a/frontend/src/react/components/CustomApproval/utils.ts+++ b/frontend/src/react/components/CustomApproval/utils.ts@@ -20,6 +20,7 @@ import {} from "@/utils";import {CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS,+ CEL_ATTRIBUTE_REQUEST_EXPORT,CEL_ATTRIBUTE_REQUEST_ROLE,CEL_ATTRIBUTE_REQUEST_UNMASK,CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,@@ -150,6 +151,7 @@ export const ApprovalSourceFactorMap: Map<CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,CEL_ATTRIBUTE_REQUEST_UNMASK,+ CEL_ATTRIBUTE_REQUEST_EXPORT,],],]);@@ -252,6 +254,7 @@ export const getApprovalOptionConfigMap = (options = getRiskLevelOptions();break;case CEL_ATTRIBUTE_REQUEST_UNMASK:+ case CEL_ATTRIBUTE_REQUEST_EXPORT:options = [{ label: "true", value: "true" },{ label: "false", value: "false" },diff --git a/frontend/src/react/components/DataExportButton.tsx b/frontend/src/react/components/DataExportButton.tsxindex 823fadf352..bfca12c44f 100644--- a/frontend/src/react/components/DataExportButton.tsx+++ b/frontend/src/react/components/DataExportButton.tsx@@ -1,7 +1,7 @@import dayjs from "dayjs";import saveAs from "file-saver";import JSZip from "jszip";-import { ChevronDown, Download } from "lucide-react";+import { ChevronDown, Copy, Download, Wand2 } from "lucide-react";import {type ReactNode,useCallback,@@ -65,7 +65,7 @@ interface DataExportButtonProps {supportFormats: ExportFormat[];supportPassword?: boolean;viewMode: ViewMode;- tooltip?: string;+ tooltip?: ReactNode;text?: string;validate?: (option: ExportOption) => boolean;maximumExportCount?: number;@@ -84,6 +84,21 @@ const SIZE_TO_BUTTON: Record<Size, ButtonProps["size"]> = {const ROW_COUNT_PRESET = [1, 100, 500, 1000, 5000, 10000, 100000];+const GENERATED_PASSWORD_LENGTH = 8;+const GENERATED_PASSWORD_CHARSET =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";++const generateRandomPassword = (length = GENERATED_PASSWORD_LENGTH) => {+ const values = new Uint32Array(length);+ crypto.getRandomValues(values);+ let out = "";+ for (let i = 0; i < length; i++) {+ out +=+ GENERATED_PASSWORD_CHARSET[values[i] % GENERATED_PASSWORD_CHARSET.length];+ }+ return out;+};+const computeMaximumPreset = (maximum: number) => {const list = ROW_COUNT_PRESET.filter((n) => n <= maximum);if (maximum !== Number.MAX_VALUE && !list.includes(maximum)) {@@ -264,6 +279,46 @@ export function DataExportButton({});}, [currentOption, isRequesting, onExport, t]);+ // Returns true when the clipboard write succeeded — Generate callers+ // gate the password commit on that so the masked input doesn't end up+ // holding a value the user can never read back. PR #20491 bot review+ // #3349557577.+ const copyPasswordToClipboard = useCallback(+ async (value: string): Promise<boolean> => {+ if (!value) return false;+ try {+ await navigator.clipboard.writeText(value);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.copied"),+ });+ return true;+ } catch {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ });+ return false;+ }+ },+ [t]+ );++ const handleGeneratePassword = useCallback(async () => {+ const next = generateRandomPassword();+ // Only commit the generated password to state after the user has it+ // on their clipboard. If the copy fails (insecure context, denied+ // permission) the input stays empty so the user isn't left signing+ // an export ZIP with a password they can't read back from the masked+ // input.+ const copied = await copyPasswordToClipboard(next);+ if (copied) {+ setPassword(next);+ }+ }, [copyPasswordToClipboard]);+const handleSelectDropdownFormat = (selected: ExportFormat) => {setFormat(selected);if (supportPassword) {@@ -386,6 +441,27 @@ export function DataExportButton({value={password}onChange={(e) => setPassword(e.target.value)}/>+ <div className="flex items-center gap-x-2 mt-1">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={handleGeneratePassword}+ >+ <Wand2 className="size-4 mr-1" />+ {t("export-data.generate-password")}+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={!password}+ onClick={() => void copyPasswordToClipboard(password)}+ >+ <Copy className="size-4 mr-1" />+ {t("common.copy")}+ </Button>+ </div></div>)}</div>diff --git a/frontend/src/react/components/sql-editor/AccessGrantItem.tsx b/frontend/src/react/components/sql-editor/AccessGrantItem.tsxindex 131f1ba36f..7ef46f7143 100644--- a/frontend/src/react/components/sql-editor/AccessGrantItem.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantItem.tsx@@ -119,6 +119,14 @@ export function AccessGrantItem({{t("sql-editor.grant-type-unmask")}</Badge>)}+ {grant.export && (+ <Badge+ variant="default"+ className="text-[10px] px-1.5 py-0 rounded-full"+ >+ {t("sql-editor.grant-type-export")}+ </Badge>+ )}</div>{expirationText && (<span className="text-xs text-control-placeholder shrink-0">diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxindex d929099360..9a98a6bd00 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -93,6 +93,7 @@ interface Props {readonly targets?: string[];readonly query?: string;readonly unmask?: boolean;+ readonly export?: boolean;readonly onClose: () => void;}@@ -126,6 +127,7 @@ function AccessGrantRequestDrawerInner({const [targets, setTargets] = useState<string[]>(defaultTargets);const [query, setQuery] = useState(stableProps.query ?? "");const [unmask, setUnmask] = useState(stableProps.unmask ?? false);+ const [exportResult, setExportResult] = useState(stableProps.export ?? false);const [duration, setDuration] = useState<number>(4);const [customExpireTime, setCustomExpireTime] = useState<string | undefined>(undefined@@ -190,6 +192,7 @@ function AccessGrantRequestDrawerInner({targets,query,unmask,+ export: exportResult,reason,expiration,});@@ -279,6 +282,20 @@ function AccessGrantRequestDrawerInner({</label></div>+ {/* Export */}+ <div className="flex flex-col gap-y-2">+ <div className="text-sm font-medium text-control">+ {t("sql-editor.grant-type-export")}+ </div>+ <label className="flex items-center gap-2 cursor-pointer">+ <Checkbox+ checked={exportResult}+ onCheckedChange={(checked) => setExportResult(checked)}+ />+ <span>{t("sql-editor.access-type-export")}</span>+ </label>+ </div>+{/* Expiration */}<div className="flex flex-col gap-y-2"><div className="text-sm font-medium text-control">@@ -336,9 +353,16 @@ export function AccessGrantRequestDrawer({targets,query,unmask,+ export: exportResult,onClose,}: Props) {- const propsRef = useRef({ targets, query, unmask, onClose });+ const propsRef = useRef({+ targets,+ query,+ unmask,+ export: exportResult,+ onClose,+ });// Freeze props while drawer is open so inner form stays stable during close animationconst stableProps = propsRef.current;@@ -346,7 +370,7 @@ export function AccessGrantRequestDrawer({<Sheet open={true} onOpenChange={(next) => !next && onClose()}><SheetContent width="standard"><AccessGrantRequestDrawerInner- key={`${targets?.join(",")}-${query}-${unmask}`}+ key={`${targets?.join(",")}-${query}-${unmask}-${exportResult}`}stableProps={stableProps}onClose={onClose}/>diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsxindex bdb296bedc..ba09463d73 100644--- a/frontend/src/react/components/sql-editor/AccessPane.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx@@ -135,6 +135,40 @@ export function AccessPane() {}));},},+ {+ id: "unmask",+ title: t("sql-editor.grant-type-unmask"),+ description: t("sql-editor.access-search.scope.unmask.description"),+ options: [+ {+ value: "true",+ keywords: ["yes", "true"],+ render: () => t("common.yes"),+ },+ {+ value: "false",+ keywords: ["no", "false"],+ render: () => t("common.no"),+ },+ ],+ },+ {+ id: "export",+ title: t("sql-editor.grant-type-export"),+ description: t("sql-editor.access-search.scope.export.description"),+ options: [+ {+ value: "true",+ keywords: ["yes", "true"],+ render: () => t("common.yes"),+ },+ {+ value: "false",+ keywords: ["no", "false"],+ render: () => t("common.no"),+ },+ ],+ },];}, [t, projectName, fetchDatabases]);@@ -145,6 +179,8 @@ export function AccessPane() {.map((s) => s.value) as AccessGrantFilterStatus[];const databaseScope = searchParams.scopes.find((s) => s.id === "database");+ const unmaskScope = searchParams.scopes.find((s) => s.id === "unmask");+ const exportScope = searchParams.scopes.find((s) => s.id === "export");const f: AccessFilter = {status: selectedStatuses,@@ -152,6 +188,12 @@ export function AccessPane() {if (databaseScope?.value) {f.target = databaseScope.value;}+ if (unmaskScope?.value === "true" || unmaskScope?.value === "false") {+ f.unmask = unmaskScope.value === "true";+ }+ if (exportScope?.value === "true" || exportScope?.value === "false") {+ f.export = exportScope.value === "true";+ }const queryText = searchParams.query.trim();if (queryText) {f.statement = queryText;diff --git a/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx b/frontend/src/react/components/sql-editor/RequestDrawerHost.tsxindex 2004c18830..48ba8ba889 100644--- a/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx+++ b/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx@@ -21,6 +21,7 @@ type AccessGrantArgs = {query?: string;targets: string[];unmask?: boolean;+ export?: boolean;};type ContextValue = {@@ -74,6 +75,7 @@ export function RequestDrawerHost({ children }: { children: ReactNode }) {query={grantArgs.query}targets={grantArgs.targets}unmask={grantArgs.unmask}+ export={grantArgs.export}onClose={() => setGrantArgs(null)}/>)}diff --git a/frontend/src/react/components/sql-editor/RequestExportButton.tsx b/frontend/src/react/components/sql-editor/RequestExportButton.tsxnew file mode 100644index 0000000000..e7f94aaa1d--- /dev/null+++ b/frontend/src/react/components/sql-editor/RequestExportButton.tsx@@ -0,0 +1,109 @@+import { Download } from "lucide-react";+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { FeatureBadge } from "@/react/components/FeatureBadge";+import { PermissionGuard } from "@/react/components/PermissionGuard";+import { Button } from "@/react/components/ui/button";+import { useAppProject } from "@/react/hooks/useAppProject";+import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";+import { useRequestDrawerHost } from "./RequestDrawerHost";++interface Props {+ readonly size?: "sm" | "default";+ readonly statement?: string;+ readonly targets: string[];+}++/**+ * Shown in the result panel when the query-data policy disables export but+ * the project allows just-in-time access. Clicking it opens the access-grant+ * drawer pre-filled with the current database, statement, and both the unmask+ * and export capabilities checked.+ */+export function RequestExportButton({+ size = "sm",+ statement,+ targets,+}: Props) {+ const { t } = useTranslation();++ // When the layout-level host is mounted (typical case inside the SQL+ // Editor), opening the drawer dispatches up to the host so it survives+ // ancestor unmounts. Local state stays as a fallback for standalone callers.+ const drawerHost = useRequestDrawerHost();+ const [showDrawer, setShowDrawer] = useState(false);++ const loadSubscription = useAppStore((s) => s.loadSubscription);+ // The SQL editor route doesn't mount the dashboard shells that load the+ // app-store subscription, so load it here before reading feature gates.+ useEffect(() => {+ void loadSubscription();+ }, [loadSubscription]);++ const projectName = useSQLEditorEditorState((s) => s.project);+ const project = useAppProject(projectName);+ const hasJITFeature = useAppStore((s) =>+ s.hasFeature(PlanFeature.FEATURE_JIT)+ );++ if (!project?.allowJustInTimeAccess) {+ return null;+ }++ const handleClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ if (drawerHost) {+ drawerHost.openAccessGrantDrawer({+ query: statement,+ targets,+ unmask: true,+ export: true,+ });+ } else {+ setShowDrawer(true);+ }+ };++ return (+ <div>+ <PermissionGuard+ permissions={["bb.accessGrants.create"]}+ project={project}+ >+ {({ disabled }) => (+ <Button+ size={size}+ variant="default"+ disabled={disabled || !hasJITFeature}+ onClick={handleClick}+ className={cn("gap-x-1")}+ >+ {hasJITFeature ? (+ <Download className="size-4" />+ ) : (+ <FeatureBadge+ clickable={false}+ feature={PlanFeature.FEATURE_JIT}+ />+ )}+ {t("sql-editor.request-export")}+ </Button>+ )}+ </PermissionGuard>++ {showDrawer && (+ <AccessGrantRequestDrawer+ query={statement}+ targets={targets}+ unmask={true}+ export={true}+ onClose={() => setShowDrawer(false)}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsxindex 6ca0447ce1..994d0e6bb5 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx@@ -11,6 +11,7 @@ import {} from "@/react/components/DataExportButton";import { DatabaseTableView } from "@/react/components/database";import { EngineIconPath } from "@/react/components/instance/constants";+import { RequestExportButton } from "@/react/components/sql-editor/RequestExportButton";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";@@ -22,7 +23,6 @@ import {useCurrentSQLEditorTab,useSQLEditorTabState,} from "@/react/stores/sqlEditor/tab";-import { isValidDatabaseName } from "@/types";import { ExportFormat } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";@@ -33,10 +33,6 @@ import {getInstanceResource,hexToRgb,} from "@/utils";-import { buildDownloadBlob, type DownloadGroup } from "@/utils/sql-download";-import { SQL_ENGINE_QUOTES } from "@/utils/sql-download/engines";-import { downloadErrorMessage } from "@/utils/sql-download/error-messages";-import { isDev } from "@/utils/util";import { TabContextMenu } from "./ContextMenu";import { type CloseTabAction, resultTabEvents } from "./resultTabContext";@@ -93,11 +89,6 @@ export function BatchQuerySelect({Set<string>>(new Set());- // Editor's per-execution row limit. Used by the dev-path export to- // infer probable truncation: `r.rows.length === resultRowsLimit` →- // query capped, likely more rows available.- const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);-// Subscribe to the current tab's `databaseQueryContexts` Map. Immer// produces a fresh Map (and inner arrays) on every mutation, so the// selector re-runs whenever `preExecute` adds a context or `runQuery`@@ -153,30 +144,34 @@ export function BatchQuerySelect({[queriedDatabaseNames, getDatabaseByName]);- // Drop SQL from the export drawer when isDev() is active and any- // user-SELECTED database's engine can't be rendered as INSERTs. Gating- // on the full queried-database set was too conservative (a tab with one- // MongoDB + one MySQL would hide SQL even when the user selected only- // MySQL). Empty selection shows all formats so the user sees the SQL- // option before picking incompatible databases.- const supportFormats = useMemo(() => {- const all = [+ const supportFormats = useMemo(+ () => [ExportFormat.CSV,ExportFormat.JSON,ExportFormat.SQL,ExportFormat.XLSX,- ];- if (!isDev()) return all;- if (selectedDatabaseNames.size === 0) return all;- const allSupportSql = Array.from(selectedDatabaseNames).every((name) => {- const db = getDatabaseByName(name);- if (!isValidDatabaseName(db.name)) return true; // skipped at export time- return SQL_ENGINE_QUOTES.has(getInstanceResource(db).engine);- });- return allSupportSql- ? all- : [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];- }, [selectedDatabaseNames, getDatabaseByName]);+ ],+ []+ );++ // The batch was run from a single user-typed statement against many+ // databases — pull it from any one context (they all carry the same+ // params.statement). Used as the request-export drawer seed when the+ // policy disables direct export.+ const batchStatement = useMemo(() => {+ for (const context of contextsByDatabase.values()) {+ if (context?.params.statement) return context.params.statement;+ }+ return "";+ }, [contextsByDatabase]);++ // Mirror SingleResultView / ResultView: when policy disables export,+ // swap the Export button for a "Request export" affordance that opens+ // the access-grant drawer pre-filled with the queried databases and+ // the batch statement. The grant-allows-export path is naturally+ // handled per-database inside each tab's SingleResultView since the+ // applied grant is per-result.+ const showExport = !queryDataPolicy?.disableExport;const handleCloseSingleResultView = (item: BatchQueryItem) => {const contexts = currentTab?.databaseQueryContexts?.get(item.database.name);@@ -228,118 +223,8 @@ export function BatchQuerySelect({const validateExport = () =>selectedDatabaseNames.size > 0 && selectedDatabaseNames.size <= MAX_EXPORT;- const handleExport = ({ options, resolve, reject }: DataExportRequest) => {+ const handleExport = ({ options, resolve }: DataExportRequest) => {void (async () => {- // === Dev path: client-side ZIP via buildDownloadBlob ===- if (isDev()) {- try {- // Stale format guard: drop the export if the user-selected format- // is no longer in the (selection-aware) supportFormats list.- if (!supportFormats.includes(options.format)) {- reject(- "The selected format is not supported for the current database selection. Pick a different format."- );- return;- }- const tab = currentTab;- const groups: DownloadGroup[] = [];- const limit = options.limit > 0 ? options.limit : Infinity;- for (const databaseName of Array.from(selectedDatabaseNames)) {- const database = getDatabaseByName(databaseName);- // Skip stub-database returns with a WARN toast so the user- // knows their selection became stale (tab torn down mid-export).- if (!isValidDatabaseName(database.name)) {- useAppStore.getState().notify({- module: "bytebase",- style: "WARN",- title: t("sql-editor.batch-export.failed-for-db", {- db: databaseName,- }),- description: t(- "sql-editor.batch-export.database-no-longer-available"- ),- });- continue;- }- const context = head(tab?.databaseQueryContexts?.get(databaseName));- const resultSet = context?.resultSet;- const resultError =- resultSet?.error ||- resultSet?.results.find((r) => r.error)?.error;- if (resultError) {- useAppStore.getState().notify({- module: "bytebase",- style: "CRITICAL",- title: t("sql-editor.batch-export.failed-for-db", {- db: databaseName,- }),- description: resultError,- });- continue;- }- const results = resultSet?.results ?? [];- if (results.length === 0) continue;- // Truncation inference using execution-time limit.- const executedLimit = context?.params.limit ?? resultRowsLimit;- if (- options.limit > 0 &&- results.some(- (r) =>- r.rows.length === executedLimit &&- options.limit > r.rows.length- )- ) {- useAppStore.getState().notify({- module: "bytebase",- style: "WARN",- title: t("sql-editor.batch-export.failed-for-db", {- db: databaseName,- }),- description: t(- "sql-editor.batch-export.export-limit-exceeds-executed",- {- exportLimit: options.limit,- executedLimit,- }- ),- });- }- const { databaseName: dbSeg, instanceName } =- extractDatabaseResourceName(database.name);- groups.push({- instanceId: instanceName,- databaseName: dbSeg,- engine: getInstanceResource(database).engine,- statements: results.map((r) => ({- result:- r.rows.length > limit- ? { ...r, rows: r.rows.slice(0, limit) }- : r,- statement: r.statement || context?.params.statement || "",- })),- });- }- if (groups.length === 0) {- reject(t("sql-editor.batch-export.no-results"));- return;- }- const out = await buildDownloadBlob({- groups,- format: options.format,- baseFilename: `batch-export.${dayjs().format(- "YYYY-MM-DDTHH-mm-ss"- )}`,- password: options.password,- });- const content = new Uint8Array(await out.blob.arrayBuffer());- resolve([{ content, filename: out.filename }]);- setSelectedDatabaseNames(new Set());- } catch (e) {- reject(downloadErrorMessage(e, t));- }- return;- }-// === Prod path: per-database backend Export RPC ===const contents: DownloadContent[] = [];const tabsState = getSQLEditorTabsState();@@ -415,36 +300,43 @@ export function BatchQuerySelect({)}<div className="mb-2">- <DataExportButton- size="sm"- viewMode="DRAWER"- supportFormats={supportFormats}- supportPassword- text={t("sql-editor.batch-export.self")}- tooltip={t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}- validate={validateExport}- maximumExportCount={queryDataPolicy.maximumResultRows}- onExport={handleExport}- formContent={- <div className="w-full flex flex-col gap-y-2">- <div>- <p className="text-sm font-medium text-control">- {t("database.select")}- <span className="text-error ml-0.5">*</span>- </p>- <span className="text-xs text-control-light">- {t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}- </span>+ {showExport ? (+ <DataExportButton+ size="sm"+ viewMode="DRAWER"+ supportFormats={supportFormats}+ supportPassword+ text={t("sql-editor.batch-export.self")}+ tooltip={t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}+ validate={validateExport}+ maximumExportCount={queryDataPolicy.maximumResultRows}+ onExport={handleExport}+ formContent={+ <div className="w-full flex flex-col gap-y-2">+ <div>+ <p className="text-sm font-medium text-control">+ {t("database.select")}+ <span className="text-error ml-0.5">*</span>+ </p>+ <span className="text-xs text-control-light">+ {t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}+ </span>+ </div>+ <DatabaseTableView+ databases={databaseList}+ mode="PROJECT"+ selectedNames={selectedDatabaseNames}+ onSelectedNamesChange={setSelectedDatabaseNames}+ /></div>- <DatabaseTableView- databases={databaseList}- mode="PROJECT"- selectedNames={selectedDatabaseNames}- onSelectedNamesChange={setSelectedDatabaseNames}- />- </div>- }- />+ }+ />+ ) : (+ <RequestExportButton+ statement={batchStatement}+ targets={queriedDatabaseNames}+ />+ )}</div><div className="overflow-x-auto pb-2 flex-1">diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxindex 215f809ed9..7763e617b1 100644--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -8,6 +8,7 @@ import {DataExportButton,type DataExportRequest,} from "@/react/components/DataExportButton";+import { RequestExportButton } from "@/react/components/sql-editor/RequestExportButton";import { RequestQueryButton } from "@/react/components/sql-editor/RequestQueryButton";import { Button } from "@/react/components/ui/button";import {@@ -33,14 +34,9 @@ import type { Database } from "@/types/proto-es/v1/database_service_pb";import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";import { hasProjectPermissionV2 } from "@/utils/iam/permission";-import { buildDownloadBlob } from "@/utils/sql-download";-import { SQL_ENGINE_QUOTES } from "@/utils/sql-download/engines";-import { downloadErrorMessage } from "@/utils/sql-download/error-messages";-import { isDev } from "@/utils/util";import {extractDatabaseResourceName,getDatabaseProject,- getInstanceResource,} from "@/utils/v1/database";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";@@ -95,11 +91,6 @@ export function ResultView({policyType: PolicyType.DATA_QUERY,});}, [environment, getOrFetchPolicyByParentAndType]);- // The editor's per-execution row limit. A result whose .rows.length- // exactly equals this is probably truncated; fewer rows is probably- // complete. Used by the dev-path export to WARN only when the user's- // requested limit can't be satisfied from the cached result.- const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);const permissionDeniedError = useMemo<PermissionDeniedDetail | undefined@@ -137,6 +128,121 @@ export function ResultView({return false;}, [queryDataPolicy, envQueryDataPolicy]);+ // Show the real export button when the policy allows export, OR when the+ // user holds any active export-capable grant for this statement — even if+ // it's not the grant the Query path applied (Query prefers Unmask, so the+ // applied grant may be unmask-only while a separate export grant exists).+ // Without this independent search the UI would hide the Export button and+ // direct the user to "Request export" despite already having a grant — see+ // PR #20491 bot review (#3349086832).+ const searchMyAccessGrants = useAppStore((s) => s.searchMyAccessGrants);+ const databaseProjectName = database.project;+ const [exportGrantName, setExportGrantName] = useState<string>("");++ useEffect(() => {+ if (+ !queryDataPolicy?.disableExport ||+ !executeParams?.statement ||+ !databaseProjectName+ ) {+ setExportGrantName("");+ return;+ }+ let canceled = false;+ void (async () => {+ const result = await searchMyAccessGrants({+ parent: databaseProjectName,+ filter: {+ target: database.name,+ // Exact match — the backend's JIT authorization path uses+ // `query == ...` (preCheckAccess in sql_service.go). A+ // substring match (`statement: ...`) would expose Export for+ // queries that don't actually match any grant. PR #20491 bot+ // review #3349385091.+ statementExact: executeParams.statement,+ status: ["ACTIVE"],+ export: true,+ },+ });+ if (!canceled) {+ setExportGrantName(result.accessGrants[0]?.name ?? "");+ }+ })();+ return () => {+ canceled = true;+ };+ }, [+ queryDataPolicy?.disableExport,+ executeParams?.statement,+ databaseProjectName,+ database.name,+ searchMyAccessGrants,+ ]);++ // Pull display fields from the cache populated by the search above.+ const exportGrantIssue = useAppStore((s) =>+ exportGrantName ? (s.accessGrantsByName[exportGrantName]?.issue ?? "") : ""+ );+ const exportGrantReason = useAppStore((s) =>+ exportGrantName ? (s.accessGrantsByName[exportGrantName]?.reason ?? "") : ""+ );++ const showExport = !queryDataPolicy?.disableExport || !!exportGrantName;++ // Surface a tooltip explaining the grant-based bypass only when the policy+ // itself would normally block export — in the everyday "policy allows+ // export" case, no tooltip is needed. Attributes to the export-capable+ // grant (which may differ from the Query-applied grant when the user has+ // separate unmask + export grants for the same statement).+ const exportTooltip = useMemo<ReactNode>(() => {+ if (!queryDataPolicy?.disableExport || !exportGrantName) {+ return undefined;+ }+ const issueHref = exportGrantIssue+ ? exportGrantIssue.startsWith("/")+ ? exportGrantIssue+ : `/${exportGrantIssue}`+ : undefined;+ return (+ <div className="flex flex-col gap-y-1">+ <span>{t("sql-editor.export-enabled-by-grant")}</span>+ {issueHref ? (+ <a+ href={issueHref}+ target="_blank"+ rel="noreferrer"+ className="break-all underline"+ onClick={(e) => e.stopPropagation()}+ >+ {exportGrantName}+ </a>+ ) : (+ <span className="break-all">{exportGrantName}</span>+ )}+ {exportGrantReason && (+ <span className="text-xs opacity-80">{exportGrantReason}</span>+ )}+ </div>+ );+ }, [+ t,+ queryDataPolicy?.disableExport,+ exportGrantName,+ exportGrantIssue,+ exportGrantReason,+ ]);++ // When direct export is unavailable, offer a "Request export" affordance that+ // opens the access-grant drawer (pre-filled with this database, statement,+ // and unmask + export checked). The button self-hides when the project+ // doesn't allow just-in-time access.+ const requestExportButton = executeParams ? (+ <RequestExportButton+ statement={executeParams.statement}+ targets={[database.name]}+ />+ ) : null;+const filteredResults = useMemo(() => {if (!resultSet) return [];return resultSet.results.filter(@@ -146,140 +252,21 @@ export function ResultView({const tabName = (index: number) => `${t("common.query")} #${index + 1}`;- // Format list for the export drawer. Under the isDev() gate, drop SQL when- // the database's engine can't be serialized as INSERTs — otherwise- // selecting SQL would reach serializeSQL and throw UnsupportedFormat at- // runtime. Production (backend Export RPC) handles all engines.- const supportFormats = useMemo(() => {- const all = [+ const supportFormats = useMemo(+ () => [ExportFormat.CSV,ExportFormat.JSON,ExportFormat.SQL,ExportFormat.XLSX,- ];- if (!isDev()) return all;- const engine = getInstanceResource(database).engine;- return SQL_ENGINE_QUOTES.has(engine)- ? all- : [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];- }, [database]);+ ],+ []+ );const handleExport = async (req: DataExportRequest & { statement: string }) => {const { options, resolve, reject, statement } = req;- // === Dev path: client-side ZIP via buildDownloadBlob ===- // Production builds keep using the backend Export RPC below until the- // client-side download module ships GA.- if (isDev()) {- try {- // Guard against stale format selection: DataExportButton keeps its- // `format` state across engine changes, so a user who picked SQL- // before an engine switch would still submit SQL here.- if (!supportFormats.includes(options.format)) {- reject(- "The selected format is not supported for the current database engine. Pick a different format."- );- return;- }- const { databaseName, instanceName } = extractDatabaseResourceName(- database.name- );- const engine = getInstanceResource(database).engine;- // Abort the whole export if ANY sub-result errored — including- // SET statements (which we drop from `candidates` below for- // serialization purposes). Backend's doExport (sql_service.go:1109)- // iterates every result and aborts on the first error regardless of- // whether the statement would have produced rows, so scanning the- // unfiltered resultSet here keeps us in lockstep. Skipping the SET- // filter for the error check covers cases like- // `SELECT ...; SET unknown_var = 1;` where the failing statement- // is non-row-producing.- const erroredResult = resultSet?.results?.find((r) => r.error);- if (erroredResult) {- reject(erroredResult.error);- return;- }- const candidates =- viewMode === "MULTI-RESULT"- ? filteredResults- : (resultSet?.results?.slice(0, 1) ?? []);- if (candidates.length === 0) {- reject(t("sql-editor.batch-export.no-results"));- return;- }- const sourceResults = candidates;- const baseFilename = `${databaseName}.${dayjs().format(- "YYYY-MM-DDTHH-mm-ss"- )}`;- // Apply the export drawer's row limit per-result, mirroring the- // server-side LIMIT clause semantics. The dev path operates on- // already-fetched rows; when the user-requested limit exceeds the- // cached count we can only serve what we have.- const limit = options.limit > 0 ? options.limit : Infinity;- // Probable-truncation inference: compare cached row count against- // the limit IN EFFECT AT EXECUTION TIME, captured in- // `executeParams.limit`. The current editor `resultRowsLimit` is a- // snapshot of when the user clicked Export (they may have changed- // it between Run and Export), so it can't be the ground truth.- const executedLimit = executeParams.limit ?? resultRowsLimit;- if (- options.limit > 0 &&- sourceResults.some(- (r) =>- r.rows.length === executedLimit && options.limit > r.rows.length- )- ) {- useAppStore.getState().notify({- module: "bytebase",- style: "WARN",- title: t("sql-editor.batch-export.failed-for-db", {- db: databaseName,- }),- description: t(- "sql-editor.batch-export.export-limit-exceeds-executed",- {- exportLimit: options.limit,- executedLimit,- }- ),- });- }- const out = await buildDownloadBlob({- groups: [- {- instanceId: instanceName,- databaseName,- engine,- statements: sourceResults.map((r) => ({- result:- r.rows.length > limit- ? { ...r, rows: r.rows.slice(0, limit) }- : r,- // For multi-result, `r.statement` is the substatement the- // backend split out — that's what the user should see. For- // single-result, prefer the caller's verbatim `statement`- // (the per-result form may have an auto-appended LIMIT).- statement:- viewMode === "MULTI-RESULT"- ? r.statement || statement- : statement || r.statement,- })),- },- ],- format: options.format,- baseFilename,- password: options.password,- });- const content = new Uint8Array(await out.blob.arrayBuffer());- resolve([{ content, filename: out.filename }]);- } catch (e) {- reject(downloadErrorMessage(e, t));- }- return;- }-// === Prod path: backend Export RPC ===const tabsState = getSQLEditorTabsState();const admin =@@ -354,9 +341,13 @@ export function ResultView({params={executeParams}database={database}result={resultSet.results[0]}- showExport={!queryDataPolicy?.disableExport}+ showExport={showExport}+ exportTooltip={exportTooltip}maximumExportCount={queryDataPolicy?.maximumResultRows}onExport={handleExport}+ requestExportSlot={+ !showExport ? requestExportButton : undefined+ }/>))}@@ -380,7 +371,7 @@ export function ResultView({</Tooltip>))}</TabsList>- {!queryDataPolicy?.disableExport && (+ {showExport ? (<div className="mb-1"><DataExportButtonsize="sm"@@ -388,6 +379,7 @@ export function ResultView({supportFormats={supportFormats}viewMode="DRAWER"supportPassword+ tooltip={exportTooltip}maximumExportCount={queryDataPolicy?.maximumResultRows}onExport={(req) =>handleExport({@@ -397,6 +389,8 @@ export function ResultView({}/></div>+ ) : (+ <div className="mb-1">{requestExportButton}</div>)}</div>{filteredResults.map((result, i) => (diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxindex 44c711ec76..d4298f5202 100644--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -8,7 +8,14 @@ import {InfoIcon,XIcon,} from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import {@@ -45,13 +52,12 @@ import {type RowValue,} from "@/types/proto-es/v1/sql_service_pb";import { createExplainToken } from "@/utils/pev2";-import { SQL_ENGINE_QUOTES } from "@/utils/sql-download/engines";import {flattenElasticsearchSearchResult,flattenNoSQLQueryResult,} from "@/utils/sqlResult";import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";-import { isDev, isNullOrUndefined } from "@/utils/util";+import { isNullOrUndefined } from "@/utils/util";import {extractDatabaseResourceName,getDatabaseEnvironment,@@ -81,8 +87,14 @@ export interface SingleResultViewProps {database: Database;result: QueryResult;showExport: boolean;+ // Optional tooltip shown on the export button — used to explain when the+ // export is enabled by a JIT access grant despite the policy disabling it.+ exportTooltip?: ReactNode;maximumExportCount?: number;onExport?: (req: DataExportRequest & { statement: string }) => void;+ // Rendered in the toolbar when `showExport` is false — e.g. a+ // "Request export" affordance when the policy disables direct export.+ requestExportSlot?: ReactNode;}type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";@@ -217,8 +229,10 @@ function SingleResultViewInner({database,result,showExport,+ exportTooltip,maximumExportCount,onExport,+ requestExportSlot,engine,activeResult: _activeResult,columns,@@ -240,22 +254,15 @@ function SingleResultViewInner({const { runQuery } = useExecuteSQL();const { copyAll } = useSelectionContext();- // Under isDev() (client-side download), drop SQL from the format list- // when the engine isn't in SQL_ENGINE_QUOTES — otherwise selecting SQL- // would reach serializeSQL and throw UnsupportedFormat at runtime.- // Production (backend Export RPC) handles all engines.- const supportFormats = useMemo(() => {- const all = [+ const supportFormats = useMemo(+ () => [ExportFormat.CSV,ExportFormat.JSON,ExportFormat.SQL,ExportFormat.XLSX,- ];- if (!isDev()) return all;- return SQL_ENGINE_QUOTES.has(engine)- ? all- : [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];- }, [engine]);+ ],+ []+ );const dataTableRef = useRef<VirtualDataTableHandle | VirtualDataBlockHandle | null@@ -586,17 +593,20 @@ function SingleResultViewInner({{t("common.copy")}</Button>)}- {showExport && (+ {showExport ? (<DataExportButtonsize="sm"disabled={!result || isEmpty(result)}supportFormats={supportFormats}viewMode="DRAWER"supportPassword+ tooltip={exportTooltip}maximumExportCount={maximumExportCount}formContent={<DatabaseInfo database={database} />}onExport={handleExport}/>+ ) : (+ requestExportSlot)}</div><SelectionCopyTooltips />diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex be58162149..4150524666 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -345,6 +345,7 @@"n-selected": "{{n}} selected","name": "Name","next": "Next",+ "no": "No","no-data": "No data","not-started": "Not started","ok": "OK",@@ -465,6 +466,7 @@"warning": "Warning","webhooks": "Webhooks","write-only": "write only",+ "yes": "Yes","you": "you"},"create-db": {@@ -819,11 +821,17 @@"not-found": "Not Found"},"export-center": {- "data-export": "Data Export"+ "data-export": "Data Export",+ "deprecated": {+ "description": "Export Center will be deprecated in a future release. For new data exports, consider using the SQL Editor's export action.",+ "open-sql-editor": "Go to SQL Editor",+ "title": "Export Center will be deprecated"+ }},"export-data": {"export-format": "Export format","export-rows": "Export rows",+ "generate-password": "Generate password","password-info": "Provide a password to encrypt the export file.","password-optional": "Encrypt with password (Optional)"},@@ -1140,8 +1148,14 @@"access-grant": {"advanced-search": {"scope": {+ "export": {+ "description": "Filter by whether the grant allows exporting the query result"+ },"status": {"description": "Filter by access grant status"+ },+ "unmask": {+ "description": "Filter by whether the grant allows unmasking sensitive data"}}},@@ -2515,11 +2529,18 @@"database": {"description": "Filter by database"},+ "export": {+ "description": "Filter by whether the grant allows exporting the query result"+ },"status": {"description": "Search by the access grant status"+ },+ "unmask": {+ "description": "Filter by whether the grant allows unmasking sensitive data"}}},+ "access-type-export": "Export the query result","access-type-unmask": "See unmasked sensitive data","activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?",@@ -2531,10 +2552,7 @@"allow-admin-mode-only": "Instance <instance></instance> is accessible in admin mode only.","and-n-more-databases": "and {{n}} more databases","batch-export": {- "database-no-longer-available": "Database is no longer available in the current tab.",- "export-limit-exceeds-executed": "Export limit {{exportLimit}} exceeds the executed query's row limit ({{executedLimit}}); exporting cached rows only.","failed-for-db": "Failed to export data for {{db}}",- "no-results": "No results to download.","self": "Batch export","tooltip": "Select at most {{max}} databases to batch export latest query results"},@@ -2568,13 +2586,6 @@"copy-url": "Copy URL","ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.","download-as-file": "Download as {{file}}",- "download-encryption-failed": "Failed to encrypt download.",- "download-failed": "Download failed.",- "download-too-large": "Result is too large for download. Reduce the row count or use Export.",- "download-too-large-bytes": "Download is ~{{megabytes}} MB across {{statements}} statement(s); limit is {{capMb}} MB. Reduce the result size or use Export.",- "download-too-large-cells": "Download has {{cells}} cells across {{statements}} statement(s); limit is {{limit}}. Reduce the row count or use Export.",- "download-too-large-xlsx-columns": "XLSX cannot exceed {{limit}} columns; got {{count}}. Use Export or a different format.",- "download-too-large-xlsx-rows": "XLSX cannot exceed {{limit}} data rows; got {{count}}. Use Export or a different format.","duration-day": "{{days}} day","duration-days": "{{days}} days","duration-hour": "{{hours}} hour",@@ -2584,10 +2595,12 @@"expire-at": "Expire at {{time}}","expire-in": "Expire in {{time}}","expired": "Expired",+ "export-enabled-by-grant": "Export enabled by access grant","format": "Format","format-default": "Default","format-sql": "Format SQL","generate-sql": "Generate SQL",+ "grant-type-export": "Export","grant-type-unmask": "Unmask","hex-format": "Hexadecimal format","hint-tips": {@@ -2640,6 +2653,7 @@"request-aborted": "User aborted the request","request-access": "Request Access","request-data-access": "Request Data Access",+ "request-export": "Request export","request-jit": "Request just-in-time access","request-query": "Request query","result-limit": {@@ -2666,8 +2680,6 @@"self": "SQL Editor","show-databases-without-query-permission": "Show databases without query permissions","show-in-editor": "Show in Editor",- "sql-download-engine-unsupported": "SQL download is not supported for engine {{engine}}.",- "sql-download-unavailable": "SQL download is unavailable for this connection.","sync-in-progress": "Sync in progress","tab": {"context-menu": {diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex cc137fba61..e9ef6c5119 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -345,6 +345,7 @@"n-selected": "{{n}} seleccionados","name": "Nombre","next": "Siguiente",+ "no": "No","no-data": "Sin datos","not-started": "No iniciado","ok": "OK",@@ -465,6 +466,7 @@"warning": "Advertencia","webhooks": "Webhooks","write-only": "solo escritura",+ "yes": "Sí","you": "tu"},"create-db": {@@ -819,11 +821,17 @@"not-found": "No encontrado"},"export-center": {- "data-export": "Exportación de datos"+ "data-export": "Exportación de datos",+ "deprecated": {+ "description": "El Centro de Exportación será deprecado en una versión futura. Para nuevas exportaciones de datos, considere usar la acción de exportación del Editor SQL.",+ "open-sql-editor": "Ir al Editor SQL",+ "title": "El Centro de Exportación será deprecado"+ }},"export-data": {"export-format": "Formato de exportación","export-rows": "Exportar filas",+ "generate-password": "Generar contraseña","password-info": "Proporcione una contraseña para cifrar el archivo de exportación.","password-optional": "Cifrar con contraseña (opcional)"},@@ -1140,8 +1148,14 @@"access-grant": {"advanced-search": {"scope": {+ "export": {+ "description": "Filtrar por si la concesión permite exportar el resultado de la consulta"+ },"status": {"description": "Filtrar por estado de la concesión de acceso"+ },+ "unmask": {+ "description": "Filtrar por si la concesión permite ver datos sensibles sin enmascarar"}}},@@ -2515,11 +2529,18 @@"database": {"description": "Filtrar por base de datos"},+ "export": {+ "description": "Filtrar por si la concesión permite exportar el resultado de la consulta"+ },"status": {"description": "Buscar por el estado de la concesión de acceso"+ },+ "unmask": {+ "description": "Filtrar por si la concesión permite ver datos sensibles sin enmascarar"}}},+ "access-type-export": "Exportar el resultado de la consulta","access-type-unmask": "Ver datos sensibles sin enmascarar","activate-access": "Activar","activate-confirm": "¿Está seguro de que desea activar esta concesión de acceso?",@@ -2531,10 +2552,7 @@"allow-admin-mode-only": "La instancia <instance></instance> solo es accesible en modo administrador.","and-n-more-databases": "y {{n}} bases de datos más","batch-export": {- "database-no-longer-available": "La base de datos ya no está disponible en la pestaña actual.",- "export-limit-exceeds-executed": "El límite de exportación {{exportLimit}} supera el límite de filas de la consulta ejecutada ({{executedLimit}}); se exportarán solo las filas en caché.","failed-for-db": "No se pudieron exportar los datos de {{db}}",- "no-results": "No hay resultados para descargar.","self": "Exportación por lotes","tooltip": "Seleccione como máximo {{max}} bases de datos para exportar por lotes los resultados de las últimas consultas"},@@ -2568,13 +2586,6 @@"copy-url": "Copiar URL","ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.","download-as-file": "Descargar como {{file}}",- "download-encryption-failed": "No se pudo cifrar la descarga.",- "download-failed": "Error en la descarga.",- "download-too-large": "El resultado es demasiado grande para descargar. Reduzca el número de filas o use Exportar.",- "download-too-large-bytes": "La descarga es de ~{{megabytes}} MB en {{statements}} sentencia(s); el límite es {{capMb}} MB. Reduzca el tamaño del resultado o use Exportar.",- "download-too-large-cells": "La descarga tiene {{cells}} celdas en {{statements}} sentencia(s); el límite es {{limit}}. Reduzca el número de filas o use Exportar.",- "download-too-large-xlsx-columns": "XLSX no puede superar {{limit}} columnas; se obtuvieron {{count}}. Use Exportar o un formato diferente.",- "download-too-large-xlsx-rows": "XLSX no puede superar {{limit}} filas de datos; se obtuvieron {{count}}. Use Exportar o un formato diferente.","duration-day": "{{days}} día","duration-days": "{{days}} días","duration-hour": "{{hours}} hora",@@ -2584,10 +2595,12 @@"expire-at": "Expira el {{time}}","expire-in": "Expira en {{time}}","expired": "Expirado",+ "export-enabled-by-grant": "Exportación habilitada por la concesión de acceso","format": "Formato","format-default": "Predeterminado","format-sql": "Formatear SQL","generate-sql": "Generar SQL",+ "grant-type-export": "Exportar","grant-type-unmask": "Desenmascarar","hex-format": "Formato hexadecimal","hint-tips": {@@ -2640,6 +2653,7 @@"request-aborted": "El usuario abortó la solicitud","request-access": "Solicitar acceso","request-data-access": "Solicitar acceso a datos",+ "request-export": "Solicitar exportación","request-jit": "Solicitar acceso just-in-time","request-query": "Solicitar consulta","result-limit": {@@ -2666,8 +2680,6 @@"self": "Editor de SQL","show-databases-without-query-permission": "Muestra las bases de datos que no tienen permisos de consulta","show-in-editor": "Mostrar en editor",- "sql-download-engine-unsupported": "La descarga SQL no es compatible con el motor {{engine}}.",- "sql-download-unavailable": "La descarga SQL no está disponible para esta conexión.","sync-in-progress": "Sincronización en progreso","tab": {"context-menu": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 0254f4a608..be84a28c51 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -345,6 +345,7 @@"n-selected": "{{n}} 件選択中","name": "名前","next": "次のステップ",+ "no": "いいえ","no-data": "データなし","not-started": "未開始","ok": "わかりました",@@ -465,6 +466,7 @@"warning": "警告する","webhooks": "Webhook","write-only": "書き込み専用",+ "yes": "はい","you": "あなた"},"create-db": {@@ -819,11 +821,17 @@"not-found": "ページが見つかりません"},"export-center": {- "data-export": "データエクスポート"+ "data-export": "データエクスポート",+ "deprecated": {+ "description": "エクスポートセンターは将来のリリースで非推奨になります。新しいデータエクスポートには、SQL エディターのエクスポート機能の使用をご検討ください。",+ "open-sql-editor": "SQL エディターを開く",+ "title": "エクスポートセンターは非推奨になります"+ }},"export-data": {"export-format": "エクスポート形式","export-rows": "エクスポート行数",+ "generate-password": "パスワードを生成","password-info": "エクスポートされたファイルを暗号化するためのパスワードを入力します","password-optional": "パスワード暗号化の設定 (オプション)"},@@ -1140,8 +1148,14 @@"access-grant": {"advanced-search": {"scope": {+ "export": {+ "description": "付与がクエリ結果のエクスポートを許可するかどうかでフィルター"+ },"status": {"description": "アクセス権限のステータスでフィルター"+ },+ "unmask": {+ "description": "付与が機密データのマスク解除を許可するかどうかでフィルター"}}},@@ -2515,11 +2529,18 @@"database": {"description": "データベースでフィルター"},+ "export": {+ "description": "付与がクエリ結果のエクスポートを許可するかどうかでフィルター"+ },"status": {"description": "アクセス許可のステータスで検索"+ },+ "unmask": {+ "description": "付与が機密データのマスク解除を許可するかどうかでフィルター"}}},+ "access-type-export": "クエリ結果をエクスポート","access-type-unmask": "マスク解除された機密データを表示","activate-access": "有効化","activate-confirm": "このアクセス付与を有効化してもよろしいですか?",@@ -2531,10 +2552,7 @@"allow-admin-mode-only": "インスタンス <instance></instance> には管理者モードでのみアクセスできます。","and-n-more-databases": "他 {{n}} 件のデータベース","batch-export": {- "database-no-longer-available": "現在のタブでデータベースを利用できません。",- "export-limit-exceeds-executed": "エクスポート上限 {{exportLimit}} が実行済みクエリの行数上限 ({{executedLimit}}) を超えています。キャッシュされた行のみエクスポートします。","failed-for-db": "{{db}} のデータのエクスポートに失敗しました",- "no-results": "ダウンロードできる結果がありません。","self": "一括エクスポート","tooltip": "最新のクエリ結果を一括エクスポートするには、最大 {{max}} 個のデータベースを選択してください"},@@ -2568,13 +2586,6 @@"copy-url": "URLをコピー","ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。","download-as-file": "{{file}} 形式でダウンロード",- "download-encryption-failed": "ダウンロードの暗号化に失敗しました。",- "download-failed": "ダウンロードに失敗しました。",- "download-too-large": "ダウンロードするには結果が大きすぎます。行数を減らすか、エクスポートを使用してください。",- "download-too-large-bytes": "{{statements}} 件のステートメントで合計約 {{megabytes}} MB のダウンロードです。上限は {{capMb}} MB です。結果サイズを減らすか、エクスポートを使用してください。",- "download-too-large-cells": "{{statements}} 件のステートメントで合計 {{cells}} セルのダウンロードです。上限は {{limit}} セルです。行数を減らすか、エクスポートを使用してください。",- "download-too-large-xlsx-columns": "XLSX の列数は {{limit}} を超えられません(取得: {{count}})。エクスポートまたは別の形式を使用してください。",- "download-too-large-xlsx-rows": "XLSX のデータ行数は {{limit}} を超えられません(取得: {{count}})。エクスポートまたは別の形式を使用してください。","duration-day": "{{days}} 日","duration-days": "{{days}} 日","duration-hour": "{{hours}} 時間",@@ -2584,10 +2595,12 @@"expire-at": "{{time}} に期限切れ","expire-in": "{{time}} 後に期限切れ","expired": "期限切れ",+ "export-enabled-by-grant": "アクセス権限により有効になっています","format": "フォーマット","format-default": "デフォルト","format-sql": "SQL を整形","generate-sql": "SQLの生成",+ "grant-type-export": "エクスポート","grant-type-unmask": "マスク解除","hex-format": "16進形式","hint-tips": {@@ -2640,6 +2653,7 @@"request-aborted": "ユーザーがリクエストを中止しました","request-access": "アクセスをリクエスト","request-data-access": "データアクセスをリクエスト",+ "request-export": "エクスポートをリクエスト","request-jit": "ジャストインタイムアクセスをリクエスト","request-query": "リクエストクエリ","result-limit": {@@ -2666,8 +2680,6 @@"self": "SQLエディタ","show-databases-without-query-permission": "クエリ権限のないデータベースを表示します","show-in-editor": "エディタに表示",- "sql-download-engine-unsupported": "エンジン {{engine}} では SQL ダウンロードがサポートされていません。",- "sql-download-unavailable": "この接続では SQL ダウンロードを利用できません。","sync-in-progress": "同期中","tab": {"context-menu": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex e06a2e7f92..0cc91e1d00 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -345,6 +345,7 @@"n-selected": "Đã chọn {{n}}","name": "Tên","next": "Tiếp theo",+ "no": "Không","no-data": "Không có dữ liệu","not-started": "Chưa bắt đầu","ok": "OK",@@ -465,6 +466,7 @@"warning": "Cảnh báo","webhooks": "Webhook","write-only": "chỉ ghi",+ "yes": "Có","you": "bạn"},"create-db": {@@ -819,11 +821,17 @@"not-found": "Không tìm thấy"},"export-center": {- "data-export": "Xuất dữ liệu"+ "data-export": "Xuất dữ liệu",+ "deprecated": {+ "description": "Trung tâm Xuất dữ liệu sẽ bị ngừng hỗ trợ trong bản phát hành tương lai. Đối với các yêu cầu xuất dữ liệu mới, vui lòng sử dụng chức năng xuất của SQL Editor.",+ "open-sql-editor": "Đi tới SQL Editor",+ "title": "Trung tâm Xuất dữ liệu sẽ bị ngừng hỗ trợ"+ }},"export-data": {"export-format": "Định dạng xuất","export-rows": "Xuất số dòng",+ "generate-password": "Tạo mật khẩu","password-info": "Cung cấp mật khẩu để mã hóa tệp xuất.","password-optional": "Mã hóa bằng mật khẩu (Tùy chọn)"},@@ -1140,8 +1148,14 @@"access-grant": {"advanced-search": {"scope": {+ "export": {+ "description": "Lọc theo việc cấp phép có cho phép xuất kết quả truy vấn hay không"+ },"status": {"description": "Lọc theo trạng thái cấp quyền truy cập"+ },+ "unmask": {+ "description": "Lọc theo việc cấp phép có cho phép xem dữ liệu nhạy cảm chưa che hay không"}}},@@ -2515,11 +2529,18 @@"database": {"description": "Lọc theo cơ sở dữ liệu"},+ "export": {+ "description": "Lọc theo việc cấp phép có cho phép xuất kết quả truy vấn hay không"+ },"status": {"description": "Tìm kiếm theo trạng thái cấp quyền truy cập"+ },+ "unmask": {+ "description": "Lọc theo việc cấp phép có cho phép xem dữ liệu nhạy cảm chưa che hay không"}}},+ "access-type-export": "Xuất kết quả truy vấn","access-type-unmask": "Xem dữ liệu nhạy cảm chưa che","activate-access": "Kích hoạt","activate-confirm": "Bạn có chắc chắn muốn kích hoạt cấp quyền truy cập này không?",@@ -2531,10 +2552,7 @@"allow-admin-mode-only": "Phiên bản <instance></instance> chỉ có thể truy cập ở chế độ quản trị.","and-n-more-databases": "và {{n}} cơ sở dữ liệu khác","batch-export": {- "database-no-longer-available": "Cơ sở dữ liệu không còn khả dụng trong tab hiện tại.",- "export-limit-exceeds-executed": "Giới hạn xuất {{exportLimit}} vượt quá giới hạn số dòng của truy vấn đã thực thi ({{executedLimit}}); chỉ xuất các dòng đã được lưu trong bộ nhớ đệm.","failed-for-db": "Không xuất được dữ liệu cho {{db}}",- "no-results": "Không có kết quả để tải xuống.","self": "Xuất hàng loạt","tooltip": "Chọn tối đa {{max}} cơ sở dữ liệu để xuất hàng loạt kết quả truy vấn mới nhất"},@@ -2568,13 +2586,6 @@"copy-url": "Sao chép URL","ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.","download-as-file": "Tải xuống dưới dạng {{file}}",- "download-encryption-failed": "Không thể mã hóa bản tải xuống.",- "download-failed": "Tải xuống thất bại.",- "download-too-large": "Kết quả quá lớn để tải xuống. Hãy giảm số dòng hoặc sử dụng Xuất.",- "download-too-large-bytes": "Tải xuống ~{{megabytes}} MB qua {{statements}} câu lệnh; giới hạn là {{capMb}} MB. Hãy giảm kích thước kết quả hoặc sử dụng Xuất.",- "download-too-large-cells": "Tải xuống có {{cells}} ô qua {{statements}} câu lệnh; giới hạn là {{limit}}. Hãy giảm số dòng hoặc sử dụng Xuất.",- "download-too-large-xlsx-columns": "XLSX không thể vượt quá {{limit}} cột; nhận được {{count}}. Hãy sử dụng Xuất hoặc định dạng khác.",- "download-too-large-xlsx-rows": "XLSX không thể vượt quá {{limit}} dòng dữ liệu; nhận được {{count}}. Hãy sử dụng Xuất hoặc định dạng khác.","duration-day": "{{days}} ngày","duration-days": "{{days}} ngày","duration-hour": "{{hours}} giờ",@@ -2584,10 +2595,12 @@"expire-at": "Hết hạn lúc {{time}}","expire-in": "Hết hạn sau {{time}}","expired": "Đã hết hạn",+ "export-enabled-by-grant": "Xuất được kích hoạt bởi cấp quyền truy cập","format": "Định dạng","format-default": "Mặc định","format-sql": "Định dạng SQL","generate-sql": "Tạo SQL",+ "grant-type-export": "Xuất","grant-type-unmask": "Bỏ che","hex-format": "Định dạng thập lục phân","hint-tips": {@@ -2640,6 +2653,7 @@"request-aborted": "Người dùng đã hủy yêu cầu","request-access": "Yêu cầu truy cập","request-data-access": "Yêu cầu truy cập dữ liệu",+ "request-export": "Yêu cầu xuất dữ liệu","request-jit": "Yêu cầu truy cập just-in-time","request-query": "Yêu cầu truy vấn","result-limit": {@@ -2666,8 +2680,6 @@"self": "Trình soạn thảo SQL","show-databases-without-query-permission": "Hiển thị cơ sở dữ liệu không có quyền truy vấn","show-in-editor": "Hiển thị trong editor",- "sql-download-engine-unsupported": "Tải xuống SQL không được hỗ trợ cho engine {{engine}}.",- "sql-download-unavailable": "Tải xuống SQL không khả dụng cho kết nối này.","sync-in-progress": "Đang đồng bộ","tab": {"context-menu": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 7e09e0e52e..c1857d13d6 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -345,6 +345,7 @@"n-selected": "已选择 {{n}} 项","name": "名称","next": "下一步",+ "no": "否","no-data": "无数据","not-started": "未开始","ok": "确定",@@ -465,6 +466,7 @@"warning": "警告","webhooks": "Webhook","write-only": "仅写入",+ "yes": "是","you": "您"},"create-db": {@@ -819,11 +821,17 @@"not-found": "页面未找到"},"export-center": {- "data-export": "数据导出"+ "data-export": "数据导出",+ "deprecated": {+ "description": "导出中心将在未来版本中弃用。对于新的数据导出,建议使用 SQL 编辑器的导出功能。",+ "open-sql-editor": "前往 SQL 编辑器",+ "title": "导出中心即将弃用"+ }},"export-data": {"export-format": "导出格式","export-rows": "导出行数",+ "generate-password": "生成密码","password-info": "提供密码来对导出的文件进行加密","password-optional": "设置密码加密(可选)"},@@ -1140,8 +1148,14 @@"access-grant": {"advanced-search": {"scope": {+ "export": {+ "description": "按授权是否允许导出查询结果筛选"+ },"status": {"description": "按访问授权状态筛选"+ },+ "unmask": {+ "description": "按授权是否允许查看脱敏数据筛选"}}},@@ -2515,11 +2529,18 @@"database": {"description": "按数据库筛选"},+ "export": {+ "description": "按授权是否允许导出查询结果筛选"+ },"status": {"description": "按访问授权状态搜索"+ },+ "unmask": {+ "description": "按授权是否允许查看脱敏数据筛选"}}},+ "access-type-export": "导出查询结果","access-type-unmask": "查看未脱敏的敏感数据","activate-access": "激活","activate-confirm": "确定要激活此访问授权吗?",@@ -2531,10 +2552,7 @@"allow-admin-mode-only": "实例<instance></instance>只能通过管理员模式访问。","and-n-more-databases": "及其他 {{n}} 个数据库","batch-export": {- "database-no-longer-available": "该数据库在当前标签页中已不可用。",- "export-limit-exceeds-executed": "导出上限 {{exportLimit}} 超过了已执行查询的行数上限 ({{executedLimit}});仅导出已缓存的行。","failed-for-db": "无法导出 {{db}} 的数据",- "no-results": "没有可下载的结果。","self": "批量导出","tooltip": "最多选择 {{max}} 个数据库,批量导出最后一次执行的查询结果"},@@ -2568,13 +2586,6 @@"copy-url": "复制 URL","ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。","download-as-file": "下载为 {{file}} 格式",- "download-encryption-failed": "加密下载失败。",- "download-failed": "下载失败。",- "download-too-large": "结果过大,无法下载。请减少行数或使用导出。",- "download-too-large-bytes": "下载在 {{statements}} 条语句中约 {{megabytes}} MB;上限为 {{capMb}} MB。请减小结果体积或使用导出。",- "download-too-large-cells": "下载在 {{statements}} 条语句中包含 {{cells}} 个单元格;上限为 {{limit}}。请减少行数或使用导出。",- "download-too-large-xlsx-columns": "XLSX 列数不能超过 {{limit}};当前为 {{count}}。请使用导出或其他格式。",- "download-too-large-xlsx-rows": "XLSX 数据行数不能超过 {{limit}};当前为 {{count}}。请使用导出或其他格式。","duration-day": "{{days}} 天","duration-days": "{{days}} 天","duration-hour": "{{hours}} 小时",@@ -2584,10 +2595,12 @@"expire-at": "{{time}} 过期","expire-in": "{{time}} 后过期","expired": "已过期",+ "export-enabled-by-grant": "由访问授权启用导出","format": "格式化","format-default": "默认","format-sql": "格式化 SQL","generate-sql": "生成 SQL",+ "grant-type-export": "导出","grant-type-unmask": "脱敏豁免","hex-format": "十六进制格式","hint-tips": {@@ -2640,6 +2653,7 @@"request-aborted": "用户中止了请求","request-access": "申请访问","request-data-access": "申请数据访问",+ "request-export": "申请导出","request-jit": "申请即时访问","request-query": "请求查询","result-limit": {@@ -2666,8 +2680,6 @@"self": "SQL 编辑器","show-databases-without-query-permission": "显示没有查询权限的数据库","show-in-editor": "在编辑器中显示",- "sql-download-engine-unsupported": "数据库引擎 {{engine}} 不支持 SQL 下载。",- "sql-download-unavailable": "当前连接不支持 SQL 下载。","sync-in-progress": "正在同步","tab": {"context-menu": {diff --git a/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx b/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsxindex fcd5cf7576..8fc6e9c798 100644--- a/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx+++ b/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx@@ -275,6 +275,44 @@ export function ProjectAccessGrantsPage({ projectId }: { projectId: string }) {description: t("issue.advanced-search.scope.creator.description"),onSearch: searchUsers,},+ {+ id: "unmask",+ title: t("sql-editor.grant-type-unmask"),+ description: t(+ "issue.access-grant.advanced-search.scope.unmask.description"+ ),+ options: [+ {+ value: "true",+ keywords: ["yes", "true"],+ render: () => <span>{t("common.yes")}</span>,+ },+ {+ value: "false",+ keywords: ["no", "false"],+ render: () => <span>{t("common.no")}</span>,+ },+ ],+ },+ {+ id: "export",+ title: t("sql-editor.grant-type-export"),+ description: t(+ "issue.access-grant.advanced-search.scope.export.description"+ ),+ options: [+ {+ value: "true",+ keywords: ["yes", "true"],+ render: () => <span>{t("common.yes")}</span>,+ },+ {+ value: "false",+ keywords: ["no", "false"],+ render: () => <span>{t("common.no")}</span>,+ },+ ],+ },],[t, searchDatabases, searchUsers]);@@ -319,6 +357,14 @@ export function ProjectAccessGrantsPage({ projectId }: { projectId: string }) {if (database) {filter.target = database;}+ const unmask = getValueFromScopes(searchParams, "unmask");+ if (unmask === "true" || unmask === "false") {+ filter.unmask = unmask === "true";+ }+ const exportScope = getValueFromScopes(searchParams, "export");+ if (exportScope === "true" || exportScope === "false") {+ filter.export = exportScope === "true";+ }const query = searchParams.query.trim();if (query) {filter.statement = query;@@ -579,6 +625,11 @@ function AccessGrantRow({{t("sql-editor.grant-type-unmask")}</Badge>)}+ {grant.export && (+ <Badge variant="default" className="shrink-0">+ {t("sql-editor.grant-type-export")}+ </Badge>+ )}</div></TableCell><TableCell>diff --git a/frontend/src/react/pages/project/ProjectDataExportPage.tsx b/frontend/src/react/pages/project/ProjectDataExportPage.tsxindex b319cb762c..7bf414f1ee 100644--- a/frontend/src/react/pages/project/ProjectDataExportPage.tsx+++ b/frontend/src/react/pages/project/ProjectDataExportPage.tsx@@ -1,4 +1,4 @@-import { Download, Loader2 } from "lucide-react";+import { Download, Loader2, SquareTerminal } from "lucide-react";import { useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import {@@ -9,6 +9,7 @@ import {type ValueOption,} from "@/react/components/AdvancedSearch";import { HighlightLabelText } from "@/react/components/HighlightLabelText";+import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";@@ -17,6 +18,7 @@ import { displayRoleTitleFromList } from "@/react/lib/role";import { useAppStore } from "@/react/stores/app";import { router } from "@/router";import { WORKSPACE_ROUTE_USER_PROFILE } from "@/router/dashboard/workspaceRoutes";+import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";import { projectNamePrefix } from "@/store/modules/v1/common";import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";import { ApprovalStatus, RiskLevel } from "@/types/proto-es/v1/common_pb";@@ -214,32 +216,45 @@ export function ProjectDataExportPage({ projectId }: { projectId: string }) {return (<div className="py-4 w-full flex flex-col">- <div className="px-4">- <div className="w-full flex flex-col lg:flex-row items-start lg:items-center justify-between gap-2">- <div className="flex flex-1 max-w-full items-center gap-x-2">- <AdvancedSearch- params={searchParams}- onParamsChange={setSearchParams}- scopeOptions={scopeOptions}- placeholder={t("issue.advanced-search.filter")}- />- <Tooltip- content={- !canCreate- ? t("common.missing-required-permission", {- permissions:- PERMISSIONS_FOR_DATABASE_EXPORT_ISSUE.join(", "),- })- : undefined- }+ <div className="px-4 mb-3">+ <Alert+ variant="warning"+ title={t("export-center.deprecated.title")}+ description={t("export-center.deprecated.description")}+ >+ <div className="mt-3 flex justify-end">+ <Button+ size="sm"+ className="shrink-0 whitespace-nowrap"+ onClick={() => router.push({ name: SQL_EDITOR_HOME_MODULE })}>- <Button disabled={!canCreate} onClick={() => setShowDrawer(true)}>- <Download className="size-4 mr-1" />- {t("quick-action.request-export-data")}- </Button>- </Tooltip>+ <SquareTerminal className="size-4 mr-1" />+ {t("export-center.deprecated.open-sql-editor")}+ </Button></div>- </div>+ </Alert>+ </div>+ <div className="px-4 flex flex-col sm:flex-row items-start sm:items-center gap-2">+ <AdvancedSearch+ params={searchParams}+ onParamsChange={setSearchParams}+ scopeOptions={scopeOptions}+ placeholder={t("issue.advanced-search.filter")}+ />+ <Tooltip+ content={+ !canCreate+ ? t("common.missing-required-permission", {+ permissions: PERMISSIONS_FOR_DATABASE_EXPORT_ISSUE.join(", "),+ })+ : undefined+ }+ >+ <Button disabled={!canCreate} onClick={() => setShowDrawer(true)}>+ <Download className="size-4 mr-1" />+ {t("quick-action.request-export-data")}+ </Button>+ </Tooltip></div>{/* Issue list */}diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsxindex a41f7c990c..4e0cec09fa 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx@@ -3,7 +3,7 @@ import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";import { Alert } from "@/react/components/ui/alert";-import { Checkbox } from "@/react/components/ui/checkbox";+import { Badge } from "@/react/components/ui/badge";import { useVueState } from "@/react/hooks/useVueState";import { useAppStore } from "@/react/stores/app";import { projectNamePrefix } from "@/store/modules/v1/common";@@ -128,12 +128,26 @@ export function IssueDetailAccessGrantDetails() {{accessGrant.query}</pre></div>- <label className="flex items-center gap-2">- <Checkbox checked={accessGrant.unmask} disabled />- <span className="text-base">- {t("sql-editor.access-type-unmask")}- </span>- </label>+ </div>+ )}++ {(accessGrant.unmask || accessGrant.export) && (+ <div className="flex flex-col gap-y-2">+ <span className="text-sm text-control-light">+ {t("common.permissions")}+ </span>+ <div className="flex flex-wrap gap-2">+ {accessGrant.unmask && (+ <Badge variant="secondary">+ {t("sql-editor.access-type-unmask")}+ </Badge>+ )}+ {accessGrant.export && (+ <Badge variant="secondary">+ {t("sql-editor.access-type-export")}+ </Badge>+ )}+ </div></div>)}diff --git a/frontend/src/react/stores/app/accessGrant.test.ts b/frontend/src/react/stores/app/accessGrant.test.tsnew file mode 100644index 0000000000..b39f6dea9b--- /dev/null+++ b/frontend/src/react/stores/app/accessGrant.test.ts@@ -0,0 +1,107 @@+import { describe, expect, test } from "vitest";+import { buildAccessGrantFilter } from "./accessGrant";++const FIXED_NOW = new Date("2026-06-01T00:00:00Z");++describe("buildAccessGrantFilter", () => {+ test("empty filter returns empty string", () => {+ expect(buildAccessGrantFilter(undefined)).toBe("");+ expect(buildAccessGrantFilter({})).toBe("");+ });++ test("unmask=true emits literal CEL boolean", () => {+ expect(buildAccessGrantFilter({ unmask: true })).toBe("unmask == true");+ });++ test("unmask=false emits literal CEL boolean", () => {+ expect(buildAccessGrantFilter({ unmask: false })).toBe("unmask == false");+ });++ test("export=true emits literal CEL boolean", () => {+ expect(buildAccessGrantFilter({ export: true })).toBe("export == true");+ });++ test("export=false emits literal CEL boolean", () => {+ expect(buildAccessGrantFilter({ export: false })).toBe("export == false");+ });++ test("unmask and export combine with &&", () => {+ expect(buildAccessGrantFilter({ unmask: true, export: true })).toBe(+ "unmask == true && export == true"+ );+ });++ test("unmask combines with other filters in order", () => {+ expect(+ buildAccessGrantFilter({+ creator: "users/[email protected]",+ unmask: true,+ export: false,+ })+ ).toBe(+ 'creator == "users/[email protected]" && unmask == true && export == false'+ );+ });++ // Sanity check: filter values use the literal token `true`/`false` so the+ // server-side filter parser treats them as CEL booleans, not strings. This+ // matches the backend's `store.GetListAccessGrantFilter` switch which+ // expects `value.(bool)` for these two fields. Quoting them would silently+ // change the SQL emitted (or trigger a "must be a boolean" error).+ test("never quotes the boolean literal", () => {+ expect(buildAccessGrantFilter({ unmask: true })).not.toContain('"true"');+ expect(buildAccessGrantFilter({ export: false })).not.toContain('"false"');+ });++ test("absent unmask/export fields produce no emission", () => {+ // Only target, no unmask/export.+ expect(+ buildAccessGrantFilter({ target: "instances/i/databases/d" }, FIXED_NOW)+ ).toBe('target == "instances/i/databases/d"');+ });++ // statementExact pins the distinction from `statement` (substring search)+ // and mirrors the backend JIT authorization predicate `query == "..."`.+ // PR #20491 bot review #3349385091: a substring match like running+ // `SELECT * FROM t` against a grant for `SELECT * FROM t WHERE id = 1`+ // must NOT enable the Export button because the backend exact-match+ // would still deny.+ test("statementExact emits exact CEL equality", () => {+ expect(buildAccessGrantFilter({ statementExact: "SELECT * FROM t" })).toBe(+ `query == "SELECT * FROM t"`+ );+ });++ test("statementExact trims boundary whitespace", () => {+ expect(buildAccessGrantFilter({ statementExact: "\n SELECT 1\n" })).toBe(+ `query == "SELECT 1"`+ );+ });++ test("statementExact escapes embedded quotes and newlines safely", () => {+ expect(+ buildAccessGrantFilter({+ statementExact: `SELECT 'foo "bar"' FROM t\nWHERE x = 1`,+ })+ ).toBe(`query == "SELECT 'foo \\"bar\\"' FROM t\\nWHERE x = 1"`);+ });++ test("statement and statementExact emit different predicates", () => {+ // Same input: `statement` → substring; `statementExact` → exact.+ // Both must coexist for different UX cases (search box vs.+ // authorization-eligibility check).+ expect(buildAccessGrantFilter({ statement: "SELECT 1" })).toBe(+ `query.contains("SELECT 1")`+ );+ expect(buildAccessGrantFilter({ statementExact: "SELECT 1" })).toBe(+ `query == "SELECT 1"`+ );+ });++ test("empty-string statementExact still emits exact predicate", () => {+ // `statementExact === ""` is a meaningful filter (match grants whose+ // stored query is empty), distinct from `statementExact === undefined`+ // which means "no constraint". Don't conflate them.+ expect(buildAccessGrantFilter({ statementExact: "" })).toBe(`query == ""`);+ });+});diff --git a/frontend/src/react/stores/app/accessGrant.ts b/frontend/src/react/stores/app/accessGrant.tsindex dce287f01a..ba57a4bfae 100644--- a/frontend/src/react/stores/app/accessGrant.ts+++ b/frontend/src/react/stores/app/accessGrant.ts@@ -49,6 +49,11 @@ export const buildAccessGrantFilter = (if (filter.statement) {parts.push(`query.contains("${filter.statement.trim()}")`);}+ if (filter.statementExact !== undefined) {+ // Use JSON.stringify so internal quotes / backslashes / newlines in+ // the SQL are escaped safely into the CEL string literal.+ parts.push(`query == ${JSON.stringify(filter.statementExact.trim())}`);+ }if (filter.creator) {parts.push(`creator == "${filter.creator}"`);}@@ -68,6 +73,12 @@ export const buildAccessGrantFilter = (`create_time <= "${new Date(filter.createdTsBefore).toISOString()}"`);}+ if (filter.unmask !== undefined) {+ parts.push(`unmask == ${filter.unmask}`);+ }+ if (filter.export !== undefined) {+ parts.push(`export == ${filter.export}`);+ }return parts.join(" && ");};diff --git a/frontend/src/react/stores/app/sql.ts b/frontend/src/react/stores/app/sql.tsindex 049bd4c5a2..3451ac2897 100644--- a/frontend/src/react/stores/app/sql.ts+++ b/frontend/src/react/stores/app/sql.ts@@ -26,6 +26,7 @@ export const createSQLSlice: AppSliceCreator<SQLSlice> = () => ({return {error: "",results: response.results,+ appliedAccessGrant: response.appliedAccessGrant,};} catch (err) {return {diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.tsindex c4421cf008..ce251fdcc9 100644--- a/frontend/src/react/stores/app/types.ts+++ b/frontend/src/react/stores/app/types.ts@@ -143,13 +143,24 @@ export type ListWorkloadIdentitiesParams = {export type AccessGrantFilter = {name?: string;+ // Substring search via `query.contains(...)`. Use for free-text search+ // UIs. Backend ILIKE-matches the stored grant query (whitespace+ // normalized), so callers can pass any substring.statement?: string;+ // Exact-match via `query == ...`. Use for authorization-eligibility+ // checks where the frontend needs to mirror the backend JIT match+ // (e.g. "can the user export this exact statement?"). Backend trims+ // boundary whitespace on both sides — internal whitespace preserved+ // byte-for-byte. PR #20491 bot review #3349385091.+ statementExact?: string;creator?: string;status?: AccessGrantFilterStatus[];issue?: string;target?: string;createdTsAfter?: number;createdTsBefore?: number;+ unmask?: boolean;+ export?: boolean;};export type ListAccessGrantsParams = {diff --git a/frontend/src/utils/cel-attributes.ts b/frontend/src/utils/cel-attributes.tsindex ee008cd040..53a9595389 100644--- a/frontend/src/utils/cel-attributes.ts+++ b/frontend/src/utils/cel-attributes.ts@@ -23,6 +23,7 @@ export const CEL_ATTRIBUTE_STATEMENT_TEXT = "statement.text";export const CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS = "request.expiration_days";export const CEL_ATTRIBUTE_REQUEST_ROLE = "request.role";export const CEL_ATTRIBUTE_REQUEST_UNMASK = "request.unmask";+export const CEL_ATTRIBUTE_REQUEST_EXPORT = "request.data_export";export const CEL_ATTRIBUTE_REQUEST_TIME = "request.time";// CEL attribute names for risk scope.diff --git a/frontend/src/utils/sql-download/__tests__/csv.test.ts b/frontend/src/utils/sql-download/__tests__/csv.test.tsdeleted file mode 100644index 507f9cbd5b..0000000000--- a/frontend/src/utils/sql-download/__tests__/csv.test.ts+++ /dev/null@@ -1,102 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";-import { describe, expect, it } from "vitest";-import {- type QueryResult,- QueryResultSchema,- QueryRowSchema,- type RowValue,- RowValueSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import { serializeCSV } from "../formats/csv";--const TEXT_DECODER = new TextDecoder("utf-8");--const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });-const intRow = (n: bigint): RowValue =>- create(RowValueSchema, { kind: { case: "int64Value", value: n } });-const strRow = (s: string): RowValue =>- create(RowValueSchema, { kind: { case: "stringValue", value: s } });-const f32Row = (n: number): RowValue =>- create(RowValueSchema, { kind: { case: "floatValue", value: n } });-const f64Row = (n: number): RowValue =>- create(RowValueSchema, { kind: { case: "doubleValue", value: n } });-const valueRow = (v: Value): RowValue =>- create(RowValueSchema, { kind: { case: "valueValue", value: v } });--const csv = (result: QueryResult): string =>- TEXT_DECODER.decode(serializeCSV(result));--describe("serializeCSV", () => {- it("emits header-only output for an empty result", () => {- const r = create(QueryResultSchema, { columnNames: ["id", "name"] });- expect(csv(r)).toBe("id,name\n");- });-- it("emits basic ASCII rows (every string cell unconditionally CSV-quoted)", () => {- const r = create(QueryResultSchema, {- columnNames: ["id", "name"],- rows: [- rowOf(intRow(1n), strRow("Alice")),- rowOf(intRow(2n), strRow("Bob")),- ],- });- expect(csv(r)).toBe('id,name\n1,"Alice"\n2,"Bob"');- });-- it('doubles embedded `"` inside CSV-quoted strings and preserves newline/comma literals', () => {- const r = create(QueryResultSchema, {- columnNames: ["s"],- rows: [rowOf(strRow(`a"b`)), rowOf(strRow("a,b")), rowOf(strRow("a\nb"))],- });- expect(csv(r)).toBe('s\n"a""b"\n"a,b"\n"a\nb"');- });-- it("emits float32 via formatFloat32 (never exponential) and float64 native", () => {- const r = create(QueryResultSchema, {- columnNames: ["f32", "f64"],- rows: [rowOf(f32Row(1.5), f64Row(1e21))],- });- // f32: shortest-roundtrip 'f' verb; f64: JS native exponential at >= 1e21.- expect(csv(r)).toBe("f32,f64\n1.5,1e+21");- });-- it("emits NaN / +Inf / -Inf as textual float tokens, not empty cells", () => {- // Regression: prior to this guard, non-finite float64 became "", which- // is indistinguishable from a NULL cell and silently loses data. Now- // matches the backend's strconv.FormatFloat tokens.- const r = create(QueryResultSchema, {- columnNames: ["nan", "posinf", "neginf"],- rows: [- rowOf(- f64Row(Number.NaN),- f64Row(Number.POSITIVE_INFINITY),- f64Row(Number.NEGATIVE_INFINITY)- ),- ],- });- expect(csv(r)).toBe("nan,posinf,neginf\nNaN,+Inf,-Inf");- });-- it("emits structpb cells as CSV-quoted JSON (Tier 2)", () => {- const struct = create(ValueSchema, {- kind: {- case: "structValue",- value: create(StructSchema, {- fields: {- a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),- b: create(ValueSchema, {- kind: { case: "stringValue", value: "x" },- }),- },- }),- },- });- const r = create(QueryResultSchema, {- columnNames: ["v"],- rows: [rowOf(valueRow(struct))],- });- // JSON.stringify preserves insertion order; CSV escapes embedded `"` to `""`.- expect(csv(r)).toBe(`v\n"{""a"":1,""b"":""x""}"`);- });-});diff --git a/frontend/src/utils/sql-download/__tests__/engines.test.ts b/frontend/src/utils/sql-download/__tests__/engines.test.tsdeleted file mode 100644index e6ed369097..0000000000--- a/frontend/src/utils/sql-download/__tests__/engines.test.ts+++ /dev/null@@ -1,59 +0,0 @@-import { describe, expect, it } from "vitest";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { SQL_ENGINE_QUOTES } from "../engines";--describe("SQL_ENGINE_QUOTES engine coverage", () => {- // Mirrors backend SQLStatementPrefix in backend/component/export/sql.go:55-64.- // serializeSQL throws UnsupportedFormat for any engine not in the map; this- // truth table catches accidental engine removals.- it.each([- Engine.MYSQL,- Engine.MARIADB,- Engine.TIDB,- Engine.OCEANBASE,- Engine.SPANNER,- Engine.CLICKHOUSE,- Engine.MSSQL,- Engine.ORACLE,- Engine.POSTGRES,- Engine.REDSHIFT,- Engine.SQLITE,- Engine.SNOWFLAKE,- ])("supports engine %d", (engine) => {- expect(SQL_ENGINE_QUOTES.has(engine)).toBe(true);- });-- it.each([- Engine.ENGINE_UNSPECIFIED,- Engine.MONGODB,- Engine.REDIS,- Engine.ELASTICSEARCH,- Engine.DYNAMODB,- Engine.COSMOSDB,- Engine.CASSANDRA,- Engine.STARROCKS,- Engine.DORIS,- Engine.HIVE,- Engine.BIGQUERY,- Engine.COCKROACHDB,- Engine.DATABRICKS,- Engine.TRINO,- ])("does not support engine %d", (engine) => {- expect(SQL_ENGINE_QUOTES.has(engine)).toBe(false);- });-});--describe("SQL_ENGINE_QUOTES", () => {- it("uses backtick for MySQL family", () => {- expect(SQL_ENGINE_QUOTES.get(Engine.MYSQL)).toBe("`");- expect(SQL_ENGINE_QUOTES.get(Engine.MARIADB)).toBe("`");- expect(SQL_ENGINE_QUOTES.get(Engine.TIDB)).toBe("`");- });- it("uses double-quote for Postgres family", () => {- expect(SQL_ENGINE_QUOTES.get(Engine.POSTGRES)).toBe(`"`);- expect(SQL_ENGINE_QUOTES.get(Engine.REDSHIFT)).toBe(`"`);- });- it("returns undefined for unsupported engine", () => {- expect(SQL_ENGINE_QUOTES.get(Engine.MONGODB)).toBeUndefined();- });-});diff --git a/frontend/src/utils/sql-download/__tests__/error-messages.test.ts b/frontend/src/utils/sql-download/__tests__/error-messages.test.tsdeleted file mode 100644index 122d4924fb..0000000000--- a/frontend/src/utils/sql-download/__tests__/error-messages.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { describe, expect, it } from "vitest";-import { downloadErrorMessage } from "../error-messages";--const t = (key: string) => key;--// Helper: realistic DownloadError shape — an Error instance with a .code-// field. Matches what `downloadError()` from types.ts produces. Plain-// objects without `instanceof Error` fall through to the generic path-// because `isDownloadError` requires both.-const makeDownloadError = (- code: string,- message = ""-): Error & { code: string } => Object.assign(new Error(message), { code });--describe("downloadErrorMessage", () => {- it("maps ResultTooLarge (no message → locale fallback)", () => {- expect(downloadErrorMessage(makeDownloadError("ResultTooLarge"), t)).toBe(- "sql-editor.download-too-large"- );- });- it("maps UnsupportedFormat (no message → locale fallback)", () => {- expect(- downloadErrorMessage(makeDownloadError("UnsupportedFormat"), t)- ).toBe("sql-editor.sql-download-unavailable");- });- it("falls back to error message", () => {- expect(downloadErrorMessage(new Error("oops"), t)).toBe("oops");- });- it("truncates multi-line errors to the first line", () => {- expect(- downloadErrorMessage(new Error("oops\ncause: something\n more"), t)- ).toBe("oops");- });- it("truncates excessively long messages", () => {- const long = "x".repeat(500);- const out = downloadErrorMessage(new Error(long), t);- expect(out.length).toBeLessThanOrEqual(240);- expect(out.endsWith("…")).toBe(true);- });- it("ResultTooLarge surfaces the bytes/cells message from the error", () => {- const e = makeDownloadError(- "ResultTooLarge",- "Result is ~520 MB; client-side limit is 200 MB."- );- expect(downloadErrorMessage(e, t)).toContain("520 MB");- });- it("UnsupportedFormat surfaces the concrete message (e.g. unsupported SQL engine)", () => {- // serializeSQL throws UnsupportedFormat with the engine name when the- // engine isn't in SQL_ENGINE_QUOTES; falling back to the generic- // "sql-download-unavailable" locale would lose that detail.- const e = makeDownloadError(- "UnsupportedFormat",- "SQL download is not supported for engine MONGODB"- );- expect(downloadErrorMessage(e, t)).toContain("MONGODB");- });- it("UnsupportedFormat falls back to locale string when no message", () => {- expect(- downloadErrorMessage(makeDownloadError("UnsupportedFormat"), t)- ).toBe("sql-editor.sql-download-unavailable");- });- it("falls back to a localized generic when no message", () => {- // Plain object (not an Error instance) — exercises the non-DownloadError- // branch.- expect(downloadErrorMessage({}, t)).toBe("sql-editor.download-failed");- });- it("falls back to message extraction for non-DownloadError Error instances", () => {- // A vanilla Error (no .code field) — isDownloadError returns false,- // so the generic message branch handles it.- expect(downloadErrorMessage(new Error("plain"), t)).toBe("plain");- });-});diff --git a/frontend/src/utils/sql-download/__tests__/filename.test.ts b/frontend/src/utils/sql-download/__tests__/filename.test.tsdeleted file mode 100644index 55c59ca542..0000000000--- a/frontend/src/utils/sql-download/__tests__/filename.test.ts+++ /dev/null@@ -1,144 +0,0 @@-// @vitest-environment node--import { describe, expect, it } from "vitest";-import {- FALLBACK_BASENAME,- MAX_BASENAME_LENGTH,- sanitizeBasename,- uniqueFilename,-} from "../filename";--describe("sanitizeBasename (B5 — ZIP filename path traversal)", () => {- it("returns plain ASCII names unchanged", () => {- expect(sanitizeBasename("prod-db-2026-05-09")).toBe("prod-db-2026-05-09");- });-- it("replaces forward slashes with underscores", () => {- expect(sanitizeBasename("a/b")).toBe("a_b");- });-- it("replaces backslashes with underscores", () => {- expect(sanitizeBasename("a\\b")).toBe("a_b");- });-- it("strips NUL bytes", () => {- expect(sanitizeBasename("a\x00b")).toBe("ab");- });-- it("collapses parent-directory hints embedded in the name", () => {- // `..` and `.` segments inside a basename can still be re-interpreted- // by some ZIP readers after we strip the slashes.- expect(sanitizeBasename("..")).toBe(FALLBACK_BASENAME);- // `../foo` -> slash becomes `_` -> `.._foo` -> dot-run collapses to `._foo`- // -> leading dots/whitespace trimmed -> `_foo`. Underscore is safe.- expect(sanitizeBasename("../foo")).toBe("_foo");- // `foo/..` -> `foo_..` -> `foo_.` -> trimmed trailing dot -> `foo_`.- expect(sanitizeBasename("foo/..")).toBe("foo_");- });-- it("trims leading and trailing dots and whitespace", () => {- expect(sanitizeBasename(" prod ")).toBe("prod");- expect(sanitizeBasename("...prod")).toBe("prod");- expect(sanitizeBasename("prod...")).toBe("prod");- });-- it("truncates names longer than the cap", () => {- const long = "a".repeat(MAX_BASENAME_LENGTH + 50);- const out = sanitizeBasename(long);- expect(out.length).toBe(MAX_BASENAME_LENGTH);- });-- it("falls back to 'download' when input is empty or only stripped chars", () => {- expect(sanitizeBasename("")).toBe(FALLBACK_BASENAME);- expect(sanitizeBasename("\x00\x00")).toBe(FALLBACK_BASENAME);- expect(sanitizeBasename("///")).toBe("___"); // slashes become underscores, not empty- expect(sanitizeBasename("....")).toBe(FALLBACK_BASENAME);- expect(sanitizeBasename(" ")).toBe(FALLBACK_BASENAME);- });-- it("preserves non-ASCII printable Unicode (databases may carry it)", () => {- expect(sanitizeBasename("生产-db")).toBe("生产-db");- });-- it("strips bidi-override / format chars that can spoof archive viewers", () => {- // U+202E RIGHT-TO-LEFT OVERRIDE could rearrange display: `evil_<RLO>gpj.exe` -> `evil_exe.jpg`.- expect(sanitizeBasename("evil_gpj.exe")).toBe("evil_gpj.exe");- // BOM- expect(sanitizeBasename("prod")).toBe("prod");- // LRM/RLM- expect(sanitizeBasename("ab")).toBe("ab");- // Bidi isolates- expect(sanitizeBasename("prod")).toBe("prod");- // U+061C ARABIC LETTER MARK (bidi control older than U+202x)- expect(sanitizeBasename("ab")).toBe("ab");- });-- it("does not split a surrogate pair when truncating to the length cap", () => {- // 199 ASCII chars + 1 emoji (surrogate pair = 2 UTF-16 units) → s.length=201.- // Slice(0, 200) cuts inside the pair; the high surrogate would be invalid.- const input = "a".repeat(199) + "😀";- const out = sanitizeBasename(input);- expect(out.length).toBe(199); // emoji dropped entirely- // No lone surrogate left at the tail.- const last = out.charCodeAt(out.length - 1);- expect(last >= 0xd800 && last <= 0xdfff).toBe(false);- });-});--describe("uniqueFilename (B10 — batch ZIP duplicate filenames)", () => {- it("returns the name unchanged when not yet taken", () => {- const taken = new Set<string>();- expect(uniqueFilename("prod.csv", taken)).toBe("prod.csv");- expect(taken.has("prod.csv")).toBe(true);- });-- it("appends -1 on first collision, -2 on second", () => {- const taken = new Set<string>(["prod.csv"]);- expect(uniqueFilename("prod.csv", taken)).toBe("prod-1.csv");- expect(uniqueFilename("prod.csv", taken)).toBe("prod-2.csv");- });-- it("skips past pre-existing suffixed siblings rather than colliding with them", () => {- // If a customer's batch already had "db" and "db-1" as distinct- // databases, a third group named "db" must become "db-2" rather than- // double-collide with the existing literal "db-1" entry.- const taken = new Set<string>(["db", "db-1"]);- expect(uniqueFilename("db", taken)).toBe("db-2");- });-- it("appends suffix at end if no extension", () => {- const taken = new Set<string>(["batch"]);- expect(uniqueFilename("batch", taken)).toBe("batch-1");- });-- it("respects the LAST dot as extension separator", () => {- const taken = new Set<string>(["a.b.csv"]);- expect(uniqueFilename("a.b.csv", taken)).toBe("a.b-1.csv");- });-- it("treats case-only-different names as colliding (Windows extraction)", () => {- const taken = new Set<string>();- expect(uniqueFilename("Prod.csv", taken)).toBe("Prod.csv");- // Same name in different case must dedup.- expect(uniqueFilename("prod.csv", taken)).toBe("prod-1.csv");- expect(uniqueFilename("PROD.csv", taken)).toBe("PROD-2.csv");- });-- it("treats NFC and NFD forms of the same string as colliding", () => {- const taken = new Set<string>();- const nfc = "café.csv"; // single code point é (U+00E9)- const nfd = "café.csv"; // e + combining acute- expect(uniqueFilename(nfc, taken)).toBe(nfc);- expect(uniqueFilename(nfd, taken)).toBe("café-1.csv");- });- it("appends -N at the end (not before a dot) for path-like inputs", () => {- // dirPrefix dedup in buildDownloadBlob passes "inst/db" paths. When the- // database segment legitimately contains a dot (e.g. "prod.app_v2"),- // treating the dot as an extension boundary would yield "prod-1.app_v2"- // and mis-label the path. The "/" in the input signals path-mode.- const taken = new Set<string>(["inst/prod.app_v2"]);- expect(uniqueFilename("inst/prod.app_v2", taken)).toBe(- "inst/prod.app_v2-1"- );- });-});diff --git a/frontend/src/utils/sql-download/__tests__/formatter-goldens.test.ts b/frontend/src/utils/sql-download/__tests__/formatter-goldens.test.tsdeleted file mode 100644index 7b7d35d62d..0000000000--- a/frontend/src/utils/sql-download/__tests__/formatter-goldens.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";-import { create } from "@bufbuild/protobuf";-import { TimestampSchema } from "@bufbuild/protobuf/wkt";-import { describe, expect, it } from "vitest";-import {- RowValue_TimestampSchema,- RowValue_TimestampTZSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import { formatFloat32, formatTimestamp, formatTimestampTZ } from "../value";--const here = dirname(fileURLToPath(import.meta.url));-const formattersDir = resolve(here, "goldens", "formatters");--function readTSV(filename: string): string[][] {- const text = readFileSync(resolve(formattersDir, filename), "utf-8");- return text- .split("\n")- .map((l) => l.trim())- .filter((l) => l.length > 0 && !l.startsWith("#"))- .map((l) => l.split("\t"));-}--function float32FromHex(hex: string): number {- if (hex.length !== 8) throw new Error(`bad hex ${hex}`);- const u = Number.parseInt(hex, 16);- const buf = new ArrayBuffer(4);- new DataView(buf).setUint32(0, u, false);- return new DataView(buf).getFloat32(0, false);-}--describe("formatter cross-side goldens", () => {- it("formatFloat32 matches Go strconv.FormatFloat(_, 'f', -1, 32)", () => {- for (const [hex, expected] of readTSV("float32.tsv")) {- const got = formatFloat32(float32FromHex(hex));- expect(got, `bits=${hex}`).toBe(expected);- }- });-- it('formatTimestamp matches Go time.Format("2006-01-02 15:04:05.000000")', () => {- for (const [secStr, nanosStr, expected] of readTSV("timestamp.tsv")) {- const ts = create(RowValue_TimestampSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: BigInt(secStr),- nanos: Number.parseInt(nanosStr, 10),- }),- });- const got = formatTimestamp(ts);- expect(got, `seconds=${secStr} nanos=${nanosStr}`).toBe(expected);- }- });-- it("formatTimestampTZ matches Go time.RFC3339Nano in FixedZone", () => {- for (const [secStr, nanosStr, zoneRaw, offsetStr, expected] of readTSV(- "timestamptz.tsv"- )) {- const zone = zoneRaw === "-" ? "" : zoneRaw;- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: BigInt(secStr),- nanos: Number.parseInt(nanosStr, 10),- }),- zone,- offset: Number.parseInt(offsetStr, 10),- });- const got = formatTimestampTZ(tz);- expect(- got,- `seconds=${secStr} nanos=${nanosStr} zone=${zoneRaw} offset=${offsetStr}`- ).toBe(expected);- }- });-});diff --git a/frontend/src/utils/sql-download/__tests__/goldens/formatters/float32.tsv b/frontend/src/utils/sql-download/__tests__/goldens/formatters/float32.tsvdeleted file mode 100644index 69d9aa7ad3..0000000000--- a/frontend/src/utils/sql-download/__tests__/goldens/formatters/float32.tsv+++ /dev/null@@ -1,18 +0,0 @@-# float32 shortest round-trip emission. Backend: strconv.FormatFloat(_, 'f', -1, 32).-# Frontend: formatFloat32 in value.ts. Never exponential. Negative zero preserved.-# Format: <ieee754-bits-hex>\t<expected-output>-# Generated from backend Go implementation; both sides must reproduce byte-for-byte.-00000000 0-80000000 -0-3F800000 1-BF800000 -1-3FC00000 1.5-501502F9 10000000000-33D6BF95 0.0000001-4048F5C3 3.14-7F7FFFFF 340282350000000000000000000000000000000-00000001 0.000000000000000000000000000000000000000000001-00800000 0.000000000000000000000000000000000000011754944-3DCCCCCD 0.1-40490FDB 3.1415927-3F4EFA39 0.8085056diff --git a/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamp.tsv b/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamp.tsvdeleted file mode 100644index d93820c67d..0000000000--- a/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamp.tsv+++ /dev/null@@ -1,10 +0,0 @@-# Timestamp emission. Backend: ts.GoogleTimestamp.AsTime().Format("2006-01-02 15:04:05.000000").-# Frontend: formatTimestamp in value.ts. UTC. 4-digit zero-padded year. 6-digit microseconds (sub-microsecond truncated).-# Format: <seconds>\t<nanos>\t<expected-output>-0 0 1970-01-01 00:00:00.000000--62135596800 0 0001-01-01 00:00:00.000000-1700000000 0 2023-11-14 22:13:20.000000-1700000000 123456789 2023-11-14 22:13:20.123456-1700000000 1 2023-11-14 22:13:20.000000-1700000000 999999999 2023-11-14 22:13:20.999999-253402300799 0 9999-12-31 23:59:59.000000diff --git a/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamptz.tsv b/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamptz.tsvdeleted file mode 100644index 5e2a3a28ce..0000000000--- a/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamptz.tsv+++ /dev/null@@ -1,10 +0,0 @@-# TimestampTZ emission. Backend: ts.AsTime().In(time.FixedZone(zone, offset)).Format(time.RFC3339Nano).-# Frontend: formatTimestampTZ in value.ts. 4-digit zero-padded year. Variable-precision fractional seconds (trailing zeros trimmed; offset=0 emits "Z" regardless of zone name).-# Format: <seconds>\t<nanos>\t<zone>\t<offset-seconds>\t<expected-output>-# Empty zone column is represented as a single dash literal "-" because TSV treats an empty cell ambiguously.-0 0 UTC 0 1970-01-01T00:00:00Z-1700000000 500000000 JST 32400 2023-11-15T07:13:20.5+09:00-1700000000 0 PDT -25200 2023-11-14T15:13:20-07:00-1700000000 0 +0530 19800 2023-11-15T03:43:20+05:30-1700000000 0 -0330 -12600 2023-11-14T18:43:20-03:30-0 0 - 0 1970-01-01T00:00:00Zdiff --git a/frontend/src/utils/sql-download/__tests__/index.test.ts b/frontend/src/utils/sql-download/__tests__/index.test.tsdeleted file mode 100644index 61de9cf23c..0000000000--- a/frontend/src/utils/sql-download/__tests__/index.test.ts+++ /dev/null@@ -1,423 +0,0 @@-// @vitest-environment node--import { create } from "@bufbuild/protobuf";-import * as zipjs from "@zip.js/zip.js";-import { describe, expect, it } from "vitest";-import { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";-import {- QueryResultSchema,- QueryRowSchema,- RowValueSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import { buildDownloadBlob } from "../index";-import type { DownloadGroup } from "../types";--const tinyResult = create(QueryResultSchema, {- columnNames: ["id"],- columnTypeNames: ["INT"],- rows: [],-});--const oneStmtGroup = (- overrides: Partial<DownloadGroup> = {}-): DownloadGroup => ({- instanceId: "prod-instance",- databaseName: "demo-db",- engine: Engine.MYSQL,- statements: [{ result: tinyResult, statement: "SELECT 1" }],- ...overrides,-});--async function readZipEntries(blob: Blob, password?: string) {- const reader = new zipjs.ZipReader(new zipjs.BlobReader(blob), { password });- const entries = await reader.getEntries();- await reader.close();- return entries;-}--async function readEntryText(entry: zipjs.Entry): Promise<string> {- if (!("getData" in entry) || !entry.getData) {- throw new Error("expected file entry, got directory");- }- return entry.getData(new zipjs.TextWriter());-}--describe("buildDownloadBlob", () => {- it("rejects empty groups", async () => {- await expect(- buildDownloadBlob({- groups: [],- format: ExportFormat.CSV,- baseFilename: "demo",- })- ).rejects.toMatchObject({ code: "SerializationFailed" });- });-- it("rejects groups with zero statements", async () => {- await expect(- buildDownloadBlob({- groups: [- {- instanceId: "i",- databaseName: "d",- engine: Engine.MYSQL,- statements: [],- },- ],- format: ExportFormat.CSV,- baseFilename: "demo",- })- ).rejects.toMatchObject({ code: "SerializationFailed" });- });-- it("rejects unsupported format", async () => {- await expect(- buildDownloadBlob({- groups: [oneStmtGroup()],- format: 99 as ExportFormat,- baseFilename: "demo",- })- ).rejects.toMatchObject({ code: "UnsupportedFormat" });- });-- describe("single statement (1 group, 1 statement)", () => {- it("emits ZIP with <instance>/<db>/statement-1.sql and .result.csv", async () => {- const out = await buildDownloadBlob({- groups: [oneStmtGroup()],- format: ExportFormat.CSV,- baseFilename: "demo",- });- expect(out.filename).toBe("demo.zip");- expect(out.mimeType).toBe("application/zip");- const entries = await readZipEntries(out.blob);- expect(entries.map((e) => e.filename).sort()).toEqual([- "prod-instance/demo-db/statement-1.result.csv",- "prod-instance/demo-db/statement-1.sql",- ]);- });-- it("statement-1.sql contains the SQL text", async () => {- const out = await buildDownloadBlob({- groups: [- oneStmtGroup({- statements: [- {- result: tinyResult,- statement: "SELECT * FROM users WHERE id = 1",- },- ],- }),- ],- format: ExportFormat.CSV,- baseFilename: "demo",- });- const entries = await readZipEntries(out.blob);- const sqlEntry = entries.find((e) => e.filename.endsWith(".sql"))!;- const text = await readEntryText(sqlEntry);- expect(text).toBe("SELECT * FROM users WHERE id = 1");- });-- it.each([- [ExportFormat.JSON, "result.json"],- [ExportFormat.SQL, "result.sql"],- [ExportFormat.XLSX, "result.xlsx"],- ])("format %p produces statement-1.%s alongside statement-1.sql", async (format, ext) => {- const out = await buildDownloadBlob({- groups: [oneStmtGroup()],- format,- baseFilename: "demo",- });- const entries = await readZipEntries(out.blob);- const filenames = entries.map((e) => e.filename).sort();- expect(filenames).toContain(`prod-instance/demo-db/statement-1.sql`);- expect(filenames).toContain(`prod-instance/demo-db/statement-1.${ext}`);- });-- it("encrypts every entry under one password", async () => {- const out = await buildDownloadBlob({- groups: [oneStmtGroup()],- format: ExportFormat.CSV,- baseFilename: "demo",- password: "p@ss",- });- const entries = await readZipEntries(out.blob, "p@ss");- expect(entries.every((e) => e.encrypted)).toBe(true);- });- });-- describe("multi-statement (1 group, N statements)", () => {- it("numbers statements 1..N inside the same instance/db dir", async () => {- const out = await buildDownloadBlob({- groups: [- {- instanceId: "prod",- databaseName: "db1",- engine: Engine.POSTGRES,- statements: [- { result: tinyResult, statement: "SELECT 1" },- { result: tinyResult, statement: "SELECT 2" },- { result: tinyResult, statement: "SELECT 3" },- ],- },- ],- format: ExportFormat.CSV,- baseFilename: "multi",- });- const entries = await readZipEntries(out.blob);- expect(entries.map((e) => e.filename).sort()).toEqual([- "prod/db1/statement-1.result.csv",- "prod/db1/statement-1.sql",- "prod/db1/statement-2.result.csv",- "prod/db1/statement-2.sql",- "prod/db1/statement-3.result.csv",- "prod/db1/statement-3.sql",- ]);- });-- it("each statement-N.sql contains its own SQL text", async () => {- const out = await buildDownloadBlob({- groups: [- {- instanceId: "i",- databaseName: "d",- engine: Engine.MYSQL,- statements: [- { result: tinyResult, statement: "SELECT alpha" },- { result: tinyResult, statement: "SELECT beta" },- ],- },- ],- format: ExportFormat.CSV,- baseFilename: "x",- });- const entries = await readZipEntries(out.blob);- const sqls = entries- .filter((e) => e.filename.endsWith(".sql"))- .sort((a, b) => a.filename.localeCompare(b.filename));- const t1 = await readEntryText(sqls[0]);- const t2 = await readEntryText(sqls[1]);- expect(t1).toBe("SELECT alpha");- expect(t2).toBe("SELECT beta");- });- });-- describe("multi-group (batch — N instances/dbs)", () => {- it("each group becomes its own <instance>/<db>/ subtree", async () => {- const out = await buildDownloadBlob({- groups: [- {- instanceId: "prod",- databaseName: "db-a",- engine: Engine.MYSQL,- statements: [{ result: tinyResult, statement: "SELECT 1" }],- },- {- instanceId: "stage",- databaseName: "db-b",- engine: Engine.POSTGRES,- statements: [- { result: tinyResult, statement: "SELECT 1" },- { result: tinyResult, statement: "SELECT 2" },- ],- },- ],- format: ExportFormat.CSV,- baseFilename: "batch",- });- const entries = await readZipEntries(out.blob);- expect(entries.map((e) => e.filename).sort()).toEqual([- "prod/db-a/statement-1.result.csv",- "prod/db-a/statement-1.sql",- "stage/db-b/statement-1.result.csv",- "stage/db-b/statement-1.sql",- "stage/db-b/statement-2.result.csv",- "stage/db-b/statement-2.sql",- ]);- });-- it("uses each group's engine for SQL serialization", async () => {- const result = create(QueryResultSchema, {- columnNames: ["id"],- columnTypeNames: ["INT"],- rows: [- create(QueryRowSchema, {- values: [- create(RowValueSchema, {- kind: { case: "int64Value", value: 42n },- }),- ],- }),- ],- });- const out = await buildDownloadBlob({- groups: [- {- instanceId: "prod",- databaseName: "my",- engine: Engine.MYSQL,- statements: [{ result, statement: "SELECT 42" }],- },- {- instanceId: "prod",- databaseName: "pg",- engine: Engine.POSTGRES,- statements: [{ result, statement: "SELECT 42" }],- },- ],- format: ExportFormat.SQL,- baseFilename: "x",- });- const entries = await readZipEntries(out.blob);- const myEntry = entries.find(- (e) => e.filename === "prod/my/statement-1.result.sql"- )!;- const pgEntry = entries.find(- (e) => e.filename === "prod/pg/statement-1.result.sql"- )!;- const myText = await readEntryText(myEntry);- const pgText = await readEntryText(pgEntry);- expect(myText).toContain("`<table_name>`"); // MySQL backtick- expect(pgText).toContain('"<table_name>"'); // Postgres double-quote- });- });-- describe("path sanitization", () => {- it("sanitizes instanceId and databaseName as path segments", async () => {- const out = await buildDownloadBlob({- groups: [- {- instanceId: "../../etc",- databaseName: "passwd\\x00",- engine: Engine.MYSQL,- statements: [{ result: tinyResult, statement: "SELECT 1" }],- },- ],- format: ExportFormat.CSV,- baseFilename: "demo",- });- const entries = await readZipEntries(out.blob);- // No leading dot / parent-directory, no slash inside segments.- for (const e of entries) {- expect(e.filename).not.toMatch(/^\./);- expect(e.filename).not.toContain("\\");- expect(e.filename).not.toContain("\0");- // exactly two `/` separators (the structure we constructed).- const slashes = (e.filename.match(/\//g) ?? []).length;- expect(slashes).toBe(2);- }- });-- it("disambiguates cross-group dirPrefixes that sanitize to the same path", async () => {- // Two distinct (instanceId, databaseName) inputs that both sanitize- // to "inst_A/db_1". Without dedup, zip.js rejects the second group- // with `File already exists` and aborts the whole batch.- const out = await buildDownloadBlob({- groups: [- {- instanceId: "inst/A",- databaseName: "db/1",- engine: Engine.MYSQL,- statements: [{ result: tinyResult, statement: "SELECT 1" }],- },- {- instanceId: "inst\\A",- databaseName: "db\\1",- engine: Engine.MYSQL,- statements: [{ result: tinyResult, statement: "SELECT 1" }],- },- ],- format: ExportFormat.CSV,- baseFilename: "demo",- });- const entries = await readZipEntries(out.blob);- const filenames = entries.map((e) => e.filename).sort();- // 2 groups × 2 entries (.sql + .result.csv) = 4 entries, all unique.- expect(filenames).toHaveLength(4);- expect(new Set(filenames).size).toBe(4);- // First group keeps the candidate prefix; second gets disambiguated.- expect(filenames).toContain("inst_A/db_1/statement-1.sql");- expect(filenames.some((f) => f.startsWith("inst_A/db_1-"))).toBe(true);- });- });-- describe("caps", () => {- it("rejects when total cells across all groups exceeds cap", async () => {- const wide = create(QueryResultSchema, {- columnNames: Array.from({ length: 100 }, (_, i) => `c${i}`),- rows: Array.from({ length: 30_000 }, () =>- create(QueryRowSchema, { values: [] })- ),- });- // 2 groups × 30k rows × 100 cols = 6M cells > 5M cap.- await expect(- buildDownloadBlob({- groups: [- {- instanceId: "i",- databaseName: "a",- engine: Engine.MYSQL,- statements: [{ result: wide, statement: "SELECT" }],- },- {- instanceId: "i",- databaseName: "b",- engine: Engine.MYSQL,- statements: [{ result: wide, statement: "SELECT" }],- },- ],- format: ExportFormat.CSV,- baseFilename: "demo",- })- ).rejects.toMatchObject({ code: "ResultTooLarge" });- });-- it("rejects when total estimated bytes across all groups exceeds cap", async () => {- const huge = "x".repeat(25 * 1024 * 1024);- const wideStrings = create(QueryResultSchema, {- columnNames: Array.from({ length: 10 }, (_, i) => `c${i}`),- rows: Array.from({ length: 10 }, () =>- create(QueryRowSchema, {- values: Array.from({ length: 10 }, () =>- create(RowValueSchema, {- kind: { case: "stringValue", value: huge },- })- ),- })- ),- });- await expect(- buildDownloadBlob({- groups: [- {- instanceId: "i",- databaseName: "a",- engine: Engine.MYSQL,- statements: [{ result: wideStrings, statement: "SELECT" }],- },- ],- format: ExportFormat.CSV,- baseFilename: "demo",- })- ).rejects.toMatchObject({ code: "ResultTooLarge" });- });- });-- describe("SQL-engine guard", () => {- it("propagates UnsupportedFormat from per-group engine", async () => {- await expect(- buildDownloadBlob({- groups: [- {- instanceId: "i",- databaseName: "d",- engine: Engine.ENGINE_UNSPECIFIED,- statements: [{ result: tinyResult, statement: "SELECT" }],- },- ],- format: ExportFormat.SQL,- baseFilename: "demo",- })- ).rejects.toMatchObject({ code: "UnsupportedFormat" });- });- });-});diff --git a/frontend/src/utils/sql-download/__tests__/json-encoder.test.ts b/frontend/src/utils/sql-download/__tests__/json-encoder.test.tsdeleted file mode 100644index 7f107702bf..0000000000--- a/frontend/src/utils/sql-download/__tests__/json-encoder.test.ts+++ /dev/null@@ -1,70 +0,0 @@-import { describe, expect, it } from "vitest";-import { encodeIndentedJSON } from "../formats/json";-import { float32 } from "../value";--// Tier 2 relaxation: the encoder no longer mirrors Go json.MarshalIndent-// (alphabetical key sort, HTML-safe escape, U+2028/2029 escape, throw on-// NaN/Inf). It now uses native JSON.stringify escape rules + JS Object-// insertion order + float32 cells via formatFloat32. The tests below cover-// the new contract.-describe("encodeIndentedJSON", () => {- it("encodes empty containers", () => {- expect(encodeIndentedJSON([])).toBe("[]");- expect(encodeIndentedJSON({})).toBe("{}");- });-- it("encodes scalars", () => {- expect(encodeIndentedJSON(null)).toBe("null");- expect(encodeIndentedJSON(true)).toBe("true");- expect(encodeIndentedJSON("a")).toBe('"a"');- expect(encodeIndentedJSON(42)).toBe("42");- expect(encodeIndentedJSON(1.5)).toBe("1.5");- });-- it("encodes bigint via .toString() — JSON.stringify can't take bigint natively", () => {- expect(encodeIndentedJSON(9223372036854775807n)).toBe(- "9223372036854775807"- );- });-- it("indents arrays and nested objects with two spaces", () => {- expect(encodeIndentedJSON([1, 2])).toBe("[\n 1,\n 2\n]");- expect(encodeIndentedJSON({ a: 1, b: { c: 2 } })).toBe(- '{\n "a": 1,\n "b": {\n "c": 2\n }\n}'- );- });-- it("preserves object insertion order (NOT alphabetical sort)", () => {- expect(encodeIndentedJSON({ b: 1, a: 2 })).toBe(- '{\n "b": 1,\n "a": 2\n}'- );- });-- it("emits float64 via JS-native Number.toString (exponential at JS thresholds)", () => {- expect(encodeIndentedJSON(1e10)).toBe("10000000000");- expect(encodeIndentedJSON(1e21)).toBe("1e+21");- expect(encodeIndentedJSON(1e-7)).toBe("1e-7");- });-- it("emits float32 cells via formatFloat32 (always 'f' verb, byte-equal to backend CSV/SQL/XLSX)", () => {- expect(encodeIndentedJSON(float32(1.5))).toBe("1.5");- // MaxFloat32 stays in 'f' verb (no exponential). Backend JSON's encoding/json- // would emit "3.4028235e+38" for the same value — diverged under Tier 2.- expect(encodeIndentedJSON(float32(3.4028235e38))).toBe(- "340282350000000000000000000000000000000"- );- });-- it("maps NaN / +Inf / -Inf to null (matches JSON.stringify)", () => {- expect(encodeIndentedJSON(Number.NaN)).toBe("null");- expect(encodeIndentedJSON(Number.POSITIVE_INFINITY)).toBe("null");- expect(encodeIndentedJSON(Number.NEGATIVE_INFINITY)).toBe("null");- });-- it("delegates string escapes to JSON.stringify — no HTML-safe `<>&` escape", () => {- expect(encodeIndentedJSON("<a>&")).toBe('"<a>&"');- expect(encodeIndentedJSON('a"b')).toBe('"a\\"b"');- expect(encodeIndentedJSON("a\\b")).toBe('"a\\\\b"');- expect(encodeIndentedJSON("a\x00b")).toBe('"a\\u0000b"');- });-});diff --git a/frontend/src/utils/sql-download/__tests__/json.test.ts b/frontend/src/utils/sql-download/__tests__/json.test.tsdeleted file mode 100644index f0da19ded7..0000000000--- a/frontend/src/utils/sql-download/__tests__/json.test.ts+++ /dev/null@@ -1,151 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";-import { describe, expect, it } from "vitest";-import {- type QueryResult,- QueryResultSchema,- QueryRowSchema,- type RowValue,- RowValueSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import { serializeJSON } from "../formats/json";--const TEXT_DECODER = new TextDecoder("utf-8");--const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });-const intRow = (n: bigint): RowValue =>- create(RowValueSchema, { kind: { case: "int64Value", value: n } });-const strRow = (s: string): RowValue =>- create(RowValueSchema, { kind: { case: "stringValue", value: s } });-const f32Row = (n: number): RowValue =>- create(RowValueSchema, { kind: { case: "floatValue", value: n } });-const f64Row = (n: number): RowValue =>- create(RowValueSchema, { kind: { case: "doubleValue", value: n } });-const valueRow = (v: Value): RowValue =>- create(RowValueSchema, { kind: { case: "valueValue", value: v } });--const json = (result: QueryResult): string =>- TEXT_DECODER.decode(serializeJSON(result));--describe("serializeJSON", () => {- it("emits [] for an empty result", () => {- expect(json(create(QueryResultSchema, { columnNames: ["a"] }))).toBe("[]");- });-- it("emits basic ASCII rows with column-declaration key order", () => {- const r = create(QueryResultSchema, {- columnNames: ["id", "name"],- rows: [rowOf(intRow(1n), strRow("Alice"))],- });- expect(json(r)).toBe(`[- {- "id": 1,- "name": "Alice"- }-]`);- });-- it("uses JS-native JSON string escapes (no HTML escape)", () => {- const r = create(QueryResultSchema, {- columnNames: ["s"],- rows: [rowOf(strRow(`<a>&\n"`))],- });- expect(json(r)).toBe(`[- {- "s": "<a>&\\n\\""- }-]`);- });-- it("emits float32 via formatFloat32 and float64 via JS native", () => {- const r = create(QueryResultSchema, {- columnNames: ["f32", "f64"],- rows: [rowOf(f32Row(1.5), f64Row(1e-7))],- });- expect(json(r)).toBe(`[- {- "f32": 1.5,- "f64": 1e-7- }-]`);- });-- it("emits structpb cells as JSON-as-string (Tier 2)", () => {- const struct = create(ValueSchema, {- kind: {- case: "structValue",- value: create(StructSchema, {- fields: {- a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),- b: create(ValueSchema, {- kind: { case: "stringValue", value: "x" },- }),- },- }),- },- });- const r = create(QueryResultSchema, {- columnNames: ["v"],- rows: [rowOf(valueRow(struct))],- });- expect(json(r)).toBe(`[- {- "v": "{\\"a\\":1,\\"b\\":\\"x\\"}"- }-]`);- });-- it("emits NaN / +Inf / -Inf as null (matches JSON.stringify) for both float32 and float64 cells", () => {- // Regression: prior to the JSONFloat32 non-finite guard, float32 NaN/Inf- // cells emitted bare `NaN` / `+Inf` / `-Inf` tokens (formatFloat32 output)- // which are not valid JSON and would fail downstream parsers.- const r = create(QueryResultSchema, {- columnNames: [- "nan64",- "posinf64",- "neginf64",- "nan32",- "posinf32",- "neginf32",- ],- rows: [- rowOf(- f64Row(Number.NaN),- f64Row(Number.POSITIVE_INFINITY),- f64Row(Number.NEGATIVE_INFINITY),- f32Row(Number.NaN),- f32Row(Number.POSITIVE_INFINITY),- f32Row(Number.NEGATIVE_INFINITY)- ),- ],- });- expect(json(r)).toBe(`[- {- "nan64": null,- "posinf64": null,- "neginf64": null,- "nan32": null,- "posinf32": null,- "neginf32": null- }-]`);- });-- it("emits int64 / uint64 as decimal integer tokens via bigint.toString()", () => {- const r = create(QueryResultSchema, {- columnNames: ["i"],- rows: [- rowOf(intRow(-9223372036854775808n)),- rowOf(intRow(9223372036854775807n)),- ],- });- expect(json(r)).toBe(`[- {- "i": -9223372036854775808- },- {- "i": 9223372036854775807- }-]`);- });-});diff --git a/frontend/src/utils/sql-download/__tests__/sql.test.ts b/frontend/src/utils/sql-download/__tests__/sql.test.tsdeleted file mode 100644index 1ad2b0e4fb..0000000000--- a/frontend/src/utils/sql-download/__tests__/sql.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";-import { describe, expect, it } from "vitest";-import { Engine } from "@/types/proto-es/v1/common_pb";-import {- type QueryResult,- QueryResultSchema,- QueryRowSchema,- type RowValue,- RowValueSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import { serializeSQL } from "../formats/sql";--const TEXT_DECODER = new TextDecoder("utf-8");--const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });-const intRow = (n: bigint): RowValue =>- create(RowValueSchema, { kind: { case: "int64Value", value: n } });-const strRow = (s: string): RowValue =>- create(RowValueSchema, { kind: { case: "stringValue", value: s } });-const valueRow = (v: Value): RowValue =>- create(RowValueSchema, { kind: { case: "valueValue", value: v } });--const sql = (result: QueryResult, engine: Engine): string =>- TEXT_DECODER.decode(serializeSQL(result, engine));--describe("serializeSQL", () => {- it("MySQL uses backtick identifiers and single-quoted string literals with `'` doubled", () => {- const r = create(QueryResultSchema, {- columnNames: ["id", "name"],- rows: [rowOf(intRow(1n), strRow("it's"))],- });- expect(sql(r, Engine.MYSQL)).toBe(- "INSERT INTO `<table_name>` (`id`,`name`) VALUES (1,'it''s');"- );- });-- it("Postgres uses double-quote identifiers and pq.QuoteLiteral for strings", () => {- const r = create(QueryResultSchema, {- columnNames: ["id", "name"],- rows: [- rowOf(intRow(1n), strRow("plain")),- // Backslash in PG triggers the `E'...'` escape-string syntax.- rowOf(intRow(2n), strRow("a\\b")),- ],- });- expect(sql(r, Engine.POSTGRES)).toBe(- `INSERT INTO "<table_name>" ("id","name") VALUES (1,'plain');\nINSERT INTO "<table_name>" ("id","name") VALUES (2, E'a\\\\b');`- );- });-- it("structpb cell uses engine-aware SQL string quoting (single-quote, embedded `'` doubled), not CSV-style", () => {- const struct = create(ValueSchema, {- kind: {- case: "structValue",- value: create(StructSchema, {- fields: {- a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),- b: create(ValueSchema, {- kind: { case: "stringValue", value: "x" },- }),- },- }),- },- });- const r = create(QueryResultSchema, {- columnNames: ["v"],- rows: [rowOf(valueRow(struct))],- });- // Postgres: pq.QuoteLiteral wraps in `'...'`. No backslash in payload, so no `E'...'`.- expect(sql(r, Engine.POSTGRES)).toBe(- `INSERT INTO "<table_name>" ("v") VALUES ('{"a":1,"b":"x"}');`- );- // MySQL: non-PG engines use Go's strconv.Quote-style escape inside the- // single-quoted literal, which escapes embedded `"` as `\"`. Payload has- // no `'`, so the only escapes come from the JSON-as-string `"` chars.- expect(sql(r, Engine.MYSQL)).toBe(- 'INSERT INTO `<table_name>` (`v`) VALUES (\'{\\"a\\":1,\\"b\\":\\"x\\"}\');'- );- });-- it("throws UnsupportedFormat for engines without a quote-character mapping", () => {- const r = create(QueryResultSchema, {- columnNames: ["a"],- rows: [rowOf(intRow(1n))],- });- expect(() => serializeSQL(r, Engine.ENGINE_UNSPECIFIED)).toThrow(- /UnsupportedFormat|engine/i- );- });-});diff --git a/frontend/src/utils/sql-download/__tests__/value.test.ts b/frontend/src/utils/sql-download/__tests__/value.test.tsdeleted file mode 100644index c0a347d9e3..0000000000--- a/frontend/src/utils/sql-download/__tests__/value.test.ts+++ /dev/null@@ -1,454 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { TimestampSchema } from "@bufbuild/protobuf/wkt";-import { describe, expect, it } from "vitest";-import {- RowValue_TimestampSchema,- RowValue_TimestampTZSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import {- formatFloat32,- formatFloat64,- formatTimestamp,- formatTimestampTZ,- goQuoteInner,- pqQuoteLiteral,-} from "../value";--describe("formatTimestamp", () => {- it("formats epoch as midnight UTC with six fractional zeros", () => {- const ts = create(RowValue_TimestampSchema, {- googleTimestamp: create(TimestampSchema, { seconds: 0n, nanos: 0 }),- });- expect(formatTimestamp(ts)).toBe("1970-01-01 00:00:00.000000");- });-- it("preserves microseconds and truncates sub-microsecond nanos", () => {- // 123456789 ns = 123456 us + 789 ns; expect 123456 in output (truncate, not round)- const ts = create(RowValue_TimestampSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 123456789,- }),- });- expect(formatTimestamp(ts)).toBe("2023-11-14 22:13:20.123456");- });-- it("emits trailing zeros, not stripped", () => {- const ts = create(RowValue_TimestampSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 500000000, // exactly 500000 us- }),- });- expect(formatTimestamp(ts)).toBe("2023-11-14 22:13:20.500000");- });-- it("pads historical years to 4 digits (matches Go's time.Format)", () => {- // Year 1 AD: Go emits "0001-01-01 00:00:00.000000"; JS's getUTCFullYear()- // returns 1, which without padding would yield "1-01-01 ...".- // Unix seconds for 0001-01-01 00:00:00 UTC = -62135596800.- const tsYear1 = create(RowValue_TimestampSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: -62135596800n,- nanos: 0,- }),- });- expect(formatTimestamp(tsYear1)).toBe("0001-01-01 00:00:00.000000");- });-});--describe("formatTimestampTZ", () => {- it("emits Z for zero offset and integer seconds", () => {- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 0,- }),- zone: "UTC",- offset: 0,- });- expect(formatTimestampTZ(tz)).toBe("2023-11-14T22:13:20Z");- });-- it("strips trailing zero digits from fractional second", () => {- // 500_000_000 ns → ".5" (not ".500" or ".500000000")- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 500_000_000,- }),- zone: "UTC",- offset: 0,- });- expect(formatTimestampTZ(tz)).toBe("2023-11-14T22:13:20.5Z");- });-- it("preserves all nine digits when none are trailing zeros", () => {- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 123_456_789,- }),- zone: "UTC",- offset: 0,- });- expect(formatTimestampTZ(tz)).toBe("2023-11-14T22:13:20.123456789Z");- });-- it("renders positive offset as +HH:MM", () => {- // PDT-like: -7 hours from UTC has offset -25200, but test +HH:MM with positive- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 0,- }),- zone: "JST",- offset: 9 * 3600,- });- expect(formatTimestampTZ(tz)).toBe("2023-11-15T07:13:20+09:00");- });-- it("renders negative offset as -HH:MM and shifts wall time", () => {- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: 1700000000n,- nanos: 0,- }),- zone: "PDT",- offset: -7 * 3600,- });- expect(formatTimestampTZ(tz)).toBe("2023-11-14T15:13:20-07:00");- });-- it("pads historical years to 4 digits (matches Go's RFC3339Nano)", () => {- const tz = create(RowValue_TimestampTZSchema, {- googleTimestamp: create(TimestampSchema, {- seconds: -62135596800n,- nanos: 0,- }),- zone: "UTC",- offset: 0,- });- expect(formatTimestampTZ(tz)).toBe("0001-01-01T00:00:00Z");- });-});--describe("formatFloat64", () => {- it.each([- [0, "0"],- [-0, "-0"],- [1.5, "1.5"],- [1e21, "1000000000000000000000"], // never exponential- [1e-7, "0.0000001"],- ])("formats %p as %p (Go strconv 'f' verb, no exponent)", (input, expected) => {- expect(formatFloat64(input)).toBe(expected);- });- // Note: Number.MAX_VALUE is verified via the floats_edges golden in Chunk 3,- // not in this unit test — the exact 309-digit Go output is fragile to- // reproduce by hand. Goldens are the source of truth for that case.-- it("emits NaN, +Inf, -Inf strings", () => {- expect(formatFloat64(Number.NaN)).toBe("NaN");- expect(formatFloat64(Number.POSITIVE_INFINITY)).toBe("+Inf");- expect(formatFloat64(Number.NEGATIVE_INFINITY)).toBe("-Inf");- });-});--describe("formatFloat32", () => {- it("rounds to float32 first, then prints shortest decimal", () => {- // Math.fround(1/3) = 0.3333333432674408- expect(formatFloat32(1 / 3)).toBe("0.33333334");- });-- it("shares special-value rules with formatFloat64", () => {- expect(formatFloat32(Number.NaN)).toBe("NaN");- expect(formatFloat32(Number.POSITIVE_INFINITY)).toBe("+Inf");- expect(formatFloat32(Number.NEGATIVE_INFINITY)).toBe("-Inf");- });-});--describe("goQuoteInner (strconv.Quote inner content)", () => {- it("returns ASCII verbatim", () => {- expect(goQuoteInner("hello")).toBe("hello");- });-- it.each([- [`a"b`, `a\\"b`], // " escaped- [`a\\b`, `a\\\\b`], // \ escaped- ["a\nb", "a\\nb"],- ["a\rb", "a\\rb"],- ["a\tb", "a\\tb"],- ["a\bb", "a\\bb"],- ["a\fb", "a\\fb"],- ["a\vb", "a\\vb"],- ["a\x07b", "a\\ab"], // BEL → \a- ["a\x00b", "a\\x00b"], // NUL → \x00 (lowercase)- ["a\x1bb", "a\\x1bb"], // ESC → \x1b- ["a\x7fb", "a\\x7fb"], // DEL → \x7f- ["a'b", "a'b"], // single quote NOT escaped by strconv.Quote- ])("escapes %p as %p", (input, expected) => {- expect(goQuoteInner(input)).toBe(expected);- });-- it("emits non-printable runes as \\uHHHH (no curly braces)", () => {- // U+200B ZERO WIDTH SPACE is non-printable per unicode.IsPrint- expect(goQuoteInner("ab")).toBe("a\\u200bb");- });-- it("emits non-BMP non-printable runes as \\UHHHHHHHH", () => {- // U+E0001 (LANGUAGE TAG) is non-printable- const langTag = String.fromCodePoint(0xe0001);- expect(goQuoteInner(`a${langTag}b`)).toBe("a\\U000e0001b");- });-- it("emits printable BMP runes verbatim (CJK, emoji)", () => {- expect(goQuoteInner("中文")).toBe("中文");- expect(goQuoteInner("👍")).toBe("👍");- });-- // B9: explicit non-print categories.- it("escapes Private-Use Area BMP runes as \\uHHHH", () => {- expect(goQuoteInner(`a\u{e000}b`)).toBe("a\\ue000b");- expect(goQuoteInner(`a\u{f8ff}b`)).toBe("a\\uf8ffb");- });-- it("escapes Supplementary Private-Use runes as \\UHHHHHHHH", () => {- expect(goQuoteInner(`a${String.fromCodePoint(0xf0000)}b`)).toBe(- "a\\U000f0000b"- );- expect(goQuoteInner(`a${String.fromCodePoint(0x100000)}b`)).toBe(- "a\\U00100000b"- );- });-- it("escapes Zs space-separator runes as \\uHHHH (parity with Go)", () => {- // Go's unicode.IsPrint returns false for the Zs general category except- // ASCII space (0x20). Backend escapes these as `\uXXXX`; the client must- // match or SQL exports diverge for any string with exotic whitespace.- expect(goQuoteInner("a b")).toBe("a\\u2000b"); // EN QUAD- expect(goQuoteInner("a b")).toBe("a\\u200ab"); // HAIR SPACE- expect(goQuoteInner("a b")).toBe("a\\u202fb"); // NARROW NBSP- expect(goQuoteInner("a b")).toBe("a\\u205fb"); // MEDIUM MATH SPACE- expect(goQuoteInner("a b")).toBe("a\\u3000b"); // IDEOGRAPHIC SPACE- expect(goQuoteInner("a b")).toBe("a\\u1680b"); // OGHAM SPACE MARK- });-- it("emits invalid UTF-8 byte as \\xHH", () => {- // We can't form an invalid UTF-8 string in JS directly; this test asserts- // the encoded-bytes path. Skip in JS if no synthetic byte path exists;- // covered instead via Chunk 2 goldens for all-bytes 0x00..0xFF strings.- const lone = String.fromCharCode(0xd800); // lone surrogate- // TextEncoder replaces lone surrogates with U+FFFD; expect REPLACEMENT- // CHARACTER's UTF-8 encoded escape (E� = printable, so verbatim).- expect(goQuoteInner(lone)).toBe("�");- });-});--describe("pqQuoteLiteral", () => {- it("wraps simple string in single quotes", () => {- expect(pqQuoteLiteral("hello")).toBe("'hello'");- });-- it("doubles single quotes inside plain form", () => {- expect(pqQuoteLiteral("it's")).toBe("'it''s'");- });-- it("uses E'…' form when a backslash is present and escapes it", () => {- // Note: Go's pq.QuoteLiteral prepends a space before E' (matches libpq behavior)- expect(pqQuoteLiteral("a\\b")).toBe(" E'a\\\\b'");- });-- it("doubles single quotes inside E form too", () => {- expect(pqQuoteLiteral("it's\\")).toBe(" E'it''s\\\\'");- });-});--import {- type RowValue,- RowValueSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import {- csvCellFromRowValue,- estimateResultBytes,- JSONFloat32,- jsonValueFromRowValue,- sqlValueFromRowValue,- xlsxValueFromRowValue,-} from "../value";--const rv = (kind: RowValue["kind"]) => create(RowValueSchema, { kind });--describe("csvCellFromRowValue", () => {- it("null → empty", () =>- expect(csvCellFromRowValue(rv({ case: "nullValue", value: 0 }))).toBe(""));- it("bool true → true", () =>- expect(csvCellFromRowValue(rv({ case: "boolValue", value: true }))).toBe(- "true"- ));- it("int32 → bare digits", () =>- expect(csvCellFromRowValue(rv({ case: "int32Value", value: 42 }))).toBe(- "42"- ));- it("int64 → bare digits", () =>- expect(- csvCellFromRowValue(- rv({ case: "int64Value", value: 9223372036854775807n })- )- ).toBe("9223372036854775807"));- it('string → double-quoted with `"` doubled', () =>- expect(csvCellFromRowValue(rv({ case: "stringValue", value: 'a"b' }))).toBe(- `"a""b"`- ));- it("bytes → quoted lowercase 0x hex", () =>- expect(- csvCellFromRowValue(- rv({ case: "bytesValue", value: new Uint8Array([0x00, 0xff]) })- )- ).toBe(`"0x00ff"`));-});--describe("jsonValueFromRowValue", () => {- it("null → null", () =>- expect(- jsonValueFromRowValue(rv({ case: "nullValue", value: 0 }))- ).toBeNull());- it("int64 bigint passes through unchanged", () => {- const out = jsonValueFromRowValue(rv({ case: "int64Value", value: 1n }));- expect(out).toBe(1n);- });- it("string is plain string (encoder will JSON-escape)", () => {- expect(jsonValueFromRowValue(rv({ case: "stringValue", value: "x" }))).toBe(- "x"- );- });- it("float32 returns JSONFloat32 instance", () => {- const out = jsonValueFromRowValue(rv({ case: "floatValue", value: 1.5 }));- expect(out).toBeInstanceOf(JSONFloat32);- expect((out as JSONFloat32).value).toBe(Math.fround(1.5));- });-});--describe("sqlValueFromRowValue", () => {- it("non-PG string uses goQuote then SQL '' for single quotes", () => {- expect(- sqlValueFromRowValue(rv({ case: "stringValue", value: "it's" }), false)- ).toBe(`'it''s'`);- });- it("PG string uses pqQuoteLiteral", () => {- // Note: pqQuoteLiteral prepends a space before E' (matches Go lib/pq)- expect(- sqlValueFromRowValue(rv({ case: "stringValue", value: "a\\b" }), true)- ).toBe(` E'a\\\\b'`);- });- it("null → NULL", () =>- expect(- sqlValueFromRowValue(rv({ case: "nullValue", value: 0 }), false)- ).toBe("NULL"));- it("bytes → unquoted 0xhex", () =>- expect(- sqlValueFromRowValue(- rv({ case: "bytesValue", value: new Uint8Array([0x00]) }),- false- )- ).toBe("0x00"));-});--describe("xlsxValueFromRowValue", () => {- it("null → empty string", () =>- expect(xlsxValueFromRowValue(rv({ case: "nullValue", value: 0 }))).toBe(- ""- ));- it("bytes → base64", () =>- expect(- xlsxValueFromRowValue(- rv({ case: "bytesValue", value: new Uint8Array([0x00, 0xff]) })- )- ).toBe("AP8="));-});--describe("estimateResultBytes (cap guard worst-case bounds)", () => {- // Lazy schema imports inside each test to avoid top-of-file churn — the- // existing test file mixes imports throughout.- const loadSchemas = async () => {- const sql = await import("@/types/proto-es/v1/sql_service_pb");- const wkt = await import("@bufbuild/protobuf/wkt");- return { sql, wkt };- };-- it("MaxFloat64 cells are bounded above the formatted byte length", async () => {- const { sql } = await loadSchemas();- // The previous flat 16 const undercounted MaxFloat64 by ~20x: its- // non-exponential form is ~326 chars. The new APPROX_FLOAT64_BYTES- // (336) covers that.- const result = create(sql.QueryResultSchema, {- columnNames: ["d"],- rows: [- { values: [rv({ case: "doubleValue", value: Number.MAX_VALUE })] },- ],- });- const formattedLen = csvCellFromRowValue(- rv({ case: "doubleValue", value: Number.MAX_VALUE })- ).length;- const est = estimateResultBytes(result, Number.MAX_SAFE_INTEGER);- expect(est).toBeGreaterThan(formattedLen);- });-- it("hex-encoded bytes are bounded by 2x byteLength + overhead", async () => {- const { sql } = await loadSchemas();- const longBytes = new Uint8Array(10000);- longBytes.fill(0xab);- // CSV/SQL hex output is 2x byteLength + delimiters; the estimator must- // bound that. The previous `byteLength + 4` const under-counted.- const csvLen = csvCellFromRowValue(- rv({ case: "bytesValue", value: longBytes })- ).length;- const result = create(sql.QueryResultSchema, {- columnNames: ["b"],- rows: [{ values: [rv({ case: "bytesValue", value: longBytes })] }],- });- const est = estimateResultBytes(result, Number.MAX_SAFE_INTEGER);- expect(est).toBeGreaterThanOrEqual(csvLen);- });-- it("structpb value_value is bounded by recursive walk, not a flat 1KB", async () => {- const { sql, wkt } = await loadSchemas();- // A struct whose single string field is 64KB. The old flat 1024 const- // under-counted this by ~64x and let a single cell bypass the byte cap.- const bigString = "x".repeat(64 * 1024);- const inner = create(wkt.ValueSchema, {- kind: {- case: "structValue",- value: create(wkt.StructSchema, {- fields: {- payload: create(wkt.ValueSchema, {- kind: { case: "stringValue", value: bigString },- }),- },- }),- },- });- const result = create(sql.QueryResultSchema, {- columnNames: ["v"],- rows: [{ values: [rv({ case: "valueValue", value: inner })] }],- });- const est = estimateResultBytes(result, Number.MAX_SAFE_INTEGER);- expect(est).toBeGreaterThan(bigString.length);- });-- it("short-circuits once running total crosses cap", async () => {- const { sql } = await loadSchemas();- const rows = [];- for (let i = 0; i < 1000; i++) {- rows.push({- values: [rv({ case: "doubleValue", value: Number.MAX_VALUE })],- });- }- const result = create(sql.QueryResultSchema, { columnNames: ["d"], rows });- // cap = 1000; with ~336 bytes per doubleValue the loop bails after a few- // rows. The returned value is the running total when it crossed cap, not- // the full 1000×336 sum.- const est = estimateResultBytes(result, 1000);- expect(est).toBeGreaterThan(1000);- expect(est).toBeLessThan(336 * 10);- });-});diff --git a/frontend/src/utils/sql-download/__tests__/xlsx.test.ts b/frontend/src/utils/sql-download/__tests__/xlsx.test.tsdeleted file mode 100644index 531f96fd4c..0000000000--- a/frontend/src/utils/sql-download/__tests__/xlsx.test.ts+++ /dev/null@@ -1,125 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";-import ExcelJS from "exceljs";-import { describe, expect, it } from "vitest";-import {- QueryResultSchema,- QueryRowSchema,- type RowValue,- RowValueSchema,-} from "@/types/proto-es/v1/sql_service_pb";-import { serializeXLSX } from "../formats/xlsx";--const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });-const intRow = (n: bigint): RowValue =>- create(RowValueSchema, { kind: { case: "int64Value", value: n } });-const strRow = (s: string): RowValue =>- create(RowValueSchema, { kind: { case: "stringValue", value: s } });-const f64Row = (n: number): RowValue =>- create(RowValueSchema, { kind: { case: "doubleValue", value: n } });-const valueRow = (v: Value): RowValue =>- create(RowValueSchema, { kind: { case: "valueValue", value: v } });--async function loadCells(bytes: Uint8Array): Promise<string[][]> {- const book = new ExcelJS.Workbook();- const ab = bytes.buffer.slice(- bytes.byteOffset,- bytes.byteOffset + bytes.byteLength- );- await book.xlsx.load(ab as ArrayBuffer);- const sheet = book.getWorksheet("Sheet1")!;- const rows: string[][] = [];- sheet.eachRow({ includeEmpty: true }, (row) => {- const cells: string[] = [];- row.eachCell({ includeEmpty: true }, (cell) => {- cells.push(cell.value == null ? "" : String(cell.value));- });- rows.push(cells);- });- return rows;-}--describe("serializeXLSX", () => {- it("writes a header row plus N data rows with string-typed cells", async () => {- const r = create(QueryResultSchema, {- columnNames: ["id", "name"],- rows: [- rowOf(intRow(1n), strRow("Alice")),- rowOf(intRow(2n), strRow("Bob")),- ],- });- expect(await loadCells(await serializeXLSX(r))).toEqual([- ["id", "name"],- ["1", "Alice"],- ["2", "Bob"],- ]);- });-- it("emits NaN / +Inf / -Inf as textual float tokens in cell text, not empty cells", async () => {- // Regression: prior to this guard, non-finite float64 became "", which- // is indistinguishable from a NULL cell in XLSX. Now matches the- // backend's strconv.FormatFloat tokens.- const r = create(QueryResultSchema, {- columnNames: ["nan", "posinf", "neginf"],- rows: [- rowOf(- f64Row(Number.NaN),- f64Row(Number.POSITIVE_INFINITY),- f64Row(Number.NEGATIVE_INFINITY)- ),- ],- });- expect(await loadCells(await serializeXLSX(r))).toEqual([- ["nan", "posinf", "neginf"],- ["NaN", "+Inf", "-Inf"],- ]);- });-- it("emits structpb cells as JSON-as-string in the cell text (Tier 2)", async () => {- const struct = create(ValueSchema, {- kind: {- case: "structValue",- value: create(StructSchema, {- fields: {- a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),- b: create(ValueSchema, {- kind: { case: "stringValue", value: "x" },- }),- },- }),- },- });- const r = create(QueryResultSchema, {- columnNames: ["v"],- rows: [rowOf(valueRow(struct))],- });- expect(await loadCells(await serializeXLSX(r))).toEqual([- ["v"],- [`{"a":1,"b":"x"}`],- ]);- });-- it("throws ResultTooLarge when columns exceed 16384", async () => {- const tooWide = create(QueryResultSchema, {- columnNames: Array.from({ length: 16385 }, (_, i) => `c${i}`),- rows: [],- });- await expect(serializeXLSX(tooWide)).rejects.toMatchObject({- code: "ResultTooLarge",- message: expect.stringContaining("16384"),- });- });-- it("throws ResultTooLarge when data rows exceed 1,048,575", async () => {- // Sparse array — guard rejects on `rows.length` before iteration.- const sparseRows = new Array(1_048_576) as never[];- const tooTall = create(QueryResultSchema, {- columnNames: ["a"],- rows: sparseRows,- });- await expect(serializeXLSX(tooTall)).rejects.toMatchObject({- code: "ResultTooLarge",- message: expect.stringMatching(/1,?048,?575/),- });- });-});diff --git a/frontend/src/utils/sql-download/__tests__/zip.test.ts b/frontend/src/utils/sql-download/__tests__/zip.test.tsdeleted file mode 100644index c5c658db9d..0000000000--- a/frontend/src/utils/sql-download/__tests__/zip.test.ts+++ /dev/null@@ -1,32 +0,0 @@-// @vitest-environment node--import * as zipjs from "@zip.js/zip.js";-import { describe, expect, it } from "vitest";-import { wrapWithMultiEntryZip } from "../zip";--describe("wrapWithMultiEntryZip", () => {- it("produces an encrypted ZIP whose entry decrypts back to original bytes", async () => {- const inner = new TextEncoder().encode("hello world");- const out = await wrapWithMultiEntryZip(- [{ bytes: inner, filename: "hello.txt" }],- "secret",- "outer"- );- expect(out.filename).toBe("outer.zip");- expect(out.mimeType).toBe("application/zip");-- const reader = new zipjs.ZipReader(new zipjs.BlobReader(out.blob), {- password: "secret",- });- const entries = await reader.getEntries();- expect(entries).toHaveLength(1);- expect(entries[0].filename).toBe("hello.txt");- const entry = entries[0];- if (!("getData" in entry) || !entry.getData) {- throw new Error("expected file entry, got directory");- }- const back = await entry.getData(new zipjs.Uint8ArrayWriter());- await reader.close();- expect(new TextDecoder().decode(back)).toBe("hello world");- });-});diff --git a/frontend/src/utils/sql-download/engines.ts b/frontend/src/utils/sql-download/engines.tsdeleted file mode 100644index d37a9012e7..0000000000--- a/frontend/src/utils/sql-download/engines.ts+++ /dev/null@@ -1,20 +0,0 @@-import { Engine } from "@/types/proto-es/v1/common_pb";--/**- * Mirrors backend SQLStatementPrefix in backend/component/export/sql.go:55-64.- * Adding an engine here without adding it on the backend will break goldens.- */-export const SQL_ENGINE_QUOTES: ReadonlyMap<Engine, "`" | '"'> = new Map([- [Engine.MYSQL, "`"],- [Engine.MARIADB, "`"],- [Engine.TIDB, "`"],- [Engine.OCEANBASE, "`"],- [Engine.SPANNER, "`"],- [Engine.CLICKHOUSE, '"'],- [Engine.MSSQL, '"'],- [Engine.ORACLE, '"'],- [Engine.POSTGRES, '"'],- [Engine.REDSHIFT, '"'],- [Engine.SQLITE, '"'],- [Engine.SNOWFLAKE, '"'],-]);diff --git a/frontend/src/utils/sql-download/error-messages.ts b/frontend/src/utils/sql-download/error-messages.tsdeleted file mode 100644index 1a9c2757e9..0000000000--- a/frontend/src/utils/sql-download/error-messages.ts+++ /dev/null@@ -1,43 +0,0 @@-import { isDownloadError } from "./types";--// Accept any translation function that maps a key (plus optional interpolation-// params) to a string; both Vue i18n's ComposerTranslation and react-i18next's-// TFunction satisfy this. Params are passed straight through to whichever-// engine — naming conventions (`{name}` for Vue, `{{name}}` for react-i18next)-// are handled by the engine itself when the matching locale file is loaded.-type AnyTranslate = (- key: string,- params?: Record<string, string | number>-) => string;--export function downloadErrorMessage(error: unknown, t: AnyTranslate): string {- if (isDownloadError(error)) {- // If the throw site attached an i18n hint, prefer it: this is the only- // path that produces translated copy for ResultTooLarge / UnsupportedFormat- // (those error.message strings carry numeric detail that the bare locale- // fallback can't reproduce, but the hint key/params let us reconstruct- // the same sentence localized).- if (error.i18n) {- return t(error.i18n.key, error.i18n.params);- }- if (error.code === "ResultTooLarge") {- return error.message || t("sql-editor.download-too-large");- }- if (error.code === "UnsupportedFormat") {- return error.message || t("sql-editor.sql-download-unavailable");- }- if (error.code === "EncryptionFailed") {- return t("sql-editor.download-encryption-failed");- }- // SerializationFailed and any future code fall through to the generic- // message-extraction path below.- }- // Truncate multi-line errors (zip.js / exceljs throw deep cause chains).- // Cap the displayed message at 240 chars INCLUDING the trailing ellipsis.- const message = (error as Error | null)?.message;- if (message && message.length > 0) {- const firstLine = message.split("\n", 1)[0];- return firstLine.length > 240 ? firstLine.slice(0, 239) + "…" : firstLine;- }- return t("sql-editor.download-failed");-}diff --git a/frontend/src/utils/sql-download/filename.ts b/frontend/src/utils/sql-download/filename.tsdeleted file mode 100644index 93a837bd13..0000000000--- a/frontend/src/utils/sql-download/filename.ts+++ /dev/null@@ -1,102 +0,0 @@-/**- * Sanitize a user-supplied base filename so it is safe to embed inside a ZIP- * entry name or used directly as the outer download filename.- *- * Threat model: a database name or batch label flows from server-controlled- * data through the UI into the ZIP we hand the user. A ZIP entry name like- * `../../etc/passwd` is honored by some unzip implementations; NUL bytes- * confuse downstream tooling; backslashes are path separators on Windows.- *- * Rules (applied in order):- * 1. Strip NUL bytes (always invalid in filenames).- * 2. Replace forward and back slashes with `_` so no path components survive.- * 3. Collapse parent-directory segments (`.`, `..`) since they would still be- * interpretable after step 2.- * 4. Trim leading/trailing whitespace and dots (Windows hostility).- * 5. Truncate to 200 characters — long enough for "<dbname>-YYYYMMDD-HHMMSS"- * style names, short enough to keep ZIP central directory entries small.- * 6. Fall back to "download" if the result is empty.- *- * Note: this intentionally does NOT validate Windows-reserved device names- * (CON, PRN, NUL, AUX, COM1..COM9, LPT1..LPT9). Adding `.csv`/`.zip` etc.- * after sanitization makes them legal again on Windows, and the user-side- * impact is minor compared to the cost of false positives.- */-export const FALLBACK_BASENAME = "download";-export const MAX_BASENAME_LENGTH = 200;--export function sanitizeBasename(input: string): string {- let s = input ?? "";- // Drop NUL bytes outright.- s = s.replaceAll("\0", "");- // Replace path separators (forward and back) with `_`.- s = s.replace(/[/\\]/g, "_");- // Strip Unicode bidi-override and other format characters that can spoof- // displayed filenames in archive viewers (e.g. `evil_<U+202E>gpj.exe`- // appears as `evil_exe.jpg`). Only strip the known-dangerous set, not all- // of category Cf — combining marks and joiners are legitimate in non-ASCII- // identifiers.- // U+061C: Arabic Letter Mark (bidi control predates U+202x)- // U+200B-200F: zero-width / LRM/RLM- // U+202A-202E: bidi embed/override- // U+2066-2069: bidi isolates- // U+FEFF: BOM- s = s.replace(/[\u061C\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g, "");- // Collapse `..` and `.` segments — after replacing slashes there are no- // segments, but a literal "..foo" or trailing "." is still treated as a- // parent-directory hint by some unzip tools. Replace runs of dots with a- // single dot only inside the body (leading/trailing dots are trimmed- // separately below).- s = s.replace(/\.{2,}/g, ".");- // Trim leading/trailing whitespace and dots.- s = s.replace(/^[\s.]+|[\s.]+$/g, "");- if (s.length > MAX_BASENAME_LENGTH) {- s = s.slice(0, MAX_BASENAME_LENGTH);- // If the cap split a surrogate pair, drop the trailing high surrogate- // so we don't return an invalid JS string.- const last = s.charCodeAt(s.length - 1);- if (last >= 0xd800 && last <= 0xdbff) {- s = s.slice(0, -1);- }- }- if (s.length === 0) {- return FALLBACK_BASENAME;- }- return s;-}--/**- * De-duplicate a filename within a set of already-used names. If `name` is- * unused, returns it as-is and reserves it. Otherwise appends `-1`, `-2`, ...- * before the extension (or at the end if no extension) until unused.- *- * Intended for ZIP entry names where two database results may share the same- * baseFilename and we must not silently produce two entries with identical- * names — readers behavior is unspecified and at least one entry is lost.- *- * Comparison is case-insensitive AND Unicode-normalized (NFC) so that- * `Prod.csv` / `prod.csv` collide on Windows extraction, and `é` (U+00E9)- * collides with `é` (e + U+0301) on macOS HFS+. Stored set uses the folded- * form; returned filename preserves the caller's original casing.- */-export function uniqueFilename(name: string, taken: Set<string>): string {- const fold = (s: string) => s.normalize("NFC").toLowerCase();- if (!taken.has(fold(name))) {- taken.add(fold(name));- return name;- }- // For filenames, suffix `-N` BEFORE the extension (`prod.csv` → `prod-1.csv`).- // For path-like inputs (containing `/`) the trailing segment isn't a file- // extension — a database named `prod.app_v2` would otherwise become- // `prod-1.app_v2`, which mis-labels the path. Suffix at the end instead.- const dot = name.includes("/") ? -1 : name.lastIndexOf(".");- const stem = dot > 0 ? name.slice(0, dot) : name;- const ext = dot > 0 ? name.slice(dot) : "";- for (let i = 1; ; i++) {- const candidate = `${stem}-${i}${ext}`;- if (!taken.has(fold(candidate))) {- taken.add(fold(candidate));- return candidate;- }- }-}diff --git a/frontend/src/utils/sql-download/formats/csv.ts b/frontend/src/utils/sql-download/formats/csv.tsdeleted file mode 100644index 923b4bb5dc..0000000000--- a/frontend/src/utils/sql-download/formats/csv.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";-import { csvCellFromRowValue } from "../value";--const TEXT_ENCODER = new TextEncoder();--export function serializeCSV(result: QueryResult): Uint8Array {- // Backend writes columnNames + "\n" UNCONDITIONALLY (csv.go:21-26), then- // joins data rows with "\n" with no trailing newline. So:- // zero rows → "header\n"- // N rows → "header\nr1\nr2\n…\nrN"- // A naive [header, ...rows].join("\n") produces "header" for zero rows —- // diverges by one byte. Build header + "\n" + rowJoin instead.- const header = result.columnNames.join(",");- const rowLines = result.rows.map((r) =>- r.values.map(csvCellFromRowValue).join(",")- );- return TEXT_ENCODER.encode(`${header}\n${rowLines.join("\n")}`);-}diff --git a/frontend/src/utils/sql-download/formats/json.ts b/frontend/src/utils/sql-download/formats/json.tsdeleted file mode 100644index 3e402fdaff..0000000000--- a/frontend/src/utils/sql-download/formats/json.ts+++ /dev/null@@ -1,72 +0,0 @@-import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";-import {- formatFloat32,- JSONFloat32,- type JSONInput,- jsonValueFromRowValue,-} from "../value";--const TEXT_ENCODER = new TextEncoder();--/**- * Encode a JSONInput tree as indented JSON text. Tier-2 relaxed encoder:- *- * - String escaping delegates to `JSON.stringify`, inheriting ES2019+ rules- * (no HTML escape; U+2028/2029 escaped as ` ` / ` `).- * - Object keys are emitted in insertion order — typically column order- * from `serializeJSON` below. (Pre-Tier-2 encoder sorted alphabetically- * to match Go map[string]any iteration.)- * - float32 cells still emit via `formatFloat32` to preserve cross-side- * byte-equality (the contract for float32 listed in goldens/formatters/).- * - float64 / int / string / bool emit via JS-native rules.- * - bigint (int64 / uint64 from proto) emit via `.toString()` since- * `JSON.stringify` throws on bigint.- * - NaN / ±Inf → "null" (mirrors `JSON.stringify` and JSON-spec rejection).- */-function encode(v: JSONInput, indent: string, prefix: string): string {- if (v === null) return "null";- if (typeof v === "boolean") return v ? "true" : "false";- if (typeof v === "string") return JSON.stringify(v);- if (typeof v === "bigint") return v.toString();- if (v instanceof JSONFloat32) {- // `formatFloat32` emits "NaN" / "+Inf" / "-Inf" for non-finite values —- // valid output for CSV/SQL/XLSX text cells but NOT valid JSON, so the- // download would be a parse error. Match the bare-number guard just- // below and emit `null` instead.- if (!Number.isFinite(v.value)) return "null";- return formatFloat32(v.value);- }- if (typeof v === "number") {- if (!Number.isFinite(v)) return "null";- return String(v);- }- if (Array.isArray(v)) {- if (v.length === 0) return "[]";- const inner = prefix + indent;- return `[\n${v.map((x) => inner + encode(x, indent, inner)).join(",\n")}\n${prefix}]`;- }- const keys = Object.keys(v);- if (keys.length === 0) return "{}";- const inner = prefix + indent;- return `{\n${keys- .map((k) => `${inner}${JSON.stringify(k)}: ${encode(v[k], indent, inner)}`)- .join(",\n")}\n${prefix}}`;-}--export function encodeIndentedJSON(value: JSONInput, indent = " "): string {- return encode(value, indent, "");-}--export function serializeJSON(result: QueryResult): Uint8Array {- const records = result.rows.map((r) => {- // Object.create(null) so a column literally named `__proto__` (legal SQL:- // `SELECT 1 AS "__proto__"`) becomes an own enumerable property instead- // of triggering Object.prototype's setter and getting silently dropped.- const obj = Object.create(null) as { [k: string]: JSONInput };- for (let i = 0; i < result.columnNames.length; i++) {- obj[result.columnNames[i]] = jsonValueFromRowValue(r.values[i]);- }- return obj;- });- return TEXT_ENCODER.encode(encode(records, " ", ""));-}diff --git a/frontend/src/utils/sql-download/formats/sql.ts b/frontend/src/utils/sql-download/formats/sql.tsdeleted file mode 100644index 925748d592..0000000000--- a/frontend/src/utils/sql-download/formats/sql.ts+++ /dev/null@@ -1,40 +0,0 @@-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";-import { SQL_ENGINE_QUOTES } from "../engines";-import { downloadError } from "../types";-import { isPgLike, sqlValueFromRowValue } from "../value";--const TABLE_PLACEHOLDER = "<table_name>";-const TEXT_ENCODER = new TextEncoder();--function buildPrefix(engine: Engine, columnNames: readonly string[]): string {- const q = SQL_ENGINE_QUOTES.get(engine);- if (!q) {- const engineName = Engine[engine] ?? String(engine);- throw downloadError(- "UnsupportedFormat",- `SQL download is not supported for engine ${engineName}`,- undefined,- {- key: "sql-editor.sql-download-engine-unsupported",- params: { engine: engineName },- }- );- }- const cols = columnNames.map((c) => `${q}${c}${q}`).join(",");- return `INSERT INTO ${q}${TABLE_PLACEHOLDER}${q} (${cols}) VALUES (`;-}--export function serializeSQL(result: QueryResult, engine: Engine): Uint8Array {- const prefix = buildPrefix(engine, result.columnNames);- // Resolve engine → PG-like once. Hot inner loop only sees a boolean.- const isPg = isPgLike(engine);- const lines: string[] = [];- for (const r of result.rows) {- const vals = r.values.map((v) => sqlValueFromRowValue(v, isPg)).join(",");- lines.push(`${prefix}${vals});`);- }- // Backend joins rows with "\n", no trailing newline (sql.go:42-49).- // Zero rows → empty bytes.- return TEXT_ENCODER.encode(lines.join("\n"));-}diff --git a/frontend/src/utils/sql-download/formats/xlsx.ts b/frontend/src/utils/sql-download/formats/xlsx.tsdeleted file mode 100644index 5c38ca5fa5..0000000000--- a/frontend/src/utils/sql-download/formats/xlsx.ts+++ /dev/null@@ -1,69 +0,0 @@-import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";-import { downloadError } from "../types";-import { xlsxValueFromRowValue } from "../value";--// Excel / ECMA-376 hard limit: column XFD (16,384). ExcelJS's col-cache-// throws "Out of bounds. Excel supports columns from 1 to 16384" once-// getCell(_, 16385) is invoked.-const EXCEL_MAX_COLUMN = 16384;-// Excel's hard worksheet row limit (2^20). The serializer writes a header in-// row 1 and data in rows 2..N+1, so max data rows = EXCEL_MAX_ROWS - 1.-// Writing past this produces a workbook Excel cannot reliably open.-const EXCEL_MAX_ROWS = 1_048_576;--export async function serializeXLSX(result: QueryResult): Promise<Uint8Array> {- // Column and row overflows are "result too large for THIS format" — the- // user can still download CSV/JSON/SQL of the same data, or use Export- // for a server-streamed flow. ResultTooLarge keeps the message verbatim- // through downloadErrorMessage so the actual counts reach the user.- if (result.columnNames.length > EXCEL_MAX_COLUMN) {- throw downloadError(- "ResultTooLarge",- `XLSX cannot exceed ${EXCEL_MAX_COLUMN} columns; got ${result.columnNames.length}. Use Export or a different format.`,- undefined,- {- key: "sql-editor.download-too-large-xlsx-columns",- params: {- limit: EXCEL_MAX_COLUMN,- count: result.columnNames.length,- },- }- );- }- if (result.rows.length > EXCEL_MAX_ROWS - 1) {- throw downloadError(- "ResultTooLarge",- `XLSX cannot exceed ${EXCEL_MAX_ROWS - 1} data rows; got ${result.rows.length}. Use Export or a different format.`,- undefined,- {- key: "sql-editor.download-too-large-xlsx-rows",- params: {- limit: (EXCEL_MAX_ROWS - 1).toLocaleString(),- count: result.rows.length.toLocaleString(),- },- }- );- }- // ExcelJS ships as CJS. Vite's dep-prebundle exposes only the default- // export, while Node native ESM exposes both `default` and the named- // members. Destructure `default` to work in both — without this, the- // prod Vite build hits `new undefined()` and every XLSX download fails- // while vitest (which uses Node's resolver, not Vite's prebundle) passes.- const { default: ExcelJS } = await import("exceljs");- const book = new ExcelJS.Workbook();- const sheet = book.addWorksheet("Sheet1");-- // Headers in row 1- for (let j = 0; j < result.columnNames.length; j++) {- sheet.getCell(1, j + 1).value = result.columnNames[j];- }- // Rows from row 2; every cell stored as text (parity with backend).- for (let i = 0; i < result.rows.length; i++) {- const row = result.rows[i];- for (let j = 0; j < row.values.length; j++) {- sheet.getCell(i + 2, j + 1).value = xlsxValueFromRowValue(row.values[j]);- }- }- const buf = await book.xlsx.writeBuffer();- return new Uint8Array(buf as ArrayBuffer);-}diff --git a/frontend/src/utils/sql-download/index.ts b/frontend/src/utils/sql-download/index.tsdeleted file mode 100644index a695169396..0000000000--- a/frontend/src/utils/sql-download/index.ts+++ /dev/null@@ -1,216 +0,0 @@-import { ExportFormat } from "@/types/proto-es/v1/common_pb";-import { sanitizeBasename, uniqueFilename } from "./filename";-import { downloadError, isDownloadError } from "./types";-import type { DownloadInput, DownloadOutput } from "./types";-import { estimateResultBytes } from "./value";-import { serializeCSV } from "./formats/csv";-import { serializeJSON } from "./formats/json";-import { serializeSQL } from "./formats/sql";-import { serializeXLSX } from "./formats/xlsx";-import { wrapWithMultiEntryZip } from "./zip";--export type {- DownloadInput,- DownloadOutput,- DownloadGroup,- DownloadStatement,- DownloadErrorCode,- DownloadError,-} from "./types";--const TEXT_ENCODER = new TextEncoder();--const EXTENSIONS: ReadonlyMap<ExportFormat, { ext: string; mime: string }> =- new Map([- [ExportFormat.CSV, { ext: "csv", mime: "text/csv" }],- [ExportFormat.JSON, { ext: "json", mime: "application/json" }],- [ExportFormat.SQL, { ext: "sql", mime: "application/sql" }],- [- ExportFormat.XLSX,- {- ext: "xlsx",- mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- },- ],- ]);--/**- * Two-level soft cap. The cell cap (1) is O(1) and catches "lots of small- * cells". The byte cap (2) walks RowValues once and short-circuits when the- * running estimate exceeds the limit, catching "small grid with huge cells"- * which the cell cap alone misses. Both throw the same error code.- *- * The maximumResultRows policy at the query stage already bounds N for typical- * customers; these caps are a defensive guard against misconfiguration or- * future policy changes.- *- * Caps apply GLOBALLY across every statement in every group, not per-entry.- */-export const MAX_DOWNLOADABLE_CELLS = 5_000_000;-export const MAX_ESTIMATED_BYTES = 200 * 1024 * 1024; // 200 MB raw cell text--/**- * Build the download blob — always a ZIP whose internal layout mirrors- * backend's `exportResultToZip`:- *- * <baseFilename>.zip- * <instanceId>/<databaseName>/statement-1.sql- * <instanceId>/<databaseName>/statement-1.result.<ext>- * ...- *- * Single SQL editor query → 1 group, 1 statement- * Multi-statement query → 1 group, N statements- * Batch (multi-database) → N groups, each with its own statements- *- * `instanceId` and `databaseName` are sanitized as path segments (slashes,- * NULs, bidi-overrides removed) so a malicious database name can't escape- * the ZIP's intended directory tree.- */-export async function buildDownloadBlob(- input: DownloadInput-): Promise<DownloadOutput> {- if (input.groups.length === 0) {- throw downloadError(- "SerializationFailed",- "buildDownloadBlob called with no groups"- );- }-- const meta = EXTENSIONS.get(input.format);- if (!meta) {- throw downloadError(- "UnsupportedFormat",- `Unsupported format ${input.format}`- );- }-- // Cap check across every statement in every group.- let totalCells = 0;- let totalEstBytes = 0;- let totalStmts = 0;- for (const group of input.groups) {- for (const stmt of group.statements) {- totalStmts += 1;- totalCells += stmt.result.rows.length * stmt.result.columnNames.length;- if (totalCells > MAX_DOWNLOADABLE_CELLS) {- throw downloadError(- "ResultTooLarge",- `Download has ${totalCells.toLocaleString()} cells across ${totalStmts} statement(s); limit is ${MAX_DOWNLOADABLE_CELLS.toLocaleString()}. Reduce the row count or use Export.`,- undefined,- {- key: "sql-editor.download-too-large-cells",- params: {- cells: totalCells.toLocaleString(),- statements: totalStmts,- limit: MAX_DOWNLOADABLE_CELLS.toLocaleString(),- },- }- );- }- totalEstBytes += estimateResultBytes(- stmt.result,- MAX_ESTIMATED_BYTES - totalEstBytes- );- if (totalEstBytes > MAX_ESTIMATED_BYTES) {- const estMB = (totalEstBytes / (1024 * 1024)).toFixed(0);- const capMB = (MAX_ESTIMATED_BYTES / (1024 * 1024)).toFixed(0);- throw downloadError(- "ResultTooLarge",- `Download is ~${estMB} MB across ${totalStmts} statement(s); limit is ${capMB} MB. Reduce the result size or use Export.`,- undefined,- {- key: "sql-editor.download-too-large-bytes",- params: {- megabytes: estMB,- statements: totalStmts,- capMb: capMB,- },- }- );- }- }- }-- if (totalStmts === 0) {- throw downloadError(- "SerializationFailed",- "buildDownloadBlob called with groups but no statements"- );- }-- // Serialize each statement's result + bundle the original SQL alongside.- // Path layout: <instanceId>/<databaseName>/statement-N.{sql,result.<ext>}- //- // Cross-group dirPrefix collisions can occur after sanitization (e.g.- // "inst/A" and "inst_A" both sanitize to "inst_A"; macOS HFS+ collapses- // NFC vs. NFD; Windows extraction is case-insensitive). Run each- // candidate prefix through `uniqueFilename` so distinct inputs always- // produce distinct ZIP entries; otherwise zip.js rejects the second- // group with `File already exists` and the whole batch aborts.- const entries: Array<{ bytes: Uint8Array; filename: string }> = [];- const usedPrefixes = new Set<string>();-- for (const group of input.groups) {- const instSeg = sanitizeBasename(group.instanceId);- const dbSeg = sanitizeBasename(group.databaseName);- const dirPrefix = uniqueFilename(`${instSeg}/${dbSeg}`, usedPrefixes);-- for (let i = 0; i < group.statements.length; i++) {- const stmt = group.statements[i];- const n = i + 1;-- // SQL statement file — always written, even for non-SQL result formats.- entries.push({- bytes: TEXT_ENCODER.encode(stmt.statement),- filename: `${dirPrefix}/statement-${n}.sql`,- });-- // Result file — serialize per the chosen export format.- let resultBytes: Uint8Array;- try {- switch (input.format) {- case ExportFormat.CSV:- resultBytes = serializeCSV(stmt.result);- break;- case ExportFormat.JSON:- resultBytes = serializeJSON(stmt.result);- break;- case ExportFormat.SQL:- resultBytes = serializeSQL(stmt.result, group.engine);- break;- case ExportFormat.XLSX:- resultBytes = await serializeXLSX(stmt.result);- break;- default:- throw downloadError(- "UnsupportedFormat",- `Unsupported format ${input.format}`- );- }- } catch (e) {- // Rethrow any DownloadError verbatim so its actionable message- // (e.g. "JSON cannot encode NaN", "XLSX cannot exceed 1,048,575- // data rows") reaches the user via downloadErrorMessage. Wrapping- // would replace the message with the generic "Failed to serialize- // result" string. isDownloadError is the type guard for the union;- // checking it here avoids drift when DownloadErrorCode grows.- if (isDownloadError(e)) {- throw e;- }- throw downloadError(- "SerializationFailed",- "Failed to serialize result",- e- );- }-- entries.push({- bytes: resultBytes,- filename: `${dirPrefix}/statement-${n}.result.${meta.ext}`,- });- }- }-- const safeOuter = sanitizeBasename(input.baseFilename);- return wrapWithMultiEntryZip(entries, input.password, safeOuter);-}diff --git a/frontend/src/utils/sql-download/types.ts b/frontend/src/utils/sql-download/types.tsdeleted file mode 100644index e163d3744b..0000000000--- a/frontend/src/utils/sql-download/types.ts+++ /dev/null@@ -1,100 +0,0 @@-import type { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";-import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";--/**- * One query result paired with the SQL text that produced it. Goes into a- * group's `statements` array. The `statement` is written to a sibling- * `.sql` file inside the ZIP so users can see what produced each result.- */-export interface DownloadStatement {- result: QueryResult;- statement: string;-}--/**- * One (instance, database) target. Becomes a `<instanceId>/<databaseName>/`- * subdirectory in the output ZIP. Multiple statements under the same group- * share that subdirectory and are numbered `statement-1`, `statement-2`, ...- */-export interface DownloadGroup {- instanceId: string;- databaseName: string;- engine: Engine;- statements: DownloadStatement[];-}--/**- * Top-level download request.- *- * Layout produced (always a ZIP, even for a single statement):- * <baseFilename>.zip- * <instanceId>/<databaseName>/statement-1.sql- * <instanceId>/<databaseName>/statement-1.result.<ext>- * <instanceId>/<databaseName>/statement-2.sql- * ...- *- * Mirrors backend `exportResultToZip` in `backend/api/v1/sql_service.go`.- */-export interface DownloadInput {- groups: DownloadGroup[];- format: ExportFormat;- baseFilename: string;- password?: string;-}--export interface DownloadOutput {- blob: Blob;- filename: string;- mimeType: string;-}--export type DownloadErrorCode =- | "SerializationFailed"- | "EncryptionFailed"- | "UnsupportedFormat"- | "ResultTooLarge";--/** Translation hint attached to a DownloadError. When present, downloadErrorMessage- * surfaces `t(i18n.key, i18n.params)` so the user gets locale-aware copy with- * the runtime numeric details (cell counts, byte limits, engine names) folded- * in via interpolation. Throw sites still set a plain-English `message` as a- * developer-readable fallback (used by tests and console errors). */-export interface DownloadErrorI18n {- key: string;- params?: Record<string, string | number>;-}--export interface DownloadError extends Error {- code: DownloadErrorCode;- cause?: unknown;- i18n?: DownloadErrorI18n;-}--/** Narrow an unknown thrown value to a DownloadError without enumerating the- * code union at every catch site — the rethrow ladder in buildDownloadBlob- * and the message extraction in downloadErrorMessage both want this. Using- * the union literally elsewhere risks drift when a new code is added here. */-export function isDownloadError(e: unknown): e is DownloadError {- return (- e instanceof Error &&- "code" in e &&- typeof (e as { code?: unknown }).code === "string"- );-}--export function downloadError(- code: DownloadErrorCode,- message: string,- cause?: unknown,- i18n?: DownloadErrorI18n-): DownloadError {- const err = new Error(message) as DownloadError;- err.code = code;- if (cause !== undefined) {- err.cause = cause;- }- if (i18n !== undefined) {- err.i18n = i18n;- }- return err;-}diff --git a/frontend/src/utils/sql-download/value.ts b/frontend/src/utils/sql-download/value.tsdeleted file mode 100644index 2f24deea92..0000000000--- a/frontend/src/utils/sql-download/value.ts+++ /dev/null@@ -1,698 +0,0 @@-import type { Value as StructpbValue } from "@bufbuild/protobuf/wkt";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type {- QueryResult,- RowValue,- RowValue_Timestamp,- RowValue_TimestampTZ,-} from "@/types/proto-es/v1/sql_service_pb";--const pad = (n: number, width: number): string =>- n.toString().padStart(width, "0");--/** Format a Timestamp like Go's "2006-01-02 15:04:05.000000". UTC. Truncates sub-microsecond nanos. */-export function formatTimestamp(ts: RowValue_Timestamp): string {- const seconds = Number(ts.googleTimestamp?.seconds ?? 0n);- const nanos = ts.googleTimestamp?.nanos ?? 0;- const date = new Date(seconds * 1000); // UTC ms- // Pad years to 4 digits — Go's time.Format("2006-...") emits "0001-01-01"- // for year 1, while JS's getUTCFullYear() returns 1. Without padding,- // historical-date exports come out as "1-01-01" and break parity.- const yyyy = pad(date.getUTCFullYear(), 4);- const mm = pad(date.getUTCMonth() + 1, 2);- const dd = pad(date.getUTCDate(), 2);- const hh = pad(date.getUTCHours(), 2);- const mi = pad(date.getUTCMinutes(), 2);- const ss = pad(date.getUTCSeconds(), 2);- const micros = pad(Math.floor(nanos / 1000), 6);- return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}.${micros}`;-}--/** Format a TimestampTZ like Go's RFC3339Nano in the proto's FixedZone. */-export function formatTimestampTZ(tz: RowValue_TimestampTZ): string {- const seconds = Number(tz.googleTimestamp?.seconds ?? 0n);- const nanos = tz.googleTimestamp?.nanos ?? 0;- const offset = tz.offset ?? 0; // seconds east of UTC-- // Apply the fixed offset to get wall-clock components in that zone.- const shifted = new Date((seconds + offset) * 1000);- // See formatTimestamp — same year-padding rationale (Go's RFC3339Nano- // produces "0001-01-01T00:00:00Z" for year 1).- const yyyy = pad(shifted.getUTCFullYear(), 4);- const mm = pad(shifted.getUTCMonth() + 1, 2);- const dd = pad(shifted.getUTCDate(), 2);- const hh = pad(shifted.getUTCHours(), 2);- const mi = pad(shifted.getUTCMinutes(), 2);- const ss = pad(shifted.getUTCSeconds(), 2);-- let frac = "";- if (nanos > 0) {- const padded = pad(nanos, 9).replace(/0+$/, "");- frac = padded.length > 0 ? `.${padded}` : "";- }-- let zoneStr: string;- if (offset === 0) {- zoneStr = "Z";- } else {- const sign = offset > 0 ? "+" : "-";- const abs = Math.abs(offset);- const oh = pad(Math.floor(abs / 3600), 2);- const om = pad(Math.floor((abs % 3600) / 60), 2);- zoneStr = `${sign}${oh}:${om}`;- }-- return `${yyyy}-${mm}-${dd}T${hh}:${mi}:${ss}${frac}${zoneStr}`;-}--/**- * Convert a number to Go's strconv.FormatFloat(v, 'f', -1, 64) form:- * shortest round-trip decimal, NEVER exponential, no trailing zeros except- * "0" / "-0".- */-export function formatFloat64(v: number): string {- if (Number.isNaN(v)) return "NaN";- if (v === Number.POSITIVE_INFINITY) return "+Inf";- if (v === Number.NEGATIVE_INFINITY) return "-Inf";- if (Object.is(v, -0)) return "-0";- if (v === 0) return "0";-- const s = v.toString();- if (!/[eE]/.test(s)) return s; // already non-exponential-- // Expand "1.234e21" / "1.234e-7" into fixed decimal manually.- return expandExponential(s);-}--/**- * Mirrors Go's strconv.FormatFloat(v, 'f', -1, 32): shortest round-trip- * decimal for float32 precision, never exponential.- * Uses toPrecision to find the shortest significand that round-trips as- * float32, then expands exponential notation if needed.- */-export function formatFloat32(v: number): string {- if (Number.isNaN(v)) return "NaN";- if (v === Number.POSITIVE_INFINITY) return "+Inf";- if (v === Number.NEGATIVE_INFINITY) return "-Inf";- const f32 = Math.fround(v);- if (Object.is(f32, -0)) return "-0";- if (f32 === 0) return "0";- // Find shortest significant-digit count that round-trips through float32.- for (let p = 1; p <= 17; p++) {- const s = f32.toPrecision(p);- if (Math.fround(Number.parseFloat(s)) === f32) {- if (/[eE]/.test(s)) return expandExponential(s);- return s.includes(".") ? s.replace(/\.?0+$/, "") : s;- }- }- return expandExponential(f32.toString());-}--// Hot-path TextEncoder/TextDecoder — `goQuoteInner` runs per SQL string cell,-// so allocating a fresh encoder per call shows up in profiles on wide string-// columns. Both are safe to share (no per-call state).-const TEXT_ENCODER = new TextEncoder();-const FATAL_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });--const HEX = "0123456789abcdef";-const hex2 = (n: number): string => HEX[(n >> 4) & 0xf] + HEX[n & 0xf];-const hex4 = (n: number): string =>- HEX[(n >> 12) & 0xf] +- HEX[(n >> 8) & 0xf] +- HEX[(n >> 4) & 0xf] +- HEX[n & 0xf];-const hex8 = (n: number): string =>- hex4((n >>> 16) & 0xffff) + hex4(n & 0xffff);--// Rough port of Go's unicode.IsPrint: letters, marks, numbers, punct, symbol,-// and ASCII space (0x20) only. We use Intl-free heuristics good enough for-// goldens-driven validation; final correctness anchored to byte-equal goldens.-//-// B9: explicitly reject surrogates (Cs) and Private-Use Area (Co) ranges.-// `unicode.IsPrint` rejects all Cc/Cf/Co/Cs/Cn categories. A full lookup-// table would be excessive — we cover the surrogate range and the three-// PUA blocks (BMP + supplementary). New runes that fall outside these-// known-non-print ranges still go through the heuristic; goldens are the-// source of truth for any specific rune we ship into customer output.-function isPrintRune(cp: number): boolean {- if (cp === 0x20) return true;- if (cp < 0x20 || cp === 0x7f) return false;- // Format / control / unassigned ranges deemed non-print:- if (cp >= 0x80 && cp <= 0xa0) return false;- if (cp === 0xad) return false; // soft hyphen- if (cp === 0x200b || cp === 0x200c || cp === 0x200d) return false;- if (cp === 0x2028 || cp === 0x2029) return false;- // Go's unicode.IsPrint returns false for the Zs (Space_Separator)- // general category except ASCII space; matching that ensures SQL- // exports containing en quads / em spaces / ideographic space round-- // trip through `\uXXXX` escapes the same as the Go backend would.- if (cp === 0x1680) return false; // Ogham space mark- if (cp >= 0x2000 && cp <= 0x200a) return false; // en quad..hair space- if (cp === 0x202f) return false; // narrow no-break space- if (cp === 0x205f) return false; // medium mathematical space- if (cp === 0x3000) return false; // ideographic space- if (cp === 0xfeff) return false;- if (cp >= 0xfff0 && cp <= 0xfffc) return false; // specials except U+FFFD (replacement char is printable)- if (cp === 0xfffe || cp === 0xffff) return false; // BOM and non-char- // Surrogates (Cs). TextEncoder normalizes lone surrogates to U+FFFD before- // we ever see one here, but defense in depth is cheap.- if (cp >= 0xd800 && cp <= 0xdfff) return false;- // Private-Use Areas (Co):- if (cp >= 0xe000 && cp <= 0xf8ff) return false; // BMP PUA- if (cp >= 0xf0000 && cp <= 0xffffd) return false; // Supplementary PUA-A- if (cp >= 0x100000 && cp <= 0x10fffd) return false; // Supplementary PUA-B- if (cp >= 0xe0000 && cp <= 0xe007f) return false;- return true;-}--/**- * Reproduce the inner contents of Go's strconv.Quote(s):- * the double-quote-stripped middle of `"…"`. Caller wraps in single quotes- * and replaces ' with '' for SQL literals.- *- * Substrate: encode JS string to UTF-8, decode rune-by-rune; isolated bytes- * that fail UTF-8 decode become \xHH (matches Go's per-byte behavior).- */-export function goQuoteInner(s: string): string {- const bytes = TEXT_ENCODER.encode(s);- const decoder = FATAL_UTF8_DECODER;- let out = "";- let i = 0;- while (i < bytes.length) {- // Determine UTF-8 sequence length from leading byte.- const b = bytes[i];- let size: number;- if (b < 0x80) size = 1;- else if ((b & 0xe0) === 0xc0) size = 2;- else if ((b & 0xf0) === 0xe0) size = 3;- else if ((b & 0xf8) === 0xf0) size = 4;- else size = 1; // invalid leading byte → single- let rune: number | null = null;- if (size > 1 && i + size <= bytes.length) {- try {- const seg = bytes.subarray(i, i + size);- const text = decoder.decode(seg);- if (text.length > 0) {- rune = text.codePointAt(0)!;- }- } catch {- rune = null;- }- } else if (size === 1) {- rune = b;- }- if (rune === null) {- out += "\\x" + hex2(b);- i += 1;- continue;- }- out += escapeRune(rune);- i += size;- }- return out;-}--function escapeRune(cp: number): string {- switch (cp) {- case 0x07:- return "\\a";- case 0x08:- return "\\b";- case 0x09:- return "\\t";- case 0x0a:- return "\\n";- case 0x0b:- return "\\v";- case 0x0c:- return "\\f";- case 0x0d:- return "\\r";- case 0x22:- return '\\"';- case 0x5c:- return "\\\\";- }- if (cp < 0x20 || cp === 0x7f) {- return "\\x" + hex2(cp);- }- if (isPrintRune(cp)) {- return String.fromCodePoint(cp);- }- if (cp <= 0xffff) {- return "\\u" + hex4(cp);- }- return "\\U" + hex8(cp);-}--function expandExponential(s: string): string {- const m = /^(-?)(\d+)(?:\.(\d+))?[eE]([+-]?\d+)$/.exec(s);- if (!m) {- // Defensive — should never happen for finite numbers.- return s;- }- const [, sign, intPart, fracPart = "", expPart] = m;- const exp = Number.parseInt(expPart, 10);- const digits = intPart + fracPart;- const decimalPos = intPart.length + exp;-- if (decimalPos <= 0) {- return (- `${sign}0.${"0".repeat(-decimalPos)}${digits}`.replace(/0+$/, "") ||- `${sign}0`- );- }- if (decimalPos >= digits.length) {- return `${sign}${digits}${"0".repeat(decimalPos - digits.length)}`;- }- const left = digits.slice(0, decimalPos);- const right = digits.slice(decimalPos).replace(/0+$/, "");- return right.length === 0 ? `${sign}${left}` : `${sign}${left}.${right}`;-}--/**- * Mirror lib/pq.QuoteLiteral — note the leading space before E' when- * backslashes are present. This matches Go's pq.QuoteLiteral exactly:- * https://github.com/lib/pq/blob/v1.11.1/quote.go#L75- *- * B12: NUL bytes (\\x00) are preserved literally inside the single quotes- * for byte-for-byte parity with Go lib/pq. Postgres itself rejects NUL on- * INSERT, so a customer who imports the resulting SQL will get an error- * downstream — this is consistent with the backend behavior and the spec- * accepts it as the contract. We do NOT silently strip or escape NUL here.- */-export function pqQuoteLiteral(s: string): string {- if (s.includes("\\")) {- const escaped = s.replaceAll("\\", "\\\\").replaceAll("'", "''");- return ` E'${escaped}'`;- }- return `'${s.replaceAll("'", "''")}'`;-}--/**- * Compact JSON encoding of a structpb.Value — the cell-content string used- * for VARIANT-style columns across every export format under the Tier 2- * relaxation. Each side emits canonical JSON via JSON.stringify on the- * unwrapped tree; the cross-side byte-equal contract no longer covers- * structpb cells (each side picks its language-natural JSON form, which- * happens to agree for ASCII content and may diverge on HTML-unsafe chars- * or struct field order).- * Inf / NaN → null to mirror JSON.stringify and JSON-spec restrictions.- */-export function structpbValueAsJSON(v: StructpbValue | undefined): string {- return JSON.stringify(unwrapStructpbValue(v));-}--function unwrapStructpbValue(v: StructpbValue | undefined): unknown {- if (!v?.kind) return null;- switch (v.kind.case) {- case "nullValue":- return null;- case "boolValue":- return v.kind.value;- case "numberValue": {- const n = v.kind.value;- return Number.isFinite(n) ? n : null;- }- case "stringValue":- return v.kind.value;- case "listValue":- return v.kind.value.values.map(unwrapStructpbValue);- case "structValue": {- // Object.create(null) so a column literally named "__proto__" inside- // a structpb cell can't pollute the output via Object.prototype.- const out: Record<string, unknown> = Object.create(null);- for (const [k, val] of Object.entries(v.kind.value.fields ?? {})) {- out[k] = unwrapStructpbValue(val);- }- return out;- }- default:- return null;- }-}--/** CSV cell rendering of a structpb value: JSON content surrounded by CSV- * quotes with embedded quotes doubled. Kept exported for compatibility- * with the `value.test.ts` import path; previously emitted the bracket- * "a:1,b:2" form (Tier 1) — now emits JSON-as-string (Tier 2). */-export function csvCellFromStructpbValue(v: StructpbValue | undefined): string {- return csvQuoteString(structpbValueAsJSON(v));-}--/** XLSX cell rendering of a structpb value: raw JSON string (no CSV quoting,- * no surrounding quotes). Also used by the JSON encoder as the scalar- * string value for VARIANT columns. */-export function xlsxStringFromStructpbValue(- v: StructpbValue | undefined-): string {- return structpbValueAsJSON(v);-}--const ENGINES_PG_LIKE: ReadonlySet<Engine> = new Set([- Engine.POSTGRES,- Engine.REDSHIFT,-]);--const bytesToHex = (b: Uint8Array): string => {- let s = "";- for (const byte of b) s += hex2(byte);- return s;-};--const bytesToBase64 = (b: Uint8Array): string => {- let s = "";- for (const byte of b) s += String.fromCharCode(byte);- return btoa(s);-};--const csvQuoteString = (s: string): string => `"${s.replaceAll('"', '""')}"`;--/** Engine-aware single-quoted SQL literal. PG/Redshift use pq-style; others- * use Go's strconv.Quote inner with single-quote doubling. Hoist the- * PG-vs-non-PG branch once per call to avoid repeating the ternary in- * every type case below. */-export function quoteSqlString(s: string, isPg: boolean): string {- return isPg- ? pqQuoteLiteral(s)- : `'${goQuoteInner(s).replaceAll("'", "''")}'`;-}--export function csvCellFromRowValue(v: RowValue | undefined): string {- if (!v?.kind) return "";- switch (v.kind.case) {- case "nullValue":- return "";- case "stringValue":- return csvQuoteString(v.kind.value);- case "boolValue":- return v.kind.value ? "true" : "false";- case "int32Value":- return v.kind.value.toString();- case "int64Value":- return v.kind.value.toString();- case "uint32Value":- return v.kind.value.toString();- case "uint64Value":- return v.kind.value.toString();- case "floatValue":- return formatFloat32(v.kind.value);- case "doubleValue": {- // Tier 2 relaxation: language-natural number emission for CSV/JSON/XLSX- // float64 when finite. SQL float64 still uses formatFloat64 (engine-- // literal compat). NaN / ±Inf cannot be expressed as a JS-native number- // token (`String(NaN)` is "NaN" but `String(Infinity)` is "Infinity",- // diverging from Go's "+Inf"/"-Inf"), AND emitting "" would lose the- // distinction between a non-finite value and a NULL cell — so fall- // through to formatFloat64 for non-finite, which produces the same- // "NaN" / "+Inf" / "-Inf" tokens as the backend.- const n = v.kind.value;- return Number.isFinite(n) ? String(n) : formatFloat64(n);- }- case "bytesValue":- return csvQuoteString("0x" + bytesToHex(v.kind.value));- case "timestampValue":- return csvQuoteString(formatTimestamp(v.kind.value));- case "timestampTzValue":- return csvQuoteString(formatTimestampTZ(v.kind.value));- case "valueValue":- return csvCellFromStructpbValue(v.kind.value);- default:- return "";- }-}--/** What the JSON encoder accepts. `bigint` enables raw int64/uint64 tokens- * without going through JSON.stringify (which throws on bigint).- *- * `JSONFloat32` is a class instance — NOT a plain object with a magic key —- * so a column literally named "__jsonFloat32" can never collide with the- * discriminator. The encoder uses `instanceof JSONFloat32` for routing. */-export class JSONFloat32 {- constructor(public readonly value: number) {}-}-export const float32 = (n: number): JSONFloat32 =>- new JSONFloat32(Math.fround(n));--export type JSONInput =- | null- | boolean- | number- | bigint- | string- | JSONFloat32- | JSONInput[]- | { [key: string]: JSONInput };--/** Map a single proto RowValue to the encoder's input tree directly — no- * intermediate atom shape, no round-trip. Throws SerializationFailed on- * NaN/Inf to mirror Go's encoding/json error. */-export function jsonValueFromRowValue(v: RowValue | undefined): JSONInput {- if (!v?.kind) return null;- switch (v.kind.case) {- case "nullValue":- return null;- case "stringValue":- return v.kind.value;- case "boolValue":- return v.kind.value;- case "int32Value":- return v.kind.value;- case "uint32Value":- return v.kind.value;- case "int64Value":- return v.kind.value; // bigint- case "uint64Value":- return v.kind.value; // bigint- case "floatValue":- return float32(v.kind.value);- case "doubleValue":- return v.kind.value;- case "bytesValue":- return bytesToBase64(v.kind.value);- case "timestampValue":- return formatTimestamp(v.kind.value);- case "timestampTzValue":- return formatTimestampTZ(v.kind.value);- case "valueValue":- return xlsxStringFromStructpbValue(v.kind.value);- default:- return null;- }-}--/** Engine is reduced to a single boolean upstream (in serializeSQL) for the hot loop. */-export function sqlValueFromRowValue(- v: RowValue | undefined,- isPg: boolean-): string {- if (!v?.kind) return "";- switch (v.kind.case) {- case "nullValue":- return "NULL";- case "stringValue":- return quoteSqlString(v.kind.value, isPg);- case "boolValue":- return v.kind.value ? "true" : "false";- case "int32Value":- return v.kind.value.toString();- case "int64Value":- return v.kind.value.toString();- case "uint32Value":- return v.kind.value.toString();- case "uint64Value":- return v.kind.value.toString();- case "floatValue":- return formatFloat32(v.kind.value);- case "doubleValue":- return formatFloat64(v.kind.value);- case "bytesValue":- return "0x" + bytesToHex(v.kind.value);- case "timestampValue":- return quoteSqlString(formatTimestamp(v.kind.value), isPg);- case "timestampTzValue":- return quoteSqlString(formatTimestampTZ(v.kind.value), isPg);- case "valueValue":- // Structpb cells use proper engine-aware SQL string quoting (single-- // quote literals with embedded `'` doubled, or `pq.QuoteLiteral` for- // PG/Redshift). Backend currently still emits CSV-style double-quoted- // strings here (a long-standing quirk noted in HANDOFF.md's "Known- // SQL identifier / CSV header parity gap"); fixing the backend would- // also require regenerating its tests and is intentionally deferred.- // Tier 2 already drops cross-side byte equality for structpb cells,- // so the frontend gets to be correct on its own.- return quoteSqlString(structpbValueAsJSON(v.kind.value), isPg);- default:- return "";- }-}--export const isPgLike = (engine: Engine): boolean =>- ENGINES_PG_LIKE.has(engine);--/**- * Estimate serialized byte size of `result`'s cells, walking RowValues once- * without allocating any serialized output. Returns the running total- * accumulated up to the moment it crosses `cap` (or the full sum if under).- * Caller compares to the cap to decide whether to bail. Includes column-name- * overhead so wide-schema-with-no-rows results aren't free.- *- * Per-cell upper bound bytes, conservative across CSV / SQL / JSON / XLSX- * serialization. The estimator must NEVER under-count: the cap exists to- * prevent browser OOM, so over-estimating is acceptable but under-estimating- * defeats the guard.- *- * string → length * 6 + 4- * JSON `\u00XX` escape is the worst case: a string of pure- * control bytes / `<`,`>`,`&` (Go encoding/json escapes- * these by default) inflates to 6 ASCII bytes per source- * code unit. UTF-8 expansion alone bounds at 3x; the JSON- * escape dominates. CSV/SQL/XLSX worst cases stay under 6x.- * bytes → byteLength * 2 + 4- * CSV/SQL hex-encode (each byte → two hex chars). JSON and- * XLSX base64-encode (4/3x). 2x bounds both.- * float32 → 48- * Max float32 (3.4e+38) in non-exponential form ≈ 40 chars.- * float64 → 336- * MaxFloat64 in non-exponential form ≈ 326 chars (309 integer- * digits + dot + 17 mantissa digits). The previous flat 16- * under-counted by 20x on dense float64 columns.- * int/uint → 24 (covers -9223372036854775808 worst case)- * bool → 8- * timestamp→ 64 (RFC3339Nano with sub-second precision + zone)- * value_value → recursive walk over the structpb tree. The previous- * flat 1024 const let a single huge nested string/list/struct- * bypass the cap.- * null → 4- */-const APPROX_NULL_BYTES = 4;-const APPROX_BOOL_BYTES = 8;-const APPROX_INT_BYTES = 24;-const APPROX_FLOAT32_BYTES = 48;-const APPROX_FLOAT64_BYTES = 336;-const APPROX_TIMESTAMP_BYTES = 64;-const APPROX_BYTES_OVERHEAD = 4;-const APPROX_STRUCT_OVERHEAD = 16;--export function estimateResultBytes(result: QueryResult, cap: number): number {- // JSON re-emits every column name per row (`{"col": v, ...}`), and SQL- // re-emits the INSERT prefix's column list per row. Charging column-name- // overhead only for the header would let a 5M-row × 1-col × 64-byte- // result bypass the cap when serialized as JSON/SQL. Pre-compute the- // per-row column-name cost once and apply it to header + each data row.- // Column names use the SAME 6x string multiplier as cell strings (see- // approxCellBytes) — a JSON object key like `"<col>"` can inflate- // 6x via `<` escaping the same way value strings can.- let columnOverhead = 0;- for (const c of result.columnNames) columnOverhead += c.length * 6 + 4;- let total = columnOverhead;- for (const r of result.rows) {- total += columnOverhead;- for (const v of r.values) {- total += approxCellBytes(v);- if (total > cap) return total;- }- }- return total;-}--function approxCellBytes(v: RowValue | undefined): number {- if (!v?.kind) return APPROX_NULL_BYTES;- switch (v.kind.case) {- case "nullValue":- return APPROX_NULL_BYTES;- case "boolValue":- return APPROX_BOOL_BYTES;- case "int32Value":- case "int64Value":- case "uint32Value":- case "uint64Value":- return APPROX_INT_BYTES;- case "floatValue":- return APPROX_FLOAT32_BYTES;- case "doubleValue":- return APPROX_FLOAT64_BYTES;- case "stringValue":- return v.kind.value.length * 6 + 4;- case "bytesValue":- return v.kind.value.byteLength * 2 + APPROX_BYTES_OVERHEAD;- case "timestampValue":- case "timestampTzValue":- return APPROX_TIMESTAMP_BYTES;- case "valueValue":- return approxStructpbBytes(v.kind.value);- default:- return APPROX_INT_BYTES;- }-}--function approxStructpbBytes(v: StructpbValue | undefined): number {- if (!v?.kind) return APPROX_NULL_BYTES;- switch (v.kind.case) {- case "nullValue":- return APPROX_NULL_BYTES;- case "boolValue":- return APPROX_BOOL_BYTES;- case "numberValue":- return APPROX_FLOAT64_BYTES;- case "stringValue":- return v.kind.value.length * 6 + 4;- case "listValue": {- let total = APPROX_STRUCT_OVERHEAD;- for (const item of v.kind.value.values ?? []) {- total += approxStructpbBytes(item);- }- return total;- }- case "structValue": {- let total = APPROX_STRUCT_OVERHEAD;- for (const [k, val] of Object.entries(v.kind.value.fields ?? {})) {- total += k.length * 6 + 4;- total += approxStructpbBytes(val);- }- return total;- }- default:- return APPROX_INT_BYTES;- }-}--export function xlsxValueFromRowValue(v: RowValue | undefined): string {- if (!v?.kind) return "";- switch (v.kind.case) {- case "nullValue":- return "";- case "stringValue":- return v.kind.value;- case "boolValue":- return v.kind.value ? "true" : "false";- case "int32Value":- return v.kind.value.toString();- case "int64Value":- return v.kind.value.toString();- case "uint32Value":- return v.kind.value.toString();- case "uint64Value":- return v.kind.value.toString();- case "floatValue":- return formatFloat32(v.kind.value);- case "doubleValue": {- // See csvCellFromRowValue's doubleValue branch for the rationale.- // Native String() for finite; formatFloat64 for NaN / ±Inf so we emit- // textual tokens matching the backend ("NaN" / "+Inf" / "-Inf") instead- // of "" (which would be indistinguishable from a NULL cell).- const n = v.kind.value;- return Number.isFinite(n) ? String(n) : formatFloat64(n);- }- case "bytesValue":- return bytesToBase64(v.kind.value);- case "timestampValue":- return formatTimestamp(v.kind.value);- case "timestampTzValue":- return formatTimestampTZ(v.kind.value);- case "valueValue":- return xlsxStringFromStructpbValue(v.kind.value);- default:- return "";- }-}diff --git a/frontend/src/utils/sql-download/zip.ts b/frontend/src/utils/sql-download/zip.tsdeleted file mode 100644index cce1be02b8..0000000000--- a/frontend/src/utils/sql-download/zip.ts+++ /dev/null@@ -1,58 +0,0 @@-import type { DownloadOutput } from "./types";-import { downloadError } from "./types";--// zipjs.configure mutates a process-global; hoist to a single lazy init.-let zipjsConfigured = false;-async function loadZipjs(): Promise<typeof import("@zip.js/zip.js")> {- const zipjs = await import("@zip.js/zip.js");- if (!zipjsConfigured) {- zipjs.configure({ useWebWorkers: false });- zipjsConfigured = true;- }- return zipjs;-}--/**- * Wrap entries in a single ZIP. When `password` is set, every entry is- * encrypted with WinZip AES-256 (zip.js default), matching the backend's- * alexmullins/zip output: extra-field 0x9901, vendor "AE", strength=3,- * actual-method=deflate.- *- * The dynamic import is inside try/catch so a chunk-load failure (slow- * network, blocked CDN, stale service worker) maps to EncryptionFailed- * rather than an unrecognized rejection.- */-export async function wrapWithMultiEntryZip(- entries: Array<{ bytes: Uint8Array; filename: string }>,- password: string | undefined,- outerBaseFilename: string-): Promise<DownloadOutput> {- try {- const zipjs = await loadZipjs();- const writer = new zipjs.ZipWriter(- new zipjs.BlobWriter("application/zip"),- {- ...(password ? { password } : {}),- keepOrder: true,- }- );- for (const entry of entries) {- await writer.add(entry.filename, new zipjs.Uint8ArrayReader(entry.bytes));- }- const blob = await writer.close();- return {- blob,- filename: `${outerBaseFilename}.zip`,- mimeType: "application/zip",- };- } catch (e) {- // EncryptionFailed only when a password was actually involved. Other- // failure modes (dynamic-import failure, duplicate filename rejection,- // OOM) under an unencrypted ZIP shouldn't surface as encryption errors.- throw downloadError(- password ? "EncryptionFailed" : "SerializationFailed",- "Failed to build download ZIP",- e- );- }-}