mirror of
https://github.com/larksuite/cli.git
synced 2026-08-03 08:32:46 +08:00
Compare commits
22 Commits
fix/docs-h
...
v1.0.74
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4168ab84f | ||
|
|
12ca42c953 | ||
|
|
d382ee9053 | ||
|
|
daaacb4977 | ||
|
|
680501c1df | ||
|
|
6675e3c247 | ||
|
|
7b48709438 | ||
|
|
c876841106 | ||
|
|
4c1a92caa6 | ||
|
|
577ff035c3 | ||
|
|
4b4ca4283a | ||
|
|
ad4a6d68c7 | ||
|
|
d8fb368ce4 | ||
|
|
40840915c7 | ||
|
|
fb57e17905 | ||
|
|
4cdfa2fcda | ||
|
|
3c2cc273f7 | ||
|
|
b52677269e | ||
|
|
78390f8ea1 | ||
|
|
d6cebd6723 | ||
|
|
79adf89beb | ||
|
|
9dd355a52d |
@@ -10,9 +10,10 @@
|
||||
## Build & Test
|
||||
|
||||
```bash
|
||||
make build # Build (runs fetch_meta first)
|
||||
make unit-test # Required before PR (runs with -race where supported, e.g. amd64/arm64)
|
||||
make test # Full: vet + unit + integration
|
||||
make build # Build (runs fetch_meta first)
|
||||
make unit-test # Required before PR (runs with -race where supported, e.g. amd64/arm64)
|
||||
make live-skills-test # Opt-in real Skills CLI tests; runs with isolated user directories
|
||||
make test # Full: vet + unit + integration
|
||||
```
|
||||
|
||||
## Notification Opt-Outs
|
||||
|
||||
58
CHANGELOG.md
58
CHANGELOG.md
@@ -2,6 +2,62 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [v1.0.74] - 2026-07-21
|
||||
|
||||
### Features
|
||||
|
||||
- **slides**: add history rollback shortcuts (#1714)
|
||||
- **base**: support per-record batch updates (#1889)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- preserve slides schema issues
|
||||
- allow jq examples in quality gate dry-runs
|
||||
- **im**: warn when flag pagination is truncated (#1906)
|
||||
- **slides**: warn on text shape overflow
|
||||
- **slides**: exempt chart roundtrip attributes from lint
|
||||
- **slides**: detect image text occlusion
|
||||
- **slides**: clarify xml-text-overlap-lint error for positional argument (#1986)
|
||||
|
||||
### Documentation
|
||||
|
||||
- clarify drive upload overwrite guidance (#1982)
|
||||
|
||||
### Tests
|
||||
|
||||
- isolate unit tests from user state (#1883)
|
||||
|
||||
### Refactoring
|
||||
|
||||
- converge success output through a single Emitter that owns the write (#1899)
|
||||
|
||||
## [v1.0.73] - 2026-07-20
|
||||
|
||||
### Features
|
||||
|
||||
- **apps**: design_html support, creative-design skill, unified TOS publish (#1901)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **slides**: detect visual elements outside canvas
|
||||
- reduce public content credential fixture false positives
|
||||
- standardize CLI shortcut text in English (#1942)
|
||||
|
||||
### Documentation
|
||||
|
||||
- **base**: reduce filter and update retry loops (#1879)
|
||||
- **vc**: default transcript routing to smart notes over minutes (#1961)
|
||||
- clarify local trigger automation (#1958)
|
||||
|
||||
### Tests
|
||||
|
||||
- synchronize temporary Git maintenance (#1946)
|
||||
|
||||
### Misc
|
||||
|
||||
- **slides**: update lark-slides skill to 0715 snapshot (#1933)
|
||||
- [codex] support bot menu events (#1765)
|
||||
|
||||
## [v1.0.72] - 2026-07-17
|
||||
|
||||
### Features
|
||||
@@ -1552,6 +1608,8 @@ Bundled AI agent skills for intelligent assistance:
|
||||
- Bilingual documentation (English & Chinese).
|
||||
- CI/CD pipelines: linting, testing, coverage reporting, and automated releases.
|
||||
|
||||
[v1.0.74]: https://github.com/larksuite/cli/releases/tag/v1.0.74
|
||||
[v1.0.73]: https://github.com/larksuite/cli/releases/tag/v1.0.73
|
||||
[v1.0.72]: https://github.com/larksuite/cli/releases/tag/v1.0.72
|
||||
[v1.0.71]: https://github.com/larksuite/cli/releases/tag/v1.0.71
|
||||
[v1.0.70]: https://github.com/larksuite/cli/releases/tag/v1.0.70
|
||||
|
||||
7
Makefile
7
Makefile
@@ -23,7 +23,7 @@ PREFIX ?= /usr/local
|
||||
TEST_GOARCH := $(or $(GOARCH),$(shell go env GOARCH))
|
||||
RACE_FLAG := $(if $(filter riscv64,$(TEST_GOARCH)),,-race)
|
||||
|
||||
.PHONY: all build vet fmt-check script-test test unit-test integration-test examples-build quality-gate install uninstall clean fetch_meta gitleaks sidecar-test
|
||||
.PHONY: all build vet fmt-check script-test test unit-test live-skills-test integration-test examples-build quality-gate install uninstall clean fetch_meta gitleaks sidecar-test
|
||||
|
||||
all: test
|
||||
|
||||
@@ -58,6 +58,11 @@ unit-test: fetch_meta
|
||||
go test $(RACE_FLAG) -gcflags="all=-N -l" -count=1 \
|
||||
./cmd/... ./internal/... ./shortcuts/... ./extension/...
|
||||
|
||||
live-skills-test: fetch_meta
|
||||
LARKSUITE_CLI_RUN_LIVE_SKILLS_TESTS=1 \
|
||||
go test -v -count=1 ./cmd/update \
|
||||
-run '^TestUpdateCommand_(RealSkillsSyncRewritesState|SkillsSyncColdStart)$$'
|
||||
|
||||
# examples-build keeps the shipped plugin-SDK examples compilable. If this
|
||||
# breaks, the plugin author guide's "go build ./..." path is broken.
|
||||
examples-build:
|
||||
|
||||
@@ -344,20 +344,18 @@ func apiPaginate(ctx context.Context, ac *client.APIClient, request client.RawAp
|
||||
|
||||
switch format {
|
||||
case output.FormatNDJSON, output.FormatTable, output.FormatCSV:
|
||||
pf := output.NewPaginatedFormatter(out, format)
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: out,
|
||||
ErrOut: errOut,
|
||||
CommandPath: commandPath,
|
||||
Identity: string(pagOpts.Identity),
|
||||
NoticeProvider: output.GetNotice,
|
||||
})
|
||||
result, hasItems, err := ac.StreamPages(ctx, request, func(items []interface{}) error {
|
||||
// Streaming formats intentionally emit each page after that page has
|
||||
// passed safety scanning. A later page may still fail, so callers
|
||||
// must use the exit code to distinguish complete vs partial output.
|
||||
scanResult := output.ScanForSafety(commandPath, items, errOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
output.WriteAlertWarning(errOut, scanResult.Alert)
|
||||
}
|
||||
pf.FormatPage(items)
|
||||
return nil
|
||||
return emitter.StreamPage(items, output.StreamOptions{Format: format.String()})
|
||||
}, pagOpts)
|
||||
if err != nil {
|
||||
return errs.MarkRaw(err)
|
||||
|
||||
396
cmd/api/api_paginate_test.go
Normal file
396
cmd/api/api_paginate_test.go
Normal file
@@ -0,0 +1,396 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
)
|
||||
|
||||
type apiFailOnWriteWriter struct {
|
||||
buf bytes.Buffer
|
||||
writes int
|
||||
failAt int
|
||||
err error
|
||||
}
|
||||
|
||||
func (w *apiFailOnWriteWriter) Write(p []byte) (int, error) {
|
||||
w.writes++
|
||||
if w.writes == w.failAt {
|
||||
return 0, w.err
|
||||
}
|
||||
return w.buf.Write(p)
|
||||
}
|
||||
|
||||
func newAPIPaginateTestHarness(t *testing.T) (*client.APIClient, *bytes.Buffer, *bytes.Buffer, *httpmock.Registry) {
|
||||
t.Helper()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
previousNotice := output.PendingNotice
|
||||
output.PendingNotice = nil
|
||||
t.Cleanup(func() { output.PendingNotice = previousNotice })
|
||||
|
||||
config := &core.CliConfig{
|
||||
AppID: "test-app",
|
||||
AppSecret: "test-secret",
|
||||
Brand: core.BrandFeishu,
|
||||
}
|
||||
f, out, errOut, reg := cmdutil.TestFactory(t, config)
|
||||
ac, err := f.NewAPIClientWithConfig(config)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAPIClientWithConfig() error = %v", err)
|
||||
}
|
||||
ac.ErrOut = io.Discard
|
||||
return ac, out, errOut, reg
|
||||
}
|
||||
|
||||
func apiPaginateRequest() client.RawApiRequest {
|
||||
return client.RawApiRequest{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/test/v1/items",
|
||||
As: core.AsBot,
|
||||
}
|
||||
}
|
||||
|
||||
func assertAPIPaginateJSONBytes(t *testing.T, got []byte, want interface{}) {
|
||||
t.Helper()
|
||||
wantBytes, err := json.MarshalIndent(want, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("marshal expected JSON: %v", err)
|
||||
}
|
||||
wantBytes = append(wantBytes, '\n')
|
||||
if !bytes.Equal(got, wantBytes) {
|
||||
t.Fatalf("stdout bytes mismatch\ngot:\n%s\nwant:\n%s", got, wantBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_DefaultAggregatesAllPages(t *testing.T) {
|
||||
ac, out, errOut, reg := newAPIPaginateTestHarness(t)
|
||||
calls := 0
|
||||
wantTokens := []string{"", "next-1", "next-2"}
|
||||
for i, wantToken := range wantTokens {
|
||||
page := i + 1
|
||||
hasMore := page < len(wantTokens)
|
||||
data := map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"id": string(rune('0' + page))}},
|
||||
"has_more": hasMore,
|
||||
}
|
||||
if hasMore {
|
||||
data["page_token"] = wantTokens[page]
|
||||
}
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
OnMatch: func(req *http.Request) {
|
||||
calls++
|
||||
if got := req.URL.Query().Get("page_token"); got != wantToken {
|
||||
t.Errorf("request %d page_token = %q, want %q", page, got, wantToken)
|
||||
}
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": data,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
output.FormatJSON, "", out, errOut, "lark-cli api GET", client.PaginationOptions{
|
||||
PageLimit: 10,
|
||||
PageDelay: -1,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("apiPaginate() error = %v, want nil", err)
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Fatalf("pagination requests = %d, want 3", calls)
|
||||
}
|
||||
assertAPIPaginateJSONBytes(t, out.Bytes(), output.Envelope{
|
||||
OK: true,
|
||||
Identity: "bot",
|
||||
Data: map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "1"},
|
||||
map[string]interface{}{"id": "2"},
|
||||
map[string]interface{}{"id": "3"},
|
||||
},
|
||||
"has_more": false,
|
||||
},
|
||||
})
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_StreamingFormatsEmitExactMultiPageBytes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "ndjson",
|
||||
format: output.FormatNDJSON,
|
||||
want: "{\"id\":\"1\",\"name\":\"Alice\"}\n{\"id\":\"2\",\"name\":\"Carol\",\"page_only\":\"ignored\"}\n",
|
||||
},
|
||||
{
|
||||
name: "table",
|
||||
format: output.FormatTable,
|
||||
want: "id name \n── ─────\n1 Alice\n2 Carol\n",
|
||||
},
|
||||
{
|
||||
name: "csv",
|
||||
format: output.FormatCSV,
|
||||
want: "id,name\n1,Alice\n2,Carol\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ac, out, errOut, reg := newAPIPaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "1", "name": "Alice"},
|
||||
},
|
||||
"has_more": true,
|
||||
"page_token": "next-1",
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "2", "name": "Carol", "page_only": "ignored"},
|
||||
},
|
||||
"has_more": false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
tt.format, "", out, errOut, "lark-cli api GET", client.PaginationOptions{
|
||||
PageLimit: 10,
|
||||
PageDelay: -1,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("apiPaginate() error = %v, want nil", err)
|
||||
}
|
||||
if got := out.String(); got != tt.want {
|
||||
t.Fatalf("stdout byte mismatch\ngot (%d bytes):\n%q\nwant (%d bytes):\n%q", len(got), got, len(tt.want), tt.want)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_StreamingWriteFailureStopsFurtherPages(t *testing.T) {
|
||||
ac, _, errOut, reg := newAPIPaginateTestHarness(t)
|
||||
sentinel := errors.New("page write failed")
|
||||
out := &apiFailOnWriteWriter{failAt: 2, err: sentinel}
|
||||
calls := 0
|
||||
for page := 1; page <= 2; page++ {
|
||||
hasMore := true
|
||||
data := map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"id": page}},
|
||||
"has_more": hasMore,
|
||||
}
|
||||
if hasMore {
|
||||
data["page_token"] = fmt.Sprintf("next-%d", page)
|
||||
}
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
OnMatch: func(*http.Request) {
|
||||
calls++
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": data,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
output.FormatNDJSON, "", out, errOut, "lark-cli api GET",
|
||||
client.PaginationOptions{PageLimit: 10, PageDelay: -1})
|
||||
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("apiPaginate() error = %v, want preserved writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("apiPaginate() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("pagination requests = %d, want 2", calls)
|
||||
}
|
||||
if got, want := out.buf.String(), "{\"id\":1}\n"; got != want {
|
||||
t.Fatalf("stdout bytes = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_StreamingFormatFallsBackToJSONWithoutList(t *testing.T) {
|
||||
ac, out, errOut, reg := newAPIPaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"name": "Test User",
|
||||
"user_id": "u123",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
output.FormatNDJSON, "", out, errOut, "lark-cli api GET", client.PaginationOptions{PageDelay: -1})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("apiPaginate() error = %v, want nil", err)
|
||||
}
|
||||
assertAPIPaginateJSONBytes(t, out.Bytes(), output.Envelope{
|
||||
OK: true,
|
||||
Identity: "bot",
|
||||
Data: map[string]interface{}{
|
||||
"name": "Test User",
|
||||
"user_id": "u123",
|
||||
},
|
||||
})
|
||||
wantWarning := "warning: this API does not return a list, format \"ndjson\" is not supported, falling back to json\n"
|
||||
if got := errOut.String(); got != wantWarning {
|
||||
t.Fatalf("stderr bytes = %q, want %q", got, wantWarning)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_BusinessErrorsWriteRawAndAreMarkedRaw(t *testing.T) {
|
||||
businessResponse := map[string]interface{}{
|
||||
"code": 123456,
|
||||
"msg": "fixture business error",
|
||||
"data": map[string]interface{}{"detail": "business failed"},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
jqExpr string
|
||||
}{
|
||||
{name: "jq", format: output.FormatJSON, jqExpr: ".data.items"},
|
||||
{name: "default_json", format: output.FormatJSON},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ac, out, errOut, reg := newAPIPaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: businessResponse,
|
||||
})
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
tt.format, tt.jqExpr, out, errOut, "lark-cli api GET", client.PaginationOptions{PageDelay: -1})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("apiPaginate() error = nil, want business error")
|
||||
}
|
||||
if !errs.IsRaw(err) {
|
||||
t.Fatalf("errs.IsRaw(error) = false, want true; error = %T: %v", err, err)
|
||||
}
|
||||
assertAPIPaginateJSONBytes(t, out.Bytes(), businessResponse)
|
||||
if bytes.Contains(out.Bytes(), []byte(`"ok": true`)) {
|
||||
t.Fatalf("business-error stdout contains a success envelope:\n%s", out.Bytes())
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_TransportErrorsAreMarkedRaw(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
jqExpr string
|
||||
}{
|
||||
{name: "jq_paginate_all", format: output.FormatJSON, jqExpr: ".data.items"},
|
||||
{name: "stream_pages", format: output.FormatNDJSON},
|
||||
{name: "default_paginate_all", format: output.FormatJSON},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ac, out, errOut, _ := newAPIPaginateTestHarness(t)
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
tt.format, tt.jqExpr, out, errOut, "lark-cli api GET", client.PaginationOptions{PageDelay: -1})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("apiPaginate() error = nil, want transport error")
|
||||
}
|
||||
if !errs.IsRaw(err) {
|
||||
t.Fatalf("errs.IsRaw(error) = false, want true; error = %T: %v", err, err)
|
||||
}
|
||||
if got := out.String(); got != "" {
|
||||
t.Fatalf("stdout bytes = %q, want empty", got)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPaginate_StreamBusinessErrorIsMarkedRaw(t *testing.T) {
|
||||
ac, out, errOut, reg := newAPIPaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 123456,
|
||||
"msg": "fixture business error",
|
||||
"data": map[string]interface{}{},
|
||||
},
|
||||
})
|
||||
|
||||
err := apiPaginate(context.Background(), ac, apiPaginateRequest(),
|
||||
output.FormatNDJSON, "", out, errOut, "lark-cli api GET", client.PaginationOptions{PageDelay: -1})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("apiPaginate() error = nil, want business error")
|
||||
}
|
||||
if !errs.IsRaw(err) {
|
||||
t.Fatalf("errs.IsRaw(error) = false, want true; error = %T: %v", err, err)
|
||||
}
|
||||
if got := out.String(); got != "" {
|
||||
t.Fatalf("stdout bytes = %q, want empty", got)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
@@ -352,6 +352,9 @@ func TestApiCmd_OutputAndPageAllConflict(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApiCmd_BinaryResponse_AutoSave(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cmdutil.TestChdir(t, dir)
|
||||
|
||||
f, stdout, stderr, reg := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app-bin", AppSecret: "test-secret-bin", Brand: core.BrandFeishu,
|
||||
})
|
||||
@@ -371,8 +374,33 @@ func TestApiCmd_BinaryResponse_AutoSave(t *testing.T) {
|
||||
if !strings.Contains(stderr.String(), "binary response detected") {
|
||||
t.Error("expected binary response hint in stderr")
|
||||
}
|
||||
if !strings.Contains(stdout.String(), "saved_path") {
|
||||
t.Error("expected saved_path in output")
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("stdout is not JSON: %v\nstdout:\n%s", err, stdout.String())
|
||||
}
|
||||
savedPath, _ := got["saved_path"].(string)
|
||||
if savedPath == "" {
|
||||
t.Fatalf("saved_path missing from output: %#v", got)
|
||||
}
|
||||
// The file must land inside the temporary cwd — this pins the isolation
|
||||
// contract: rolling back TestChdir would leave download.bin in the repo.
|
||||
wantDir, err := filepath.EvalSymlinks(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotDir, err := filepath.EvalSymlinks(filepath.Dir(savedPath))
|
||||
if err != nil {
|
||||
t.Fatalf("saved_path %q dir not resolvable: %v", savedPath, err)
|
||||
}
|
||||
if gotDir != wantDir {
|
||||
t.Errorf("saved_path %q is outside temp cwd %q", savedPath, wantDir)
|
||||
}
|
||||
content, err := os.ReadFile(savedPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read saved file: %v", err)
|
||||
}
|
||||
if string(content) != "fake-binary-content" {
|
||||
t.Errorf("saved file content = %q, want %q", content, "fake-binary-content")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
46
cmd/auth/testmain_test.go
Normal file
46
cmd/auth/testmain_test.go
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/registry/registrytest"
|
||||
)
|
||||
|
||||
// TestMain isolates auth command tests from the host machine: config, logs
|
||||
// and the registry cache are redirected to a temp dir, then the registry is
|
||||
// seeded from the tracked fixture and initialized eagerly. Domain-completion
|
||||
// tests read the registry, so without seeding a clean checkout would either
|
||||
// fail or trigger a remote metadata fetch.
|
||||
//
|
||||
// Note: os.Exit skips deferred functions, so cleanup runs explicitly after
|
||||
// m.Run before exiting.
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-cmd-auth-test-*")
|
||||
if err != nil {
|
||||
println("cmd/auth test setup: MkdirTemp failed:", err.Error())
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", filepath.Join(root, "config")); err != nil {
|
||||
println("cmd/auth test setup: Setenv failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_LOG_DIR", filepath.Join(root, "logs")); err != nil {
|
||||
println("cmd/auth test setup: Setenv failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := registrytest.Seed(root); err != nil {
|
||||
println("cmd/auth test setup: registrytest.Seed failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -371,10 +371,11 @@ func TestIntegration_StrictModeUser_ProfileOverride_ShortcutExplicitBotReturnsEn
|
||||
|
||||
func TestIntegration_StrictModeBot_ProfileOverride_ServiceExplicitUserReturnsEnvelope(t *testing.T) {
|
||||
f, stdout, stderr := newStrictModeDefaultFactory(t, "target", core.StrictModeBot)
|
||||
rootCmd := buildStrictModeIntegrationRootCmd(t, f)
|
||||
catalog := strictModeFixtureCatalog()
|
||||
rootCmd := buildStrictModeIntegrationRootCmdWithCatalog(t, f, &catalog)
|
||||
|
||||
code := executeRootIntegration(t, f, rootCmd, []string{
|
||||
"im", "chats", "get", "--params", `{"chat_id":"oc_test"}`, "--as", "user", "--dry-run",
|
||||
"fixture", "things", "create", "--data", `{"name":"probe"}`, "--as", "user", "--dry-run",
|
||||
})
|
||||
|
||||
if code != output.ExitValidation {
|
||||
|
||||
@@ -707,20 +707,18 @@ func servicePaginate(ctx context.Context, ac *client.APIClient, request client.R
|
||||
|
||||
switch format {
|
||||
case output.FormatNDJSON, output.FormatTable, output.FormatCSV:
|
||||
pf := output.NewPaginatedFormatter(out, format)
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: out,
|
||||
ErrOut: errOut,
|
||||
CommandPath: commandPath,
|
||||
Identity: string(pagOpts.Identity),
|
||||
NoticeProvider: output.GetNotice,
|
||||
})
|
||||
result, hasItems, err := ac.StreamPages(ctx, request, func(items []interface{}) error {
|
||||
// Streaming formats intentionally emit each page after that page has
|
||||
// passed safety scanning. A later page may still fail, so callers
|
||||
// must use the exit code to distinguish complete vs partial output.
|
||||
scanResult := output.ScanForSafety(commandPath, items, errOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
output.WriteAlertWarning(errOut, scanResult.Alert)
|
||||
}
|
||||
pf.FormatPage(items)
|
||||
return nil
|
||||
return emitter.StreamPage(items, output.StreamOptions{Format: format.String()})
|
||||
}, pagOpts)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
400
cmd/service/service_paginate_test.go
Normal file
400
cmd/service/service_paginate_test.go
Normal file
@@ -0,0 +1,400 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
)
|
||||
|
||||
type serviceFailOnWriteWriter struct {
|
||||
buf bytes.Buffer
|
||||
writes int
|
||||
failAt int
|
||||
err error
|
||||
}
|
||||
|
||||
func (w *serviceFailOnWriteWriter) Write(p []byte) (int, error) {
|
||||
w.writes++
|
||||
if w.writes == w.failAt {
|
||||
return 0, w.err
|
||||
}
|
||||
return w.buf.Write(p)
|
||||
}
|
||||
|
||||
func newServicePaginateTestHarness(t *testing.T) (*client.APIClient, *bytes.Buffer, *bytes.Buffer, *httpmock.Registry) {
|
||||
t.Helper()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
previousNotice := output.PendingNotice
|
||||
output.PendingNotice = nil
|
||||
t.Cleanup(func() { output.PendingNotice = previousNotice })
|
||||
|
||||
config := &core.CliConfig{
|
||||
AppID: "test-app",
|
||||
AppSecret: "test-secret",
|
||||
Brand: core.BrandFeishu,
|
||||
}
|
||||
f, out, errOut, reg := cmdutil.TestFactory(t, config)
|
||||
ac, err := f.NewAPIClientWithConfig(config)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAPIClientWithConfig() error = %v", err)
|
||||
}
|
||||
ac.ErrOut = io.Discard
|
||||
return ac, out, errOut, reg
|
||||
}
|
||||
|
||||
func servicePaginateRequest() client.RawApiRequest {
|
||||
return client.RawApiRequest{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/test/v1/items",
|
||||
As: core.AsBot,
|
||||
}
|
||||
}
|
||||
|
||||
func assertServicePaginateJSONBytes(t *testing.T, got []byte, want interface{}) {
|
||||
t.Helper()
|
||||
wantBytes, err := json.MarshalIndent(want, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("marshal expected JSON: %v", err)
|
||||
}
|
||||
wantBytes = append(wantBytes, '\n')
|
||||
if !bytes.Equal(got, wantBytes) {
|
||||
t.Fatalf("stdout bytes mismatch\ngot:\n%s\nwant:\n%s", got, wantBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_DefaultAggregatesAllPages(t *testing.T) {
|
||||
ac, out, errOut, reg := newServicePaginateTestHarness(t)
|
||||
calls := 0
|
||||
wantTokens := []string{"", "next-1", "next-2"}
|
||||
for i, wantToken := range wantTokens {
|
||||
page := i + 1
|
||||
hasMore := page < len(wantTokens)
|
||||
data := map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"id": string(rune('0' + page))}},
|
||||
"has_more": hasMore,
|
||||
}
|
||||
if hasMore {
|
||||
data["page_token"] = wantTokens[page]
|
||||
}
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
OnMatch: func(req *http.Request) {
|
||||
calls++
|
||||
if got := req.URL.Query().Get("page_token"); got != wantToken {
|
||||
t.Errorf("request %d page_token = %q, want %q", page, got, wantToken)
|
||||
}
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": data,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
output.FormatJSON, "", out, errOut, "lark-cli test items list", client.PaginationOptions{
|
||||
PageLimit: 10,
|
||||
PageDelay: -1,
|
||||
}, ac.CheckResponse)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("servicePaginate() error = %v, want nil", err)
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Fatalf("pagination requests = %d, want 3", calls)
|
||||
}
|
||||
assertServicePaginateJSONBytes(t, out.Bytes(), output.Envelope{
|
||||
OK: true,
|
||||
Identity: "bot",
|
||||
Data: map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "1"},
|
||||
map[string]interface{}{"id": "2"},
|
||||
map[string]interface{}{"id": "3"},
|
||||
},
|
||||
"has_more": false,
|
||||
},
|
||||
})
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_StreamingFormatsEmitExactMultiPageBytes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "ndjson",
|
||||
format: output.FormatNDJSON,
|
||||
want: "{\"id\":\"1\",\"name\":\"Alice\"}\n{\"id\":\"2\",\"name\":\"Carol\",\"page_only\":\"ignored\"}\n",
|
||||
},
|
||||
{
|
||||
name: "table",
|
||||
format: output.FormatTable,
|
||||
want: "id name \n── ─────\n1 Alice\n2 Carol\n",
|
||||
},
|
||||
{
|
||||
name: "csv",
|
||||
format: output.FormatCSV,
|
||||
want: "id,name\n1,Alice\n2,Carol\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ac, out, errOut, reg := newServicePaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "1", "name": "Alice"},
|
||||
},
|
||||
"has_more": true,
|
||||
"page_token": "next-1",
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "2", "name": "Carol", "page_only": "ignored"},
|
||||
},
|
||||
"has_more": false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
tt.format, "", out, errOut, "lark-cli test items list", client.PaginationOptions{
|
||||
PageLimit: 10,
|
||||
PageDelay: -1,
|
||||
}, ac.CheckResponse)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("servicePaginate() error = %v, want nil", err)
|
||||
}
|
||||
if got := out.String(); got != tt.want {
|
||||
t.Fatalf("stdout byte mismatch\ngot (%d bytes):\n%q\nwant (%d bytes):\n%q", len(got), got, len(tt.want), tt.want)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_StreamingWriteFailureStopsFurtherPages(t *testing.T) {
|
||||
ac, _, errOut, reg := newServicePaginateTestHarness(t)
|
||||
sentinel := errors.New("page write failed")
|
||||
out := &serviceFailOnWriteWriter{failAt: 2, err: sentinel}
|
||||
calls := 0
|
||||
for page := 1; page <= 2; page++ {
|
||||
hasMore := true
|
||||
data := map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"id": page}},
|
||||
"has_more": hasMore,
|
||||
}
|
||||
if hasMore {
|
||||
data["page_token"] = fmt.Sprintf("next-%d", page)
|
||||
}
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
OnMatch: func(*http.Request) {
|
||||
calls++
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": data,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
output.FormatNDJSON, "", out, errOut, "lark-cli test items list",
|
||||
client.PaginationOptions{PageLimit: 10, PageDelay: -1}, ac.CheckResponse)
|
||||
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("servicePaginate() error = %v, want preserved writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("servicePaginate() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("pagination requests = %d, want 2", calls)
|
||||
}
|
||||
if got, want := out.buf.String(), "{\"id\":1}\n"; got != want {
|
||||
t.Fatalf("stdout bytes = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_StreamingFormatFallsBackToJSONWithoutList(t *testing.T) {
|
||||
ac, out, errOut, reg := newServicePaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"name": "Test User",
|
||||
"user_id": "u123",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
output.FormatNDJSON, "", out, errOut, "lark-cli test items get",
|
||||
client.PaginationOptions{PageDelay: -1}, ac.CheckResponse)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("servicePaginate() error = %v, want nil", err)
|
||||
}
|
||||
assertServicePaginateJSONBytes(t, out.Bytes(), output.Envelope{
|
||||
OK: true,
|
||||
Identity: "bot",
|
||||
Data: map[string]interface{}{
|
||||
"name": "Test User",
|
||||
"user_id": "u123",
|
||||
},
|
||||
})
|
||||
wantWarning := "warning: this API does not return a list, format \"ndjson\" is not supported, falling back to json\n"
|
||||
if got := errOut.String(); got != wantWarning {
|
||||
t.Fatalf("stderr bytes = %q, want %q", got, wantWarning)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_BusinessErrorsWriteRawAndRemainUnmarked(t *testing.T) {
|
||||
businessResponse := map[string]interface{}{
|
||||
"code": 123456,
|
||||
"msg": "fixture business error",
|
||||
"data": map[string]interface{}{"detail": "business failed"},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
jqExpr string
|
||||
}{
|
||||
{name: "jq", format: output.FormatJSON, jqExpr: ".data.items"},
|
||||
{name: "default_json", format: output.FormatJSON},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ac, out, errOut, reg := newServicePaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: businessResponse,
|
||||
})
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
tt.format, tt.jqExpr, out, errOut, "lark-cli test items list",
|
||||
client.PaginationOptions{PageDelay: -1}, ac.CheckResponse)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("servicePaginate() error = nil, want business error")
|
||||
}
|
||||
if errs.IsRaw(err) {
|
||||
t.Fatalf("errs.IsRaw(error) = true, want current servicePaginate pass-through behavior")
|
||||
}
|
||||
assertServicePaginateJSONBytes(t, out.Bytes(), businessResponse)
|
||||
if bytes.Contains(out.Bytes(), []byte(`"ok": true`)) {
|
||||
t.Fatalf("business-error stdout contains a success envelope:\n%s", out.Bytes())
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_TransportErrorsRemainUnmarked(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
jqExpr string
|
||||
}{
|
||||
{name: "jq_paginate_all", format: output.FormatJSON, jqExpr: ".data.items"},
|
||||
{name: "stream_pages", format: output.FormatNDJSON},
|
||||
{name: "default_paginate_all", format: output.FormatJSON},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ac, out, errOut, _ := newServicePaginateTestHarness(t)
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
tt.format, tt.jqExpr, out, errOut, "lark-cli test items list",
|
||||
client.PaginationOptions{PageDelay: -1}, ac.CheckResponse)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("servicePaginate() error = nil, want transport error")
|
||||
}
|
||||
if errs.IsRaw(err) {
|
||||
t.Fatalf("errs.IsRaw(error) = true, want current servicePaginate pass-through behavior")
|
||||
}
|
||||
if got := out.String(); got != "" {
|
||||
t.Fatalf("stdout bytes = %q, want empty", got)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePaginate_StreamBusinessErrorRemainsUnmarked(t *testing.T) {
|
||||
ac, out, errOut, reg := newServicePaginateTestHarness(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 123456,
|
||||
"msg": "fixture business error",
|
||||
"data": map[string]interface{}{},
|
||||
},
|
||||
})
|
||||
|
||||
err := servicePaginate(context.Background(), ac, servicePaginateRequest(),
|
||||
output.FormatNDJSON, "", out, errOut, "lark-cli test items list",
|
||||
client.PaginationOptions{PageDelay: -1}, ac.CheckResponse)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("servicePaginate() error = nil, want business error")
|
||||
}
|
||||
if errs.IsRaw(err) {
|
||||
t.Fatalf("errs.IsRaw(error) = true, want current servicePaginate pass-through behavior")
|
||||
}
|
||||
if got := out.String(); got != "" {
|
||||
t.Fatalf("stdout bytes = %q, want empty", got)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
39
cmd/service/testmain_test.go
Normal file
39
cmd/service/testmain_test.go
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/registry/registrytest"
|
||||
)
|
||||
|
||||
// TestMain isolates service command tests from the host machine: config (and
|
||||
// the registry cache under it) is redirected to a temp dir, then the registry
|
||||
// is seeded from the tracked fixture and initialized eagerly. Tests pass on a
|
||||
// clean checkout with no network, no `make fetch_meta`, and no user cache.
|
||||
//
|
||||
// Note: os.Exit skips deferred functions, so cleanup runs explicitly after
|
||||
// m.Run before exiting.
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-cmd-service-test-*")
|
||||
if err != nil {
|
||||
println("cmd/service test setup: MkdirTemp failed:", err.Error())
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", root); err != nil {
|
||||
println("cmd/service test setup: Setenv failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := registrytest.Seed(root); err != nil {
|
||||
println("cmd/service test setup: registrytest.Seed failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
code := m.Run()
|
||||
os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -12,11 +13,34 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
)
|
||||
|
||||
const startupBrandHelperEnv = "GO_TEST_STARTUP_BRAND_HELPER"
|
||||
|
||||
var _ = flag.String("startup-brand-helper", "", "internal startup brand test helper nonce")
|
||||
|
||||
func isStartupBrandHelper() bool {
|
||||
return startupBrandHelperEnabled(os.Getenv(startupBrandHelperEnv), startupBrandHelperNonce(os.Args))
|
||||
}
|
||||
|
||||
func startupBrandHelperEnabled(envNonce, argNonce string) bool {
|
||||
return envNonce != "" && envNonce == argNonce
|
||||
}
|
||||
|
||||
func startupBrandHelperNonce(args []string) string {
|
||||
const prefix = "-startup-brand-helper="
|
||||
for _, arg := range args {
|
||||
if strings.HasPrefix(arg, prefix) {
|
||||
return strings.TrimPrefix(arg, prefix)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestResolveStartupBrand_Precedence(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", tmp)
|
||||
@@ -54,7 +78,7 @@ func TestResolveStartupBrand_Precedence(t *testing.T) {
|
||||
// sync.Once, so the brand must be injected before the first catalog access.
|
||||
// It runs in a subprocess because the registry is process-global.
|
||||
func TestStartupBrandReachesRegistry_RealStartupOrder(t *testing.T) {
|
||||
if os.Getenv("GO_TEST_STARTUP_BRAND_HELPER") == "1" {
|
||||
if isStartupBrandHelper() {
|
||||
// Helper: replicate Execute()'s build wiring with a lark config.
|
||||
buildInternal(
|
||||
context.Background(), cmdutil.InvocationContext{},
|
||||
@@ -71,9 +95,11 @@ func TestStartupBrandReachesRegistry_RealStartupOrder(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
nonce := uuid.NewString()
|
||||
t.Setenv(startupBrandHelperEnv, nonce)
|
||||
cmd := exec.Command(os.Args[0], "-test.run", "TestStartupBrandReachesRegistry_RealStartupOrder")
|
||||
cmd.Args = append(cmd.Args, "-startup-brand-helper="+nonce)
|
||||
cmd.Env = append(os.Environ(),
|
||||
"GO_TEST_STARTUP_BRAND_HELPER=1",
|
||||
"LARKSUITE_CLI_CONFIG_DIR="+tmp,
|
||||
"LARKSUITE_CLI_REMOTE_META=off", // no network during the subprocess build
|
||||
)
|
||||
@@ -85,3 +111,33 @@ func TestStartupBrandReachesRegistry_RealStartupOrder(t *testing.T) {
|
||||
t.Errorf("registry brand after real startup order = %s, want lark", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupBrandHelperRequiresMatchingCommandNonce(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
envNonce string
|
||||
argNonce string
|
||||
want bool
|
||||
}{
|
||||
{name: "neither set"},
|
||||
{name: "ambient environment only", envNonce: "ambient"},
|
||||
{name: "command argument only", argNonce: "command"},
|
||||
{name: "mismatch", envNonce: "ambient", argNonce: "command"},
|
||||
{name: "matching", envNonce: "nonce", argNonce: "nonce", want: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := startupBrandHelperEnabled(tt.envNonce, tt.argNonce); got != tt.want {
|
||||
t.Fatalf("startupBrandHelperEnabled() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupBrandHelperNonce(t *testing.T) {
|
||||
if got := startupBrandHelperNonce([]string{"test", "-test.run", "brand"}); got != "" {
|
||||
t.Fatalf("startupBrandHelperNonce() = %q, want empty", got)
|
||||
}
|
||||
if got := startupBrandHelperNonce([]string{"test", "-startup-brand-helper=nonce"}); got != "nonce" {
|
||||
t.Fatalf("startupBrandHelperNonce() = %q, want nonce", got)
|
||||
}
|
||||
}
|
||||
|
||||
46
cmd/testmain_test.go
Normal file
46
cmd/testmain_test.go
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/registry/registrytest"
|
||||
)
|
||||
|
||||
// TestMain isolates command-tree tests from the host machine: config (and the
|
||||
// registry cache under it) is redirected to a temp dir, then the registry is
|
||||
// seeded from the tracked fixture and initialized eagerly. Tests pass on a
|
||||
// clean checkout with no network, no `make fetch_meta`, and no user cache.
|
||||
//
|
||||
// Note: os.Exit skips deferred functions, so cleanup runs explicitly after
|
||||
// m.Run before exiting.
|
||||
func TestMain(m *testing.M) {
|
||||
if isStartupBrandHelper() {
|
||||
// Re-exec helper subprocess (startup_brand_test.go): the parent test
|
||||
// already provides an isolated config dir and disables remote metadata,
|
||||
// and the helper must own the first registry Init to prove the startup
|
||||
// order — do not seed or eagerly initialize here.
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
root, err := os.MkdirTemp("", "lark-cli-cmd-test-*")
|
||||
if err != nil {
|
||||
println("cmd test setup: MkdirTemp failed:", err.Error())
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", root); err != nil {
|
||||
println("cmd test setup: Setenv failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := registrytest.Seed(root); err != nil {
|
||||
println("cmd test setup: registrytest.Seed failed:", err.Error())
|
||||
os.RemoveAll(root)
|
||||
os.Exit(2)
|
||||
}
|
||||
code := m.Run()
|
||||
os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
23
cmd/update/testmain_test.go
Normal file
23
cmd/update/testmain_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdupdate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-update-test-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", filepath.Join(root, "config")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -24,6 +24,8 @@ import (
|
||||
"github.com/larksuite/cli/internal/skillscheck"
|
||||
)
|
||||
|
||||
const runLiveSkillsTestsEnv = "LARKSUITE_CLI_RUN_LIVE_SKILLS_TESTS"
|
||||
|
||||
// newTestFactory creates a test factory with minimal config.
|
||||
func newTestFactory(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
@@ -31,13 +33,17 @@ func newTestFactory(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffe
|
||||
return f, stdout, stderr
|
||||
}
|
||||
|
||||
// mockDetect sets up newUpdater to return an Updater with the given DetectResult.
|
||||
// mockDetect sets up newUpdater to return an Updater with the given DetectResult
|
||||
// and fully mocked skills operations. Tests that only care about install-method
|
||||
// detection must never fall through to the real npx skills CLI.
|
||||
func mockDetect(t *testing.T, result selfupdate.DetectResult) {
|
||||
t.Helper()
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult { return result }
|
||||
u.SkillsIndexFetchOverride = successfulSkillsIndexFetch()
|
||||
u.SkillsCommandOverride = successfulSkillsCommand()
|
||||
return u
|
||||
}
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
@@ -104,6 +110,18 @@ func successfulSkillsCommand() func(args ...string) *selfupdate.NpmResult {
|
||||
}
|
||||
}
|
||||
|
||||
func mockSkillsSync(t *testing.T) {
|
||||
t.Helper()
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.SkillsIndexFetchOverride = successfulSkillsIndexFetch()
|
||||
u.SkillsCommandOverride = successfulSkillsCommand()
|
||||
return u
|
||||
}
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
}
|
||||
|
||||
func TestUpdatePnpm_JSON(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
@@ -228,6 +246,9 @@ func TestNormalizeVersion(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUpdateAlreadyUpToDate_JSON(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
mockSkillsSync(t)
|
||||
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
|
||||
cmd := NewCmdUpdate(f)
|
||||
@@ -256,6 +277,9 @@ func TestUpdateAlreadyUpToDate_JSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUpdateAlreadyUpToDate_Human(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
mockSkillsSync(t)
|
||||
|
||||
f, _, stderr := newTestFactory(t)
|
||||
|
||||
cmd := NewCmdUpdate(f)
|
||||
@@ -281,6 +305,7 @@ func TestUpdateAlreadyUpToDate_Human(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUpdateManual_JSON(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
@@ -312,6 +337,7 @@ func TestUpdateManual_JSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUpdateManual_Human(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
@@ -1161,6 +1187,7 @@ func TestRunSkillsAndState_DedupForceBypass(t *testing.T) {
|
||||
}
|
||||
called := false
|
||||
updater := &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: successfulSkillsIndexFetch(),
|
||||
SkillsCommandOverride: func(args ...string) *selfupdate.NpmResult {
|
||||
called = true
|
||||
return successfulSkillsCommand()(args...)
|
||||
@@ -1177,7 +1204,10 @@ func TestRunSkillsAndState_DedupForceBypass(t *testing.T) {
|
||||
|
||||
func TestRunSkillsAndState_SuccessWritesState(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
updater := &selfupdate.Updater{SkillsCommandOverride: successfulSkillsCommand()}
|
||||
updater := &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: successfulSkillsIndexFetch(),
|
||||
SkillsCommandOverride: successfulSkillsCommand(),
|
||||
}
|
||||
got := runSkillsAndState(updater, newTestIO(), "1.0.21", false)
|
||||
if got == nil || got.Err != nil {
|
||||
t.Fatalf("runSkillsAndState() = %+v, want non-nil with nil Err", got)
|
||||
@@ -1197,6 +1227,7 @@ func TestRunSkillsAndState_FailureKeepsOldState(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updater := &selfupdate.Updater{
|
||||
SkillsIndexFetchOverride: successfulSkillsIndexFetch(),
|
||||
SkillsCommandOverride: func(args ...string) *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Err = fmt.Errorf("npx failed")
|
||||
@@ -1513,28 +1544,133 @@ func TestEmitSkillsTextHints_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCommand_RealSkillsSyncRewritesState is a live integration test that
|
||||
// verifies "lark-cli update" correctly triggers skills sync and rewrites the
|
||||
// state file. It calls the real npx skills CLI, so the test is skipped when
|
||||
// npx or the skills registry is unavailable (e.g. no network or fork PRs).
|
||||
func TestUpdateCommand_RealSkillsSyncRewritesState(t *testing.T) {
|
||||
// Phase 1: Verify the real npx skills CLI is available; skip otherwise.
|
||||
if _, err := exec.LookPath("npx"); err != nil {
|
||||
t.Skipf("npx not found in PATH: %v", err)
|
||||
// liveSkillsIsolationEnv is the single source of truth for the user-state
|
||||
// directories a live skills test must redirect under the temporary home. It
|
||||
// covers the CLI's own config, the agent homes the skills CLI installs into,
|
||||
// the XDG dirs it derives paths from (XDG_STATE_HOME holds its global
|
||||
// .skill-lock.json), and the npm/npx overrides that take precedence over
|
||||
// HOME-derived defaults (both cases: npm reads npm_config_* case-insensitively).
|
||||
func liveSkillsIsolationEnv(home string) map[string]string {
|
||||
return map[string]string{
|
||||
"HOME": home,
|
||||
"USERPROFILE": home,
|
||||
"APPDATA": filepath.Join(home, "AppData", "Roaming"),
|
||||
"LOCALAPPDATA": filepath.Join(home, "AppData", "Local"),
|
||||
"XDG_CONFIG_HOME": filepath.Join(home, ".config"),
|
||||
"XDG_DATA_HOME": filepath.Join(home, ".local", "share"),
|
||||
"XDG_STATE_HOME": filepath.Join(home, ".local", "state"),
|
||||
"CODEX_HOME": filepath.Join(home, ".codex"),
|
||||
"CLAUDE_CONFIG_DIR": filepath.Join(home, ".claude"),
|
||||
"LARKSUITE_CLI_CONFIG_DIR": filepath.Join(home, ".lark-cli"),
|
||||
"npm_config_cache": filepath.Join(home, ".npm-cache"),
|
||||
"NPM_CONFIG_CACHE": filepath.Join(home, ".npm-cache"),
|
||||
"npm_config_prefix": filepath.Join(home, ".npm-global"),
|
||||
"NPM_CONFIG_PREFIX": filepath.Join(home, ".npm-global"),
|
||||
"npm_config_userconfig": filepath.Join(home, ".npmrc"),
|
||||
"NPM_CONFIG_USERCONFIG": filepath.Join(home, ".npmrc"),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
}
|
||||
|
||||
func prepareLiveSkillsIntegration(t *testing.T) string {
|
||||
t.Helper()
|
||||
if os.Getenv(runLiveSkillsTestsEnv) != "1" {
|
||||
t.Skipf("live skills integration test disabled; set %s=1 to run", runLiveSkillsTestsEnv)
|
||||
}
|
||||
|
||||
home := t.TempDir()
|
||||
for key, value := range liveSkillsIsolationEnv(home) {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
return home
|
||||
}
|
||||
|
||||
func TestPrepareLiveSkillsIntegration(t *testing.T) {
|
||||
reachedAfterGate := false
|
||||
t.Run("requires explicit opt-in", func(t *testing.T) {
|
||||
t.Setenv(runLiveSkillsTestsEnv, "")
|
||||
prepareLiveSkillsIntegration(t)
|
||||
reachedAfterGate = true
|
||||
})
|
||||
if reachedAfterGate {
|
||||
t.Fatal("prepareLiveSkillsIntegration continued without explicit opt-in")
|
||||
}
|
||||
|
||||
t.Run("isolates user directories", func(t *testing.T) {
|
||||
t.Setenv(runLiveSkillsTestsEnv, "1")
|
||||
home := prepareLiveSkillsIntegration(t)
|
||||
// Pin the isolation contract by key: removing a variable from
|
||||
// liveSkillsIsolationEnv must fail this list, and every redirected
|
||||
// value must live under the temporary home.
|
||||
required := []string{
|
||||
"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA",
|
||||
"XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME",
|
||||
"CODEX_HOME", "CLAUDE_CONFIG_DIR", "LARKSUITE_CLI_CONFIG_DIR",
|
||||
"npm_config_cache", "NPM_CONFIG_CACHE",
|
||||
"npm_config_prefix", "NPM_CONFIG_PREFIX",
|
||||
"npm_config_userconfig", "NPM_CONFIG_USERCONFIG",
|
||||
}
|
||||
env := liveSkillsIsolationEnv(home)
|
||||
for _, key := range required {
|
||||
expected, ok := env[key]
|
||||
if !ok {
|
||||
t.Errorf("liveSkillsIsolationEnv dropped required key %s", key)
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(expected, home) {
|
||||
t.Errorf("%s = %q escapes temporary home %q", key, expected, home)
|
||||
}
|
||||
if got := os.Getenv(key); got != expected {
|
||||
t.Errorf("%s = %q, want %q", key, got, expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// seedLiveSkillsGlobal verifies the real npx skills CLI is reachable, installs
|
||||
// lark-calendar into the isolated global skills dir, and returns the parsed
|
||||
// global skills list. The caller opted in explicitly, so every missing
|
||||
// precondition is a hard failure — skipping would report "nothing verified"
|
||||
// as a green run.
|
||||
func seedLiveSkillsGlobal(t *testing.T) []string {
|
||||
t.Helper()
|
||||
if _, err := exec.LookPath("npx"); err != nil {
|
||||
t.Fatalf("live skills tests opted in but npx not found in PATH: %v", err)
|
||||
}
|
||||
// Three sequential npx runs against a cold cache (the isolated home starts
|
||||
// empty) can be slow; with Fatal-on-timeout semantics the budget errs on
|
||||
// the generous side.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
if err := exec.CommandContext(ctx, "npx", "-y", "skills", "add", "https://open.feishu.cn", "--list").Run(); err != nil {
|
||||
t.Skipf("real skills CLI unavailable: %v", err)
|
||||
t.Fatalf("live skills tests opted in but real skills CLI unavailable: %v", err)
|
||||
}
|
||||
if err := exec.CommandContext(ctx, "npx", "-y", "skills", "add", "https://open.feishu.cn", "-s", "lark-calendar", "-g", "-y").Run(); err != nil {
|
||||
t.Fatalf("failed to seed isolated global skills: %v", err)
|
||||
}
|
||||
globalOut, err := exec.CommandContext(ctx, "npx", "-y", "skills", "ls", "-g").Output()
|
||||
if err != nil {
|
||||
t.Skipf("real global skills CLI unavailable: %v", err)
|
||||
t.Fatalf("real global skills CLI unavailable: %v", err)
|
||||
}
|
||||
localSkills := skillscheck.ParseSkillsList(string(globalOut))
|
||||
if err := ctx.Err(); err != nil {
|
||||
t.Skipf("real skills CLI availability check timed out: %v", err)
|
||||
if len(localSkills) == 0 {
|
||||
t.Fatal("seeded lark-calendar but global skills list is empty")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
t.Fatalf("real skills CLI availability check timed out: %v", err)
|
||||
}
|
||||
return localSkills
|
||||
}
|
||||
|
||||
// TestUpdateCommand_RealSkillsSyncRewritesState is a live integration test that
|
||||
// verifies "lark-cli update" correctly triggers skills sync and rewrites the
|
||||
// state file. It calls the real npx skills CLI and only runs with explicit
|
||||
// opt-in. All user directories are redirected to a temporary home.
|
||||
func TestUpdateCommand_RealSkillsSyncRewritesState(t *testing.T) {
|
||||
prepareLiveSkillsIntegration(t)
|
||||
|
||||
// Phase 1: Verify the real npx skills CLI is available and seed the
|
||||
// isolated global skills install.
|
||||
localSkills := seedLiveSkillsGlobal(t)
|
||||
|
||||
// Phase 2: Seed a previous sync state simulating an upgrade from v1.0.19.
|
||||
// lark-doc and lark-mail are recorded as skipped/deleted, meaning the user
|
||||
@@ -1630,26 +1766,17 @@ func TestUpdateCommand_RealSkillsSyncRewritesState(t *testing.T) {
|
||||
// not exist (cold start), the update command installs all official skills and
|
||||
// writes a fresh state file. No skill should appear in SkippedDeletedSkills
|
||||
// because there is no previous state to preserve user deletions from.
|
||||
// This is a live integration test that calls the real npx skills CLI; it is
|
||||
// skipped when npx or the skills registry is unavailable.
|
||||
// This is a live integration test that calls the real npx skills CLI and only
|
||||
// runs with explicit opt-in. All user directories are redirected to a temporary
|
||||
// home.
|
||||
func TestUpdateCommand_SkillsSyncColdStart(t *testing.T) {
|
||||
// Phase 1: Verify the real npx skills CLI is available; skip otherwise.
|
||||
if _, err := exec.LookPath("npx"); err != nil {
|
||||
t.Skipf("npx not found in PATH: %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
if err := exec.CommandContext(ctx, "npx", "-y", "skills", "add", "https://open.feishu.cn", "--list").Run(); err != nil {
|
||||
t.Skipf("real skills CLI unavailable: %v", err)
|
||||
}
|
||||
globalOut, err := exec.CommandContext(ctx, "npx", "-y", "skills", "ls", "-g").Output()
|
||||
if err != nil {
|
||||
t.Skipf("real global skills CLI unavailable: %v", err)
|
||||
}
|
||||
localSkills := skillscheck.ParseSkillsList(string(globalOut))
|
||||
if err := ctx.Err(); err != nil {
|
||||
t.Skipf("real skills CLI availability check timed out: %v", err)
|
||||
}
|
||||
prepareLiveSkillsIntegration(t)
|
||||
|
||||
// Phase 1: Verify the real npx skills CLI is available and seed one known
|
||||
// official skill into the isolated global install. Cold start means no
|
||||
// skills-state.json — locally installed skills may still exist, and seeding
|
||||
// one keeps the Phase 4 per-skill assertions from running zero times.
|
||||
localSkills := seedLiveSkillsGlobal(t)
|
||||
|
||||
// Phase 2: Use an isolated config dir with no pre-existing skills-state.json.
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
|
||||
107
events/application/menu.go
Normal file
107
events/application/menu.go
Normal file
@@ -0,0 +1,107 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/internal/event"
|
||||
)
|
||||
|
||||
// BotMenuOutput is the flattened shape for application.bot.menu_v6.
|
||||
type BotMenuOutput struct {
|
||||
Type string `json:"type" desc:"Event type; always application.bot.menu_v6"`
|
||||
EventID string `json:"event_id,omitempty" desc:"Globally unique event ID; safe for deduplication"`
|
||||
Timestamp string `json:"timestamp,omitempty" desc:"Event delivery time (ms timestamp string); prefers header.create_time" kind:"timestamp_ms"`
|
||||
AppID string `json:"app_id,omitempty" desc:"Application ID from the event header"`
|
||||
TenantKey string `json:"tenant_key,omitempty" desc:"Tenant key from the event header"`
|
||||
EventKey string `json:"event_key,omitempty" desc:"Developer-defined bot menu event key"`
|
||||
MenuTimestamp string `json:"menu_timestamp,omitempty" desc:"Menu click timestamp from the event body" kind:"timestamp_ms"`
|
||||
OperatorID string `json:"operator_id,omitempty" desc:"Operator open_id; kept as a short alias of operator_open_id" kind:"open_id"`
|
||||
OperatorOpenID string `json:"operator_open_id,omitempty" desc:"Operator open_id" kind:"open_id"`
|
||||
OperatorUnionID string `json:"operator_union_id,omitempty" desc:"Operator union_id" kind:"union_id"`
|
||||
OperatorUserID string `json:"operator_user_id,omitempty" desc:"Operator user_id" kind:"user_id"`
|
||||
OperatorName string `json:"operator_name,omitempty" desc:"Operator display name"`
|
||||
}
|
||||
|
||||
func processBotMenu(_ context.Context, _ event.APIClient, raw *event.RawEvent, _ map[string]string) (json.RawMessage, error) {
|
||||
var envelope struct {
|
||||
Header struct {
|
||||
EventID string `json:"event_id"`
|
||||
EventType string `json:"event_type"`
|
||||
CreateTime string `json:"create_time"`
|
||||
AppID string `json:"app_id"`
|
||||
TenantKey string `json:"tenant_key"`
|
||||
} `json:"header"`
|
||||
Event struct {
|
||||
EventKey string `json:"event_key"`
|
||||
Timestamp json.RawMessage `json:"timestamp"`
|
||||
Operator struct {
|
||||
OperatorID struct {
|
||||
OpenID string `json:"open_id"`
|
||||
UnionID string `json:"union_id"`
|
||||
UserID string `json:"user_id"`
|
||||
} `json:"operator_id"`
|
||||
OperatorName string `json:"operator_name"`
|
||||
} `json:"operator"`
|
||||
} `json:"event"`
|
||||
}
|
||||
if err := json.Unmarshal(raw.Payload, &envelope); err != nil {
|
||||
return raw.Payload, nil //nolint:nilerr // passthrough on malformed payload so consumers still see the event
|
||||
}
|
||||
|
||||
menuTimestamp := timestampMillisString(envelope.Event.Timestamp)
|
||||
timestamp := envelope.Header.CreateTime
|
||||
if timestamp == "" {
|
||||
timestamp = menuTimestamp
|
||||
}
|
||||
operatorID := envelope.Event.Operator.OperatorID.OpenID
|
||||
|
||||
out := &BotMenuOutput{
|
||||
Type: eventTypeBotMenuV6,
|
||||
EventID: envelope.Header.EventID,
|
||||
Timestamp: timestamp,
|
||||
AppID: envelope.Header.AppID,
|
||||
TenantKey: envelope.Header.TenantKey,
|
||||
EventKey: envelope.Event.EventKey,
|
||||
MenuTimestamp: menuTimestamp,
|
||||
OperatorID: operatorID,
|
||||
OperatorOpenID: operatorID,
|
||||
OperatorUnionID: envelope.Event.Operator.OperatorID.UnionID,
|
||||
OperatorUserID: envelope.Event.Operator.OperatorID.UserID,
|
||||
OperatorName: envelope.Event.Operator.OperatorName,
|
||||
}
|
||||
return json.Marshal(out)
|
||||
}
|
||||
|
||||
func rawScalarString(raw json.RawMessage) string {
|
||||
s := strings.TrimSpace(string(raw))
|
||||
if s == "" || s == "null" {
|
||||
return ""
|
||||
}
|
||||
var text string
|
||||
if err := json.Unmarshal(raw, &text); err == nil {
|
||||
return text
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func timestampMillisString(raw json.RawMessage) string {
|
||||
s := rawScalarString(raw)
|
||||
if len(s) == 10 && allDigits(s) {
|
||||
return s + "000"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func allDigits(s string) bool {
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return s != ""
|
||||
}
|
||||
227
events/application/menu_test.go
Normal file
227
events/application/menu_test.go
Normal file
@@ -0,0 +1,227 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/event"
|
||||
)
|
||||
|
||||
func TestKeysBotMenuMetadata(t *testing.T) {
|
||||
keys := Keys()
|
||||
if len(keys) != 1 {
|
||||
t.Fatalf("len(Keys()) = %d, want 1", len(keys))
|
||||
}
|
||||
|
||||
def := keys[0]
|
||||
if def.Key != eventTypeBotMenuV6 {
|
||||
t.Errorf("Key = %q, want %q", def.Key, eventTypeBotMenuV6)
|
||||
}
|
||||
if def.EventType != eventTypeBotMenuV6 {
|
||||
t.Errorf("EventType = %q, want %q", def.EventType, eventTypeBotMenuV6)
|
||||
}
|
||||
if def.SubscriptionType != "" {
|
||||
t.Errorf("SubscriptionType = %q, want default event subscription", def.SubscriptionType)
|
||||
}
|
||||
if def.Schema.Custom == nil {
|
||||
t.Fatal("Schema.Custom is nil")
|
||||
}
|
||||
if def.Schema.Custom.Type != reflect.TypeOf(BotMenuOutput{}) {
|
||||
t.Errorf("custom type = %v, want BotMenuOutput", def.Schema.Custom.Type)
|
||||
}
|
||||
if def.Schema.Native != nil {
|
||||
t.Fatal("Schema.Native must be nil for processed output")
|
||||
}
|
||||
if def.Process == nil {
|
||||
t.Fatal("Process is nil")
|
||||
}
|
||||
if !reflect.DeepEqual(def.AuthTypes, []string{"bot"}) {
|
||||
t.Errorf("AuthTypes = %#v", def.AuthTypes)
|
||||
}
|
||||
if !reflect.DeepEqual(def.RequiredConsoleEvents, []string{eventTypeBotMenuV6}) {
|
||||
t.Errorf("RequiredConsoleEvents = %#v", def.RequiredConsoleEvents)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBotMenuRegistersCleanly(t *testing.T) {
|
||||
const key = eventTypeBotMenuV6
|
||||
event.UnregisterKeyForTest(key)
|
||||
t.Cleanup(func() { event.UnregisterKeyForTest(key) })
|
||||
|
||||
for _, def := range Keys() {
|
||||
event.RegisterKey(def)
|
||||
}
|
||||
if _, ok := event.Lookup(key); !ok {
|
||||
t.Fatalf("event.Lookup(%q) not registered", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessBotMenu(t *testing.T) {
|
||||
payload := `{
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
"event_id": "ev_menu_001",
|
||||
"event_type": "application.bot.menu_v6",
|
||||
"create_time": "1776409469273",
|
||||
"app_id": "cli_test",
|
||||
"tenant_key": "tenant_test"
|
||||
},
|
||||
"event": {
|
||||
"event_key": "start_eval",
|
||||
"timestamp": 1776409469000,
|
||||
"operator": {
|
||||
"operator_id": {
|
||||
"open_id": "ou_operator",
|
||||
"union_id": "on_operator",
|
||||
"user_id": "user_operator"
|
||||
},
|
||||
"operator_name": "Test User"
|
||||
}
|
||||
}
|
||||
}`
|
||||
out := runBotMenu(t, payload)
|
||||
|
||||
if out.Type != eventTypeBotMenuV6 {
|
||||
t.Errorf("Type = %q, want %q", out.Type, eventTypeBotMenuV6)
|
||||
}
|
||||
if out.EventID != "ev_menu_001" {
|
||||
t.Errorf("EventID = %q", out.EventID)
|
||||
}
|
||||
if out.Timestamp != "1776409469273" {
|
||||
t.Errorf("Timestamp = %q", out.Timestamp)
|
||||
}
|
||||
if out.EventKey != "start_eval" {
|
||||
t.Errorf("EventKey = %q", out.EventKey)
|
||||
}
|
||||
if out.MenuTimestamp != "1776409469000" {
|
||||
t.Errorf("MenuTimestamp = %q", out.MenuTimestamp)
|
||||
}
|
||||
if out.OperatorID != "ou_operator" || out.OperatorOpenID != "ou_operator" {
|
||||
t.Errorf("OperatorID/OperatorOpenID = %q/%q", out.OperatorID, out.OperatorOpenID)
|
||||
}
|
||||
if out.OperatorUnionID != "on_operator" {
|
||||
t.Errorf("OperatorUnionID = %q", out.OperatorUnionID)
|
||||
}
|
||||
if out.OperatorUserID != "user_operator" {
|
||||
t.Errorf("OperatorUserID = %q", out.OperatorUserID)
|
||||
}
|
||||
if out.OperatorName != "Test User" {
|
||||
t.Errorf("OperatorName = %q", out.OperatorName)
|
||||
}
|
||||
if out.AppID != "cli_test" || out.TenantKey != "tenant_test" {
|
||||
t.Errorf("AppID/TenantKey = %q/%q", out.AppID, out.TenantKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessBotMenuStringTimestampFallback(t *testing.T) {
|
||||
payload := `{
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
"event_id": "ev_menu_002",
|
||||
"event_type": "application.bot.menu_v6"
|
||||
},
|
||||
"event": {
|
||||
"event_key": "start_eval",
|
||||
"timestamp": "1776409469001",
|
||||
"operator": {
|
||||
"operator_id": {"open_id": "ou_operator"}
|
||||
}
|
||||
}
|
||||
}`
|
||||
out := runBotMenu(t, payload)
|
||||
|
||||
if out.Timestamp != "1776409469001" {
|
||||
t.Errorf("Timestamp fallback = %q", out.Timestamp)
|
||||
}
|
||||
if out.MenuTimestamp != "1776409469001" {
|
||||
t.Errorf("MenuTimestamp = %q", out.MenuTimestamp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessBotMenuSecondsTimestampFallback(t *testing.T) {
|
||||
payload := `{
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
"event_id": "ev_menu_seconds",
|
||||
"event_type": "application.bot.menu_v6"
|
||||
},
|
||||
"event": {
|
||||
"event_key": "start_eval",
|
||||
"timestamp": 1694592375,
|
||||
"operator": {
|
||||
"operator_id": {"open_id": "ou_operator"}
|
||||
}
|
||||
}
|
||||
}`
|
||||
out := runBotMenu(t, payload)
|
||||
|
||||
if out.Timestamp != "1694592375000" {
|
||||
t.Errorf("Timestamp fallback = %q, want seconds normalized to milliseconds", out.Timestamp)
|
||||
}
|
||||
if out.MenuTimestamp != "1694592375000" {
|
||||
t.Errorf("MenuTimestamp = %q, want seconds normalized to milliseconds", out.MenuTimestamp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessBotMenuTypeUsesLocalConstant(t *testing.T) {
|
||||
payload := `{
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
"event_id": "ev_menu_003",
|
||||
"event_type": "unexpected.event_type",
|
||||
"create_time": "1776409469275"
|
||||
},
|
||||
"event": {
|
||||
"event_key": "start_eval",
|
||||
"operator": {
|
||||
"operator_id": {"open_id": "ou_operator"}
|
||||
}
|
||||
}
|
||||
}`
|
||||
out := runBotMenu(t, payload)
|
||||
|
||||
if out.Type != eventTypeBotMenuV6 {
|
||||
t.Errorf("Type = %q, want %q", out.Type, eventTypeBotMenuV6)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessBotMenuMalformedPayload(t *testing.T) {
|
||||
raw := &event.RawEvent{
|
||||
EventID: "ev_bad",
|
||||
EventType: eventTypeBotMenuV6,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
got, err := processBotMenu(context.Background(), nil, raw, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Process should swallow parse errors, got %v", err)
|
||||
}
|
||||
if string(got) != "not json" {
|
||||
t.Errorf("malformed fallback output = %q, want original bytes", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func runBotMenu(t *testing.T, payload string) BotMenuOutput {
|
||||
t.Helper()
|
||||
raw := &event.RawEvent{
|
||||
EventID: "ev_test",
|
||||
EventType: eventTypeBotMenuV6,
|
||||
Payload: json.RawMessage(payload),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
got, err := processBotMenu(context.Background(), nil, raw, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("processBotMenu: %v", err)
|
||||
}
|
||||
var out BotMenuOutput
|
||||
if err := json.Unmarshal(got, &out); err != nil {
|
||||
t.Fatalf("unmarshal output: %v\n%s", err, got)
|
||||
}
|
||||
return out
|
||||
}
|
||||
31
events/application/register.go
Normal file
31
events/application/register.go
Normal file
@@ -0,0 +1,31 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package application registers Application-domain EventKeys.
|
||||
package application
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/larksuite/cli/internal/event"
|
||||
)
|
||||
|
||||
const eventTypeBotMenuV6 = "application.bot.menu_v6"
|
||||
|
||||
// Keys returns all Application-domain EventKey definitions.
|
||||
func Keys() []event.KeyDefinition {
|
||||
return []event.KeyDefinition{
|
||||
{
|
||||
Key: eventTypeBotMenuV6,
|
||||
DisplayName: "Bot menu",
|
||||
Description: "Triggered when a user clicks a custom bot menu item whose action is configured as a push event.",
|
||||
EventType: eventTypeBotMenuV6,
|
||||
Schema: event.SchemaDef{
|
||||
Custom: &event.SchemaSpec{Type: reflect.TypeOf(BotMenuOutput{})},
|
||||
},
|
||||
Process: processBotMenu,
|
||||
AuthTypes: []string{"bot"},
|
||||
RequiredConsoleEvents: []string{eventTypeBotMenuV6},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"github.com/larksuite/cli/events/application"
|
||||
"github.com/larksuite/cli/events/approval"
|
||||
"github.com/larksuite/cli/events/im"
|
||||
"github.com/larksuite/cli/events/minutes"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
// Mail is intentionally omitted in this phase.
|
||||
func init() {
|
||||
all := [][]event.KeyDefinition{
|
||||
application.Keys(),
|
||||
approval.Keys(),
|
||||
im.Keys(),
|
||||
minutes.Keys(),
|
||||
|
||||
23
internal/auth/testmain_test.go
Normal file
23
internal/auth/testmain_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-internal-auth-test-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_LOG_DIR", filepath.Join(root, "logs")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -132,16 +132,14 @@ func HandleResponse(resp *larkcore.ApiResp, opts ResponseOptions) error {
|
||||
})
|
||||
}
|
||||
|
||||
// Content safety scanning for non-JSON presentation formats.
|
||||
scanResult := output.ScanForSafety(opts.CommandPath, result, opts.ErrOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
output.WriteAlertWarning(opts.ErrOut, scanResult.Alert)
|
||||
}
|
||||
output.FormatValue(opts.Out, result, opts.Format)
|
||||
return nil
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: opts.Out,
|
||||
ErrOut: opts.ErrOut,
|
||||
CommandPath: opts.CommandPath,
|
||||
Identity: string(identity),
|
||||
NoticeProvider: output.GetNotice,
|
||||
})
|
||||
return emitter.Success(result, output.EmitOptions{Format: opts.Format.String()})
|
||||
}
|
||||
|
||||
// Non-JSON (binary) responses.
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/vfs/localfileio"
|
||||
)
|
||||
@@ -239,6 +240,87 @@ func TestHandleResponse_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleResponse_NonJSONFormatsEmitExactStructuredResponseBytes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
format output.Format
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "ndjson",
|
||||
format: output.FormatNDJSON,
|
||||
want: "{\"id\":\"1\",\"name\":\"Alice\"}\n{\"id\":\"2\",\"name\":\"Bob\"}\n",
|
||||
},
|
||||
{
|
||||
name: "table",
|
||||
format: output.FormatTable,
|
||||
want: "id name \n── ─────\n1 Alice\n2 Bob \n",
|
||||
},
|
||||
{
|
||||
name: "csv",
|
||||
format: output.FormatCSV,
|
||||
want: "id,name\n1,Alice\n2,Bob\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
reg := &httpmock.Registry{}
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: http.MethodGet,
|
||||
URL: "/open-apis/test/v1/items",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"id": "1", "name": "Alice"},
|
||||
map[string]interface{}{"id": "2", "name": "Bob"},
|
||||
},
|
||||
"has_more": false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
httpResp, err := httpmock.NewClient(reg).Get("https://open.feishu.cn/open-apis/test/v1/items")
|
||||
if err != nil {
|
||||
t.Fatalf("fixture request failed: %v", err)
|
||||
}
|
||||
body, err := io.ReadAll(httpResp.Body)
|
||||
_ = httpResp.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read fixture response: %v", err)
|
||||
}
|
||||
resp := &larkcore.ApiResp{
|
||||
StatusCode: httpResp.StatusCode,
|
||||
Header: httpResp.Header.Clone(),
|
||||
RawBody: body,
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
var errOut bytes.Buffer
|
||||
err = HandleResponse(resp, ResponseOptions{
|
||||
Format: tt.format,
|
||||
Identity: core.AsBot,
|
||||
Out: &out,
|
||||
ErrOut: &errOut,
|
||||
CommandPath: "lark-cli api GET",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("HandleResponse() error = %v, want nil", err)
|
||||
}
|
||||
if got := out.String(); got != tt.want {
|
||||
t.Fatalf("stdout byte mismatch\ngot (%d bytes):\n%q\nwant (%d bytes):\n%q", len(got), got, len(tt.want), tt.want)
|
||||
}
|
||||
if got := errOut.String(); got != "" {
|
||||
t.Fatalf("stderr bytes = %q, want empty", got)
|
||||
}
|
||||
reg.Verify(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleResponse_JSONWithJqUsesSuccessEnvelope(t *testing.T) {
|
||||
body := []byte(`{"code":0,"msg":"ok","data":{"id":"1"}}`)
|
||||
resp := newApiResp(body, map[string]string{"Content-Type": "application/json"})
|
||||
|
||||
30
internal/cmdutil/testmain_test.go
Normal file
30
internal/cmdutil/testmain_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Default-factory tests initialize the registry and resolve config. Keep
|
||||
// them deterministic: never read the developer's real ~/.lark-cli and
|
||||
// prevent background remote-metadata refreshes from touching user state.
|
||||
root, err := os.MkdirTemp("", "lark-cli-cmdutil-test-*")
|
||||
if err != nil {
|
||||
println("internal/cmdutil test setup: MkdirTemp failed:", err.Error())
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", filepath.Join(root, "config")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_REMOTE_META", "off"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
23
internal/event/testmain_test.go
Normal file
23
internal/event/testmain_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package event
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-event-test-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", filepath.Join(root, "config")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
28
internal/keychain/testmain_test.go
Normal file
28
internal/keychain/testmain_test.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package keychain
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-keychain-test-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
for key, value := range map[string]string{
|
||||
"LARKSUITE_CLI_DATA_DIR": filepath.Join(root, "data"),
|
||||
"LARKSUITE_CLI_LOG_DIR": filepath.Join(root, "logs"),
|
||||
} {
|
||||
if err := os.Setenv(key, value); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -7,70 +7,91 @@ import (
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// FormatAsCSV formats data as CSV (with header) and writes it to w.
|
||||
func FormatAsCSV(w io.Writer, data interface{}) {
|
||||
FormatAsCSVPaginated(w, data, true)
|
||||
// Match the other legacy wrappers: surface only a marshal failure (as the
|
||||
// JSON fallback historically did); plain write failures stay swallowed.
|
||||
if err := WriteCSV(w, data); isOutputMarshalError(err) {
|
||||
legacyStderrf("json marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteCSV formats data as CSV and returns marshal or write errors.
|
||||
func WriteCSV(w io.Writer, data interface{}) error {
|
||||
return WriteCSVPaginated(w, data, true)
|
||||
}
|
||||
|
||||
// FormatAsCSVPaginated formats data as CSV with pagination awareness.
|
||||
// When isFirstPage is true, outputs the header row; otherwise only data rows.
|
||||
func FormatAsCSVPaginated(w io.Writer, data interface{}, isFirstPage bool) {
|
||||
if err := WriteCSVPaginated(w, data, isFirstPage); isOutputMarshalError(err) {
|
||||
legacyStderrf("json marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteCSVPaginated formats data as CSV and returns marshal or write errors.
|
||||
func WriteCSVPaginated(w io.Writer, data interface{}, isFirstPage bool) error {
|
||||
rows, cols, isList := prepareRows(data)
|
||||
if cols == nil {
|
||||
if isList {
|
||||
fmt.Fprintln(w, "(empty)")
|
||||
_, err := fmt.Fprintln(w, "(empty)")
|
||||
return err
|
||||
} else {
|
||||
PrintJson(w, data)
|
||||
return WriteJSON(w, data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
if isFirstPage {
|
||||
fmt.Fprintln(w, "(empty)")
|
||||
_, err := fmt.Fprintln(w, "(empty)")
|
||||
return err
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if !isList {
|
||||
// Single object: key,value rows
|
||||
cw := csv.NewWriter(w)
|
||||
if isFirstPage {
|
||||
cw.Write([]string{"key", "value"})
|
||||
if err := cw.Write([]string{"key", "value"}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, col := range cols {
|
||||
cw.Write([]string{col, rows[0][col]})
|
||||
if err := cw.Write([]string{col, rows[0][col]}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
flushCSV(cw)
|
||||
return
|
||||
return flushCSV(cw)
|
||||
}
|
||||
|
||||
writeCSVRows(w, rows, cols, isFirstPage)
|
||||
return writeCSVRows(w, rows, cols, isFirstPage)
|
||||
}
|
||||
|
||||
// writeCSVRows writes CSV data rows (and optionally header) using the given columns.
|
||||
func writeCSVRows(w io.Writer, rows []map[string]string, cols []string, writeHeader bool) {
|
||||
func writeCSVRows(w io.Writer, rows []map[string]string, cols []string, writeHeader bool) error {
|
||||
cw := csv.NewWriter(w)
|
||||
if writeHeader {
|
||||
cw.Write(cols)
|
||||
if err := cw.Write(cols); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, row := range rows {
|
||||
record := make([]string, len(cols))
|
||||
for i, col := range cols {
|
||||
record[i] = row[col]
|
||||
}
|
||||
cw.Write(record)
|
||||
if err := cw.Write(record); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
flushCSV(cw)
|
||||
return flushCSV(cw)
|
||||
}
|
||||
|
||||
// flushCSV flushes the csv.Writer and reports any write error to stderr.
|
||||
func flushCSV(cw *csv.Writer) {
|
||||
// flushCSV flushes the csv.Writer and returns any write error.
|
||||
func flushCSV(cw *csv.Writer) error {
|
||||
cw.Flush()
|
||||
if err := cw.Error(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "csv write error: %v\n", err)
|
||||
}
|
||||
return cw.Error()
|
||||
}
|
||||
|
||||
@@ -50,10 +50,11 @@ func wrapBlockError(alert *extcs.Alert) error {
|
||||
|
||||
// WriteAlertWarning writes a human-readable content-safety warning to w.
|
||||
// Used by non-JSON output paths (pretty, table, csv) in warn mode.
|
||||
func WriteAlertWarning(w io.Writer, alert *extcs.Alert) {
|
||||
func WriteAlertWarning(w io.Writer, alert *extcs.Alert) error {
|
||||
if alert == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintf(w, "warning: content safety alert from %s (rules: %s)\n",
|
||||
_, err := fmt.Fprintf(w, "warning: content safety alert from %s (rules: %s)\n",
|
||||
alert.Provider, strings.Join(alert.MatchedRules, ", "))
|
||||
return err
|
||||
}
|
||||
|
||||
336
internal/output/emitter.go
Normal file
336
internal/output/emitter.go
Normal file
@@ -0,0 +1,336 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package output
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
)
|
||||
|
||||
// NoticeProvider supplies the notice attached to a structured envelope.
|
||||
// The provider is captured by an Emitter so emission never reads the global
|
||||
// PendingNotice hook implicitly.
|
||||
type NoticeProvider func() map[string]interface{}
|
||||
|
||||
// PrettyRenderer writes the human-readable representation of one result.
|
||||
// colorEnabled is the terminal capability captured when the Emitter is built.
|
||||
type PrettyRenderer func(w io.Writer, colorEnabled bool) error
|
||||
|
||||
// EmitterConfig contains command-scoped dependencies. A command constructs one
|
||||
// Emitter and reuses it for its success result or streamed pages.
|
||||
type EmitterConfig struct {
|
||||
Out io.Writer
|
||||
ErrOut io.Writer
|
||||
CommandPath string
|
||||
Identity string
|
||||
ColorEnabled bool
|
||||
NoticeProvider NoticeProvider
|
||||
}
|
||||
|
||||
// EmitOptions describes one result's wire representation.
|
||||
//
|
||||
// The format contract is explicit: JSON (including the empty default) uses an
|
||||
// Envelope; pretty, table, csv, and ndjson render naked business data. JQ takes
|
||||
// precedence over Format and filters the JSON Envelope. Raw affects only JSON
|
||||
// envelope encoding and jq's complex-value encoding.
|
||||
//
|
||||
// JQSafetyWarning preserves the legacy difference between RuntimeContext.emit
|
||||
// (false) and WriteSuccessEnvelope (true) until their callers are migrated.
|
||||
type EmitOptions struct {
|
||||
Raw bool
|
||||
Meta *Meta
|
||||
Format string
|
||||
JQ string
|
||||
DryRun bool
|
||||
Pretty PrettyRenderer
|
||||
JQSafetyWarning bool
|
||||
}
|
||||
|
||||
// StreamOptions describes one streamed page's wire representation. Streaming
|
||||
// carries page items directly, so it deliberately exposes only the fields that
|
||||
// affect a single page: the format and, for pretty, its renderer. It has no
|
||||
// OK/Meta/DryRun/JQ — an ok:false envelope, metadata, dry-run, and jq all need
|
||||
// the aggregated result, which the caller's pagination layer owns before it
|
||||
// streams pages.
|
||||
type StreamOptions struct {
|
||||
Format string
|
||||
Pretty PrettyRenderer
|
||||
}
|
||||
|
||||
// Emitter owns all command-scoped output dependencies and pagination state.
|
||||
// It deliberately has no dependency on client or cmdutil.
|
||||
type Emitter struct {
|
||||
out io.Writer
|
||||
errOut io.Writer
|
||||
commandPath string
|
||||
identity string
|
||||
colorEnabled bool
|
||||
noticeProvider NoticeProvider
|
||||
|
||||
streamFormat string
|
||||
streamFormatter *PaginatedFormatter
|
||||
}
|
||||
|
||||
// NewEmitter constructs a command-scoped output emitter.
|
||||
func NewEmitter(config EmitterConfig) *Emitter {
|
||||
errOut := config.ErrOut
|
||||
if errOut == nil {
|
||||
errOut = io.Discard
|
||||
}
|
||||
return &Emitter{
|
||||
out: config.Out,
|
||||
errOut: errOut,
|
||||
commandPath: config.CommandPath,
|
||||
identity: config.Identity,
|
||||
colorEnabled: config.ColorEnabled,
|
||||
noticeProvider: config.NoticeProvider,
|
||||
}
|
||||
}
|
||||
|
||||
// Success scans and emits one command result by composing the package's leaf
|
||||
// primitives. JSON and jq use the standard envelope; pretty, table, csv, and
|
||||
// ndjson render the business value directly.
|
||||
func (e *Emitter) Success(data interface{}, opts EmitOptions) error {
|
||||
if err := e.requireOutput(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.JQ != "" {
|
||||
return e.emitEnvelope(data, true, opts)
|
||||
}
|
||||
|
||||
switch opts.Format {
|
||||
case "", "json":
|
||||
return e.emitEnvelope(data, true, opts)
|
||||
case "pretty":
|
||||
return e.emitPretty(data, opts)
|
||||
default:
|
||||
return e.emitFormatted(data, opts.Format)
|
||||
}
|
||||
}
|
||||
|
||||
// PartialFailure emits a multi-status result whose envelope honestly reports
|
||||
// ok:false. It is the typed counterpart to Success for batch operations where
|
||||
// some items failed but the per-item outcomes are the primary stdout output.
|
||||
// Like the legacy OutPartialFailure it produces only the JSON/jq envelope; the
|
||||
// caller owns the non-zero exit signal, keeping the Emitter free of exit
|
||||
// semantics.
|
||||
func (e *Emitter) PartialFailure(data interface{}, opts EmitOptions) error {
|
||||
if err := e.requireOutput(); err != nil {
|
||||
return err
|
||||
}
|
||||
return e.emitEnvelope(data, false, opts)
|
||||
}
|
||||
|
||||
// StreamPage scans and emits one page while retaining table/csv columns from
|
||||
// the first page. Streamed output carries page items directly, so it takes a
|
||||
// StreamOptions (format + optional pretty renderer) rather than the full
|
||||
// EmitOptions: ok/meta/dry-run/jq all need the aggregated result and are the
|
||||
// caller's pagination-layer responsibility, not a per-page concern. Excluding
|
||||
// jq from the type makes "jq requires aggregated output" a compile-time fact
|
||||
// instead of a runtime rejection.
|
||||
func (e *Emitter) StreamPage(data interface{}, opts StreamOptions) error {
|
||||
if err := e.requireOutput(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
scanResult := ScanForSafety(e.commandPath, data, e.errOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
if err := WriteAlertWarning(e.errOut, scanResult.Alert); err != nil {
|
||||
return wrapOutputError("write", err)
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Format == "pretty" {
|
||||
if opts.Pretty == nil {
|
||||
return errs.NewInternalError(errs.SubtypeUnknown,
|
||||
"pretty output requires a renderer")
|
||||
}
|
||||
return e.emit(func(w io.Writer) error {
|
||||
return opts.Pretty(w, e.colorEnabled)
|
||||
})
|
||||
}
|
||||
|
||||
format, known := ParseFormat(opts.Format)
|
||||
if !known && e.streamFormatter == nil && e.errOut != nil {
|
||||
fmt.Fprintf(e.errOut, "warning: unknown format %q, falling back to json\n", opts.Format)
|
||||
}
|
||||
if e.streamFormatter == nil {
|
||||
e.streamFormat = opts.Format
|
||||
e.streamFormatter = NewPaginatedFormatter(nil, format)
|
||||
} else if opts.Format != e.streamFormat {
|
||||
return errs.NewInternalError(errs.SubtypeUnknown,
|
||||
"stream output format changed from %q to %q", e.streamFormat, opts.Format)
|
||||
}
|
||||
|
||||
return e.emit(func(w io.Writer) error {
|
||||
e.streamFormatter.W = w
|
||||
return e.streamFormatter.WritePage(data)
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Emitter) emitEnvelope(data interface{}, ok bool, opts EmitOptions) error {
|
||||
scanResult := ScanForSafety(e.commandPath, data, e.errOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
|
||||
env := Envelope{
|
||||
OK: ok,
|
||||
Identity: e.identity,
|
||||
DryRun: opts.DryRun,
|
||||
Data: data,
|
||||
Meta: opts.Meta,
|
||||
Notice: e.notice(),
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
env.ContentSafetyAlert = scanResult.Alert
|
||||
}
|
||||
|
||||
if opts.JQ != "" {
|
||||
if scanResult.Alert != nil && opts.JQSafetyWarning {
|
||||
if err := WriteAlertWarning(e.errOut, scanResult.Alert); err != nil {
|
||||
return wrapOutputError("write", err)
|
||||
}
|
||||
}
|
||||
// Buffer the jq output manually so jq's own typed error (a validation
|
||||
// error for a bad expression, an api error for a runtime failure) is
|
||||
// returned unchanged; only a genuine stdout write failure is wrapped as
|
||||
// an internal output error.
|
||||
var buf bytes.Buffer
|
||||
var jqErr error
|
||||
if opts.Raw {
|
||||
jqErr = JqFilterRaw(&buf, env, opts.JQ)
|
||||
} else {
|
||||
jqErr = JqFilter(&buf, env, opts.JQ)
|
||||
}
|
||||
if jqErr != nil {
|
||||
return jqErr
|
||||
}
|
||||
if _, err := io.Copy(e.out, &buf); err != nil {
|
||||
return wrapOutputError("write", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return e.emit(func(w io.Writer) error {
|
||||
if opts.Raw {
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(env)
|
||||
}
|
||||
return WriteJSON(w, env)
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Emitter) emitPretty(data interface{}, opts EmitOptions) error {
|
||||
scanResult := ScanForSafety(e.commandPath, data, e.errOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
if err := WriteAlertWarning(e.errOut, scanResult.Alert); err != nil {
|
||||
return wrapOutputError("write", err)
|
||||
}
|
||||
}
|
||||
if opts.Pretty != nil {
|
||||
return e.emit(func(w io.Writer) error {
|
||||
return opts.Pretty(w, e.colorEnabled)
|
||||
})
|
||||
}
|
||||
|
||||
// RuntimeContext.outFormat falls back through Out/OutRaw when no pretty
|
||||
// renderer is supplied. Keep that second scan visible in the leaf contract
|
||||
// until production callers are migrated and the legacy behavior is removed.
|
||||
return e.emitEnvelope(data, true, opts)
|
||||
}
|
||||
|
||||
func (e *Emitter) emitFormatted(data interface{}, rawFormat string) error {
|
||||
scanResult := ScanForSafety(e.commandPath, data, e.errOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
if err := WriteAlertWarning(e.errOut, scanResult.Alert); err != nil {
|
||||
return wrapOutputError("write", err)
|
||||
}
|
||||
}
|
||||
|
||||
format, known := ParseFormat(rawFormat)
|
||||
if !known && e.errOut != nil {
|
||||
fmt.Fprintf(e.errOut, "warning: unknown format %q, falling back to json\n", rawFormat)
|
||||
}
|
||||
if format == FormatJSON {
|
||||
return e.printLegacyDataJSON(data)
|
||||
}
|
||||
return e.emit(func(w io.Writer) error {
|
||||
return WriteFormatted(w, data, format)
|
||||
})
|
||||
}
|
||||
|
||||
type emitterDataMap map[string]interface{}
|
||||
|
||||
// printLegacyDataJSON matches FormatValue's JSON branch while sourcing notice
|
||||
// data from this Emitter instead of PrintJson's global PendingNotice hook.
|
||||
func (e *Emitter) printLegacyDataJSON(data interface{}) error {
|
||||
// Normalise structs / named maps to plain generic types first, exactly as
|
||||
// FormatValue does, so a struct or named-map payload still matches the map
|
||||
// case below and keeps its injected _notice on the unknown-format fallback.
|
||||
data = toGeneric(data)
|
||||
if m, ok := data.(map[string]interface{}); ok {
|
||||
if _, isEnvelope := m["ok"]; isEnvelope {
|
||||
if notice := e.notice(); notice != nil {
|
||||
m = maps.Clone(m)
|
||||
m["_notice"] = notice
|
||||
}
|
||||
}
|
||||
// The named map retains identical JSON bytes while preventing PrintJson
|
||||
// from consulting its legacy global notice hook a second time.
|
||||
return e.emit(func(w io.Writer) error {
|
||||
return WriteJSON(w, emitterDataMap(m))
|
||||
})
|
||||
}
|
||||
return e.emit(func(w io.Writer) error {
|
||||
return WriteJSON(w, data)
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Emitter) emit(render func(io.Writer) error) error {
|
||||
var buf bytes.Buffer
|
||||
if err := render(&buf); err != nil {
|
||||
return wrapOutputError("render", err)
|
||||
}
|
||||
if _, err := io.Copy(e.out, &buf); err != nil {
|
||||
return wrapOutputError("write", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func wrapOutputError(op string, err error) error {
|
||||
return errs.NewInternalError(errs.SubtypeUnknown, "failed to %s command output", op).WithCause(err)
|
||||
}
|
||||
|
||||
func (e *Emitter) notice() map[string]interface{} {
|
||||
if e.noticeProvider == nil {
|
||||
return nil
|
||||
}
|
||||
return e.noticeProvider()
|
||||
}
|
||||
|
||||
func (e *Emitter) requireOutput() error {
|
||||
if e == nil || e.out == nil {
|
||||
return errs.NewInternalError(errs.SubtypeUnknown,
|
||||
"success output writer is not configured")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
350
internal/output/emitter_contract_test.go
Normal file
350
internal/output/emitter_contract_test.go
Normal file
@@ -0,0 +1,350 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package output_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
extcs "github.com/larksuite/cli/extension/contentsafety"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
)
|
||||
|
||||
type contractFailingWriter struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (w contractFailingWriter) Write([]byte) (int, error) {
|
||||
return 0, w.err
|
||||
}
|
||||
|
||||
type contractSafetyProvider struct {
|
||||
alert *extcs.Alert
|
||||
}
|
||||
|
||||
func (p *contractSafetyProvider) Name() string {
|
||||
return "emitter-contract"
|
||||
}
|
||||
|
||||
func (p *contractSafetyProvider) Scan(context.Context, extcs.ScanRequest) (*extcs.Alert, error) {
|
||||
return p.alert, nil
|
||||
}
|
||||
|
||||
func TestEmitterSuccessWritesAllBytes(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
Identity: "bot",
|
||||
})
|
||||
data := map[string]interface{}{"id": "1"}
|
||||
|
||||
err := emitter.Success(data, output.EmitOptions{Format: "json"})
|
||||
if err != nil {
|
||||
t.Fatalf("Emitter.Success() error = %v", err)
|
||||
}
|
||||
want, marshalErr := json.MarshalIndent(output.Envelope{OK: true, Identity: "bot", Data: data}, "", " ")
|
||||
if marshalErr != nil {
|
||||
t.Fatalf("marshal expected envelope: %v", marshalErr)
|
||||
}
|
||||
want = append(want, '\n')
|
||||
if !bytes.Equal(stdout.Bytes(), want) {
|
||||
t.Fatalf("stdout bytes = %q, want %q", stdout.Bytes(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterMarshalFailureReturnsTypedErrorWithoutOutput(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
|
||||
err := emitter.Success(map[string]interface{}{"unsupported": func() {}}, output.EmitOptions{Format: "json"})
|
||||
if err == nil {
|
||||
t.Fatal("Emitter.Success() error = nil, want marshal failure")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("Emitter.Success() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
var unsupported *json.UnsupportedTypeError
|
||||
if !errors.As(err, &unsupported) {
|
||||
t.Fatalf("Emitter.Success() error = %v, want json.UnsupportedTypeError cause", err)
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("Emitter.Success() stdout = %q, want empty", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterWriterFailurePreservesCause(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
sentinel := errors.New("write failed")
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: contractFailingWriter{err: sentinel},
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
|
||||
err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{Format: "json"})
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("Emitter.Success() error = %v, want preserved writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("Emitter.Success() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterPrettyRendererFailurePreservesCause(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
sentinel := errors.New("pretty render failed")
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
|
||||
err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{
|
||||
Format: "pretty",
|
||||
Pretty: func(io.Writer, bool) error {
|
||||
return sentinel
|
||||
},
|
||||
})
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("Emitter.Success() error = %v, want preserved renderer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("Emitter.Success() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("Emitter.Success() stdout = %q, want empty", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterAlertWarningFailurePreservesCause(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "warn")
|
||||
extcs.Register(&contractSafetyProvider{alert: &extcs.Alert{
|
||||
Provider: "emitter-contract",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
}})
|
||||
t.Cleanup(func() { extcs.Register(nil) })
|
||||
sentinel := errors.New("warning write failed")
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: contractFailingWriter{err: sentinel},
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
|
||||
err := emitter.Success([]interface{}{map[string]interface{}{"id": "1"}}, output.EmitOptions{Format: "table"})
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("Emitter.Success() error = %v, want preserved warning writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("Emitter.Success() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("Emitter.Success() stdout = %q, want empty", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmitterDefaultsNilErrOutToDiscard(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "warn")
|
||||
extcs.Register(&contractSafetyProvider{alert: &extcs.Alert{
|
||||
Provider: "emitter-contract",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
}})
|
||||
t.Cleanup(func() { extcs.Register(nil) })
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
|
||||
if err := emitter.Success([]interface{}{map[string]interface{}{"id": "1"}}, output.EmitOptions{Format: "table"}); err != nil {
|
||||
t.Fatalf("Emitter.Success() error = %v", err)
|
||||
}
|
||||
if stdout.Len() == 0 {
|
||||
t.Fatal("Emitter.Success() stdout is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterDoesNotMutateCallerMap(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
data := map[string]interface{}{"ok": true, "value": "fixture"}
|
||||
want := map[string]interface{}{"ok": true, "value": "fixture"}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: &bytes.Buffer{},
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
NoticeProvider: func() map[string]interface{} {
|
||||
return map[string]interface{}{"update": "available"}
|
||||
},
|
||||
})
|
||||
|
||||
if err := emitter.Success(data, output.EmitOptions{Format: "yaml"}); err != nil {
|
||||
t.Fatalf("Emitter.Success() error = %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(data, want) {
|
||||
t.Fatalf("caller map = %#v, want unchanged %#v", data, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterDoesNotOverwriteCallerNotice(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
existing := map[string]interface{}{"source": "caller"}
|
||||
data := map[string]interface{}{"ok": true, "_notice": existing}
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
NoticeProvider: func() map[string]interface{} {
|
||||
return map[string]interface{}{"source": "provider"}
|
||||
},
|
||||
})
|
||||
|
||||
if err := emitter.Success(data, output.EmitOptions{Format: "yaml"}); err != nil {
|
||||
t.Fatalf("Emitter.Success() error = %v", err)
|
||||
}
|
||||
if got := data["_notice"]; !reflect.DeepEqual(got, existing) {
|
||||
t.Fatalf("caller _notice = %#v, want unchanged %#v", got, existing)
|
||||
}
|
||||
var emitted map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &emitted); err != nil {
|
||||
t.Fatalf("decode stdout: %v", err)
|
||||
}
|
||||
if got := emitted["_notice"]; !reflect.DeepEqual(got, map[string]interface{}{"source": "provider"}) {
|
||||
t.Fatalf("emitted _notice = %#v, want provider notice", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterReadsNoticeProviderAtMostOncePerEmission(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
calls := 0
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: &bytes.Buffer{},
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
NoticeProvider: func() map[string]interface{} {
|
||||
calls++
|
||||
return map[string]interface{}{"source": "provider"}
|
||||
},
|
||||
})
|
||||
|
||||
if err := emitter.Success(map[string]interface{}{"ok": true}, output.EmitOptions{Format: "yaml"}); err != nil {
|
||||
t.Fatalf("Emitter.Success() error = %v", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("notice provider calls = %d, want 1", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterRawJSONPropagatesWriteError(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
sentinel := errors.New("write failed")
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: contractFailingWriter{err: sentinel},
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{
|
||||
Raw: true, Format: "json",
|
||||
})
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("Emitter.Success() error = %v, want preserved writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("Emitter.Success() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterInvalidJQReturnsErrorWithoutStderr(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
stderr := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: &bytes.Buffer{},
|
||||
ErrOut: stderr,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{
|
||||
Format: "json",
|
||||
JQ: "this is not valid jq (((",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Success() with invalid jq = nil, want error")
|
||||
}
|
||||
if stderr.Len() != 0 {
|
||||
t.Fatalf("Success() with invalid jq wrote stderr %q, want empty", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterJQRuntimeErrorPreservesTypedError(t *testing.T) {
|
||||
// A valid expression that fails at runtime must surface jq's own typed error
|
||||
// (an api error), not a wrapped internal output error, and must emit no
|
||||
// partial stdout.
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{
|
||||
Format: "json",
|
||||
JQ: `error("boom")`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Success() with a runtime jq error = nil, want error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category == errs.CategoryInternal {
|
||||
t.Fatalf("Success() jq runtime error problem = %#v, %v; want jq's own typed error, not internal", problem, ok)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "jq error") {
|
||||
t.Fatalf("Success() jq runtime error = %v, want jq's own error message preserved", err)
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("Success() jq runtime error wrote stdout %q, want empty", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterUnknownFormatStructKeepsNotice(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
type payload struct {
|
||||
OK bool `json:"ok"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
stdout := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
NoticeProvider: func() map[string]interface{} {
|
||||
return map[string]interface{}{"update": map[string]interface{}{"latest": "9.9.9"}}
|
||||
},
|
||||
})
|
||||
if err := emitter.Success(payload{OK: true, Value: "fixture"}, output.EmitOptions{Format: "yaml"}); err != nil {
|
||||
t.Fatalf("Success() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdout.String(), "_notice") {
|
||||
t.Fatalf("struct payload on unknown-format fallback dropped _notice:\n%s", stdout.String())
|
||||
}
|
||||
}
|
||||
827
internal/output/emitter_legacy_compat_test.go
Normal file
827
internal/output/emitter_legacy_compat_test.go
Normal file
@@ -0,0 +1,827 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Legacy oracle fixtures are frozen at base SHA 4a56748bfa941ff0ee0bfec92e65acac427732b0.
|
||||
// Golden regeneration is allowed only from that base, never from the current system under test.
|
||||
|
||||
package output_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
extcs "github.com/larksuite/cli/extension/contentsafety"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
type emitterCapture struct {
|
||||
stdout string
|
||||
stderr string
|
||||
err error
|
||||
}
|
||||
|
||||
type emitterSafetyProvider struct {
|
||||
alert *extcs.Alert
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *emitterSafetyProvider) Name() string { return "emitter-oracle" }
|
||||
|
||||
func (p *emitterSafetyProvider) Scan(context.Context, extcs.ScanRequest) (*extcs.Alert, error) {
|
||||
return p.alert, p.err
|
||||
}
|
||||
|
||||
const (
|
||||
runtimeContextLegacyGoldenPath = "testdata/runtime_context_legacy.golden.json"
|
||||
writeSuccessEnvelopeLegacyGoldenPath = "testdata/write_success_envelope_legacy.golden.json"
|
||||
)
|
||||
|
||||
type runtimeContextOracleCase struct {
|
||||
name string
|
||||
data func() interface{}
|
||||
raw bool
|
||||
ok bool
|
||||
meta *output.Meta
|
||||
jq string
|
||||
format string
|
||||
useFormat bool
|
||||
pretty bool
|
||||
notice map[string]interface{}
|
||||
safetyMode string
|
||||
safetyAlert *extcs.Alert
|
||||
safetyErr error
|
||||
}
|
||||
|
||||
type runtimeContextLegacyGolden struct {
|
||||
Cases map[string]emitterCaptureGolden `json:"cases"`
|
||||
}
|
||||
|
||||
type writeSuccessEnvelopeOracleCase struct {
|
||||
name string
|
||||
data func() interface{}
|
||||
dryRun bool
|
||||
jq string
|
||||
notice map[string]interface{}
|
||||
safetyMode string
|
||||
safetyAlert *extcs.Alert
|
||||
}
|
||||
|
||||
type writeSuccessEnvelopeLegacyGolden struct {
|
||||
Cases map[string]emitterCaptureGolden `json:"cases"`
|
||||
}
|
||||
|
||||
type emitterCaptureGolden struct {
|
||||
Stdout string `json:"stdout"`
|
||||
Stderr string `json:"stderr"`
|
||||
Error *emitterErrorGolden `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type emitterErrorGolden struct {
|
||||
GoType string `json:"go_type"`
|
||||
JSON json.RawMessage `json:"json"`
|
||||
Message string `json:"message"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
}
|
||||
|
||||
func TestEmitterMatchesRuntimeContextLegacyOracle(t *testing.T) {
|
||||
previousNotice := output.PendingNotice
|
||||
t.Cleanup(func() {
|
||||
output.PendingNotice = previousNotice
|
||||
extcs.Register(nil)
|
||||
})
|
||||
|
||||
cases := []runtimeContextOracleCase{
|
||||
{
|
||||
name: "json_object",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"id": "1", "enabled": true}
|
||||
},
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "raw_json_preserves_html",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"html": "<p>a&b</p>"}
|
||||
},
|
||||
raw: true,
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "format_raw_json_preserves_html",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"html": "<p>a&b</p>"}
|
||||
},
|
||||
raw: true,
|
||||
ok: true,
|
||||
format: "json",
|
||||
useFormat: true,
|
||||
},
|
||||
{
|
||||
name: "partial_failure_ok_false",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"succeeded": 1, "failed": 1}
|
||||
},
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
data: func() interface{} {
|
||||
return []interface{}{map[string]interface{}{"id": "1"}}
|
||||
},
|
||||
ok: true,
|
||||
meta: &output.Meta{Count: 1, Rollback: "lark-cli fixture rollback"},
|
||||
},
|
||||
{
|
||||
name: "jq_scalar",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"name": "Alice", "age": 30}
|
||||
},
|
||||
ok: true,
|
||||
jq: ".data.name",
|
||||
},
|
||||
{
|
||||
name: "raw_jq_complex",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"document": map[string]interface{}{"html": "<p>a&b</p>"}}
|
||||
},
|
||||
raw: true,
|
||||
ok: true,
|
||||
jq: ".data.document",
|
||||
},
|
||||
{
|
||||
name: "jq_invalid_expression",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"id": "1"}
|
||||
},
|
||||
ok: false,
|
||||
jq: "invalid[",
|
||||
},
|
||||
{
|
||||
name: "notice",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"id": "1"}
|
||||
},
|
||||
ok: true,
|
||||
notice: map[string]interface{}{"update": map[string]interface{}{"latest": "9.9.9"}},
|
||||
},
|
||||
{
|
||||
name: "pretty",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"name": "Alice"}
|
||||
},
|
||||
ok: true,
|
||||
format: "pretty",
|
||||
useFormat: true,
|
||||
pretty: true,
|
||||
},
|
||||
{
|
||||
name: "pretty_without_renderer",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"name": "Alice"}
|
||||
},
|
||||
ok: true,
|
||||
format: "pretty",
|
||||
useFormat: true,
|
||||
},
|
||||
{
|
||||
name: "ndjson",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"items": []interface{}{
|
||||
map[string]interface{}{"id": "1"},
|
||||
map[string]interface{}{"id": "2"},
|
||||
}}
|
||||
},
|
||||
ok: true,
|
||||
format: "ndjson",
|
||||
useFormat: true,
|
||||
},
|
||||
{
|
||||
name: "table_with_safety_warning",
|
||||
data: func() interface{} {
|
||||
return []interface{}{map[string]interface{}{"id": "1", "name": "Alice"}}
|
||||
},
|
||||
ok: true,
|
||||
format: "table",
|
||||
useFormat: true,
|
||||
safetyMode: "warn",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "csv",
|
||||
data: func() interface{} {
|
||||
return []interface{}{
|
||||
map[string]interface{}{"id": "1", "name": "Alice"},
|
||||
map[string]interface{}{"id": "2", "name": "Bob"},
|
||||
}
|
||||
},
|
||||
ok: true,
|
||||
format: "csv",
|
||||
useFormat: true,
|
||||
},
|
||||
{
|
||||
name: "jq_safety_alert_without_stderr_warning",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"id": "1"}
|
||||
},
|
||||
ok: true,
|
||||
jq: ".data.id",
|
||||
safetyMode: "warn",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "scanner_error_fails_open",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"id": "1"}
|
||||
},
|
||||
ok: true,
|
||||
safetyMode: "warn",
|
||||
safetyErr: errors.New("scanner unavailable"),
|
||||
},
|
||||
{
|
||||
name: "scanner_block",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"id": "blocked"}
|
||||
},
|
||||
ok: false,
|
||||
safetyMode: "block",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unknown_format_data_envelope_notice",
|
||||
data: func() interface{} {
|
||||
return map[string]interface{}{"ok": true, "value": "fixture"}
|
||||
},
|
||||
ok: true,
|
||||
format: "yaml",
|
||||
useFormat: true,
|
||||
notice: map[string]interface{}{"skills": map[string]interface{}{"current": "1.0.0"}},
|
||||
},
|
||||
}
|
||||
|
||||
golden := loadRuntimeContextLegacyGolden(t)
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
mode := tc.safetyMode
|
||||
if mode == "" {
|
||||
mode = "off"
|
||||
}
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", mode)
|
||||
extcs.Register(&emitterSafetyProvider{alert: tc.safetyAlert, err: tc.safetyErr})
|
||||
t.Cleanup(func() { extcs.Register(nil) })
|
||||
|
||||
notice := tc.notice
|
||||
output.PendingNotice = func() map[string]interface{} { return notice }
|
||||
|
||||
want, ok := golden.Cases[tc.name]
|
||||
if !ok {
|
||||
t.Fatalf("frozen golden case %q is missing", tc.name)
|
||||
}
|
||||
|
||||
opts := runtimeOracleOptions{
|
||||
raw: tc.raw,
|
||||
ok: tc.ok,
|
||||
meta: tc.meta,
|
||||
jq: tc.jq,
|
||||
format: tc.format,
|
||||
useFormat: tc.useFormat,
|
||||
pretty: tc.pretty,
|
||||
}
|
||||
current := runEmitterWithRuntimeContextContract(tc.data(), output.EmitterConfig{
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
Identity: "bot",
|
||||
NoticeProvider: func() map[string]interface{} { return notice },
|
||||
}, tc.ok, output.EmitOptions{
|
||||
Raw: tc.raw,
|
||||
Meta: tc.meta,
|
||||
Format: tc.format,
|
||||
JQ: tc.jq,
|
||||
Pretty: emitterPrettyRenderer(tc.pretty),
|
||||
})
|
||||
|
||||
assertEmitterGolden(t, want, current)
|
||||
|
||||
integrated := runRuntimeContextOracle(t, tc.data(), opts)
|
||||
assertEmitterGolden(t, want, integrated)
|
||||
if tc.safetyMode == "block" {
|
||||
var safetyErr *errs.ContentSafetyError
|
||||
if !errors.As(current.err, &safetyErr) {
|
||||
t.Fatalf("Emitter.Success() error = %T, want *errs.ContentSafetyError", current.err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if len(golden.Cases) != len(cases) {
|
||||
t.Fatalf("golden case count = %d, want %d", len(golden.Cases), len(cases))
|
||||
}
|
||||
|
||||
jqFailure := golden.Cases["jq_invalid_expression"]
|
||||
if !strings.HasPrefix(jqFailure.Stderr, "error: ") || !strings.HasSuffix(jqFailure.Stderr, "\n") {
|
||||
t.Fatalf("invalid jq golden stderr = %q, want error line ending in newline", jqFailure.Stderr)
|
||||
}
|
||||
if jqFailure.Error == nil || jqFailure.Error.ExitCode != output.ExitValidation {
|
||||
t.Fatalf("invalid jq golden exit = %#v, want %d", jqFailure.Error, output.ExitValidation)
|
||||
}
|
||||
}
|
||||
|
||||
func loadRuntimeContextLegacyGolden(t *testing.T) runtimeContextLegacyGolden {
|
||||
t.Helper()
|
||||
contents, err := os.ReadFile(runtimeContextLegacyGoldenPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read RuntimeContext legacy golden: %v", err)
|
||||
}
|
||||
var golden runtimeContextLegacyGolden
|
||||
if err := json.Unmarshal(contents, &golden); err != nil {
|
||||
t.Fatalf("decode RuntimeContext legacy golden: %v", err)
|
||||
}
|
||||
return golden
|
||||
}
|
||||
|
||||
func captureEmitterGolden(t *testing.T, capture emitterCapture) emitterCaptureGolden {
|
||||
t.Helper()
|
||||
golden := emitterCaptureGolden{Stdout: capture.stdout, Stderr: capture.stderr}
|
||||
if capture.err == nil {
|
||||
return golden
|
||||
}
|
||||
errorJSON, err := json.Marshal(capture.err)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal captured error %T: %v", capture.err, err)
|
||||
}
|
||||
golden.Error = &emitterErrorGolden{
|
||||
GoType: fmt.Sprintf("%T", capture.err),
|
||||
JSON: errorJSON,
|
||||
Message: capture.err.Error(),
|
||||
ExitCode: output.ExitCodeOf(capture.err),
|
||||
}
|
||||
return golden
|
||||
}
|
||||
|
||||
type runtimeOracleOptions struct {
|
||||
raw bool
|
||||
ok bool
|
||||
meta *output.Meta
|
||||
jq string
|
||||
format string
|
||||
useFormat bool
|
||||
pretty bool
|
||||
}
|
||||
|
||||
func runRuntimeContextOracle(t *testing.T, data interface{}, opts runtimeOracleOptions) emitterCapture {
|
||||
t.Helper()
|
||||
stdout := &bytes.Buffer{}
|
||||
stderr := &bytes.Buffer{}
|
||||
parent := &cobra.Command{Use: "lark-cli"}
|
||||
cmd := &cobra.Command{Use: "fixture"}
|
||||
leaf := &cobra.Command{Use: "+emit"}
|
||||
parent.AddCommand(cmd)
|
||||
cmd.AddCommand(leaf)
|
||||
|
||||
factory := &cmdutil.Factory{IOStreams: &cmdutil.IOStreams{Out: stdout, ErrOut: stderr}}
|
||||
runtime := common.TestNewRuntimeContextForAPI(
|
||||
context.Background(), leaf, &core.CliConfig{Brand: core.BrandFeishu}, factory, core.AsBot,
|
||||
)
|
||||
runtime.Format = opts.format
|
||||
runtime.JqExpr = opts.jq
|
||||
|
||||
pretty := func(w io.Writer) {
|
||||
fmt.Fprintln(w, "pretty:fixture")
|
||||
}
|
||||
if !opts.pretty {
|
||||
pretty = nil
|
||||
}
|
||||
|
||||
var err error
|
||||
switch {
|
||||
case opts.useFormat && opts.raw:
|
||||
runtime.OutFormatRaw(data, opts.meta, pretty)
|
||||
case opts.useFormat:
|
||||
runtime.OutFormat(data, opts.meta, pretty)
|
||||
case !opts.ok:
|
||||
err = runtime.OutPartialFailure(data, opts.meta)
|
||||
case opts.raw:
|
||||
runtime.OutRaw(data, opts.meta)
|
||||
default:
|
||||
runtime.Out(data, opts.meta)
|
||||
}
|
||||
|
||||
return emitterCapture{stdout: stdout.String(), stderr: stderr.String(), err: err}
|
||||
}
|
||||
|
||||
func runEmitterSuccess(data interface{}, config output.EmitterConfig, ok bool, opts output.EmitOptions) emitterCapture {
|
||||
stdout := &bytes.Buffer{}
|
||||
stderr := &bytes.Buffer{}
|
||||
config.Out = stdout
|
||||
config.ErrOut = stderr
|
||||
emitter := output.NewEmitter(config)
|
||||
var err error
|
||||
if ok {
|
||||
err = emitter.Success(data, opts)
|
||||
} else {
|
||||
err = emitter.PartialFailure(data, opts)
|
||||
}
|
||||
return emitterCapture{stdout: stdout.String(), stderr: stderr.String(), err: err}
|
||||
}
|
||||
|
||||
func runEmitterWithRuntimeContextContract(data interface{}, config output.EmitterConfig, ok bool, opts output.EmitOptions) emitterCapture {
|
||||
capture := runEmitterSuccess(data, config, ok, opts)
|
||||
if capture.err != nil {
|
||||
var safetyErr *errs.ContentSafetyError
|
||||
if errors.As(capture.err, &safetyErr) {
|
||||
return capture
|
||||
}
|
||||
if opts.JQ != "" {
|
||||
capture.stderr += fmt.Sprintf("error: %v\n", capture.err)
|
||||
return capture
|
||||
}
|
||||
capture.err = nil
|
||||
}
|
||||
if !ok {
|
||||
capture.err = output.PartialFailure(output.ExitAPI)
|
||||
}
|
||||
return capture
|
||||
}
|
||||
|
||||
func emitterPrettyRenderer(enabled bool) output.PrettyRenderer {
|
||||
if !enabled {
|
||||
return nil
|
||||
}
|
||||
return func(w io.Writer, _ bool) error {
|
||||
_, err := fmt.Fprintln(w, "pretty:fixture")
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitterMatchesWriteSuccessEnvelopeLegacyOracle(t *testing.T) {
|
||||
previousNotice := output.PendingNotice
|
||||
t.Cleanup(func() {
|
||||
output.PendingNotice = previousNotice
|
||||
extcs.Register(nil)
|
||||
})
|
||||
|
||||
cases := []writeSuccessEnvelopeOracleCase{
|
||||
{
|
||||
name: "json",
|
||||
data: func() interface{} { return map[string]interface{}{"id": "1"} },
|
||||
},
|
||||
{
|
||||
name: "dry_run",
|
||||
data: func() interface{} { return map[string]interface{}{"api": []interface{}{}} },
|
||||
dryRun: true,
|
||||
},
|
||||
{
|
||||
name: "jq",
|
||||
data: func() interface{} { return map[string]interface{}{"id": "1"} },
|
||||
jq: ".data.id",
|
||||
},
|
||||
{
|
||||
name: "notice",
|
||||
data: func() interface{} { return map[string]interface{}{"id": "1"} },
|
||||
notice: map[string]interface{}{"update": map[string]interface{}{"latest": "9.9.9"}},
|
||||
},
|
||||
{
|
||||
name: "jq_safety_warning",
|
||||
data: func() interface{} { return map[string]interface{}{"id": "1"} },
|
||||
jq: ".data.id",
|
||||
safetyMode: "warn",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "scanner_block",
|
||||
data: func() interface{} { return map[string]interface{}{"id": "blocked"} },
|
||||
safetyMode: "block",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
}
|
||||
golden := loadWriteSuccessEnvelopeLegacyGolden(t)
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
mode := tc.safetyMode
|
||||
if mode == "" {
|
||||
mode = "off"
|
||||
}
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", mode)
|
||||
extcs.Register(&emitterSafetyProvider{alert: tc.safetyAlert})
|
||||
t.Cleanup(func() { extcs.Register(nil) })
|
||||
notice := tc.notice
|
||||
output.PendingNotice = func() map[string]interface{} { return notice }
|
||||
|
||||
want, ok := golden.Cases[tc.name]
|
||||
if !ok {
|
||||
t.Fatalf("frozen golden case %q is missing", tc.name)
|
||||
}
|
||||
|
||||
current := runEmitterSuccess(tc.data(), output.EmitterConfig{
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
Identity: "bot",
|
||||
NoticeProvider: func() map[string]interface{} { return notice },
|
||||
}, true, output.EmitOptions{
|
||||
Format: "",
|
||||
Raw: false,
|
||||
JQ: tc.jq,
|
||||
DryRun: tc.dryRun,
|
||||
JQSafetyWarning: true,
|
||||
})
|
||||
assertEmitterGolden(t, want, current)
|
||||
|
||||
integrated := runWriteSuccessEnvelopeOracle(tc.data(), tc.dryRun, tc.jq)
|
||||
assertEmitterGolden(t, want, integrated)
|
||||
})
|
||||
}
|
||||
|
||||
if len(golden.Cases) != len(cases) {
|
||||
t.Fatalf("golden case count = %d, want %d", len(golden.Cases), len(cases))
|
||||
}
|
||||
}
|
||||
|
||||
func loadWriteSuccessEnvelopeLegacyGolden(t *testing.T) writeSuccessEnvelopeLegacyGolden {
|
||||
t.Helper()
|
||||
contents, err := os.ReadFile(writeSuccessEnvelopeLegacyGoldenPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read WriteSuccessEnvelope legacy golden: %v", err)
|
||||
}
|
||||
var golden writeSuccessEnvelopeLegacyGolden
|
||||
if err := json.Unmarshal(contents, &golden); err != nil {
|
||||
t.Fatalf("decode WriteSuccessEnvelope legacy golden: %v", err)
|
||||
}
|
||||
return golden
|
||||
}
|
||||
|
||||
func runWriteSuccessEnvelopeOracle(data interface{}, dryRun bool, jq string) emitterCapture {
|
||||
stdout := &bytes.Buffer{}
|
||||
stderr := &bytes.Buffer{}
|
||||
err := output.WriteSuccessEnvelope(data, output.SuccessEnvelopeOptions{
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
Identity: "bot",
|
||||
DryRun: dryRun,
|
||||
JqExpr: jq,
|
||||
Out: stdout,
|
||||
ErrOut: stderr,
|
||||
})
|
||||
return emitterCapture{stdout: stdout.String(), stderr: stderr.String(), err: err}
|
||||
}
|
||||
|
||||
func TestEmitterStreamPageMatchesPaginationLegacyOracle(t *testing.T) {
|
||||
t.Cleanup(func() { extcs.Register(nil) })
|
||||
|
||||
type oracleCase struct {
|
||||
name string
|
||||
format output.Format
|
||||
safetyMode string
|
||||
safetyAlert *extcs.Alert
|
||||
}
|
||||
cases := []oracleCase{
|
||||
{name: "ndjson", format: output.FormatNDJSON},
|
||||
{name: "table", format: output.FormatTable},
|
||||
{name: "csv", format: output.FormatCSV},
|
||||
{
|
||||
name: "warn",
|
||||
format: output.FormatNDJSON,
|
||||
safetyMode: "warn",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "block",
|
||||
format: output.FormatTable,
|
||||
safetyMode: "block",
|
||||
safetyAlert: &extcs.Alert{
|
||||
Provider: "emitter-oracle",
|
||||
MatchedRules: []string{"fixture-rule"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
pages := []interface{}{
|
||||
[]interface{}{map[string]interface{}{"id": "1", "name": "Alice"}},
|
||||
[]interface{}{map[string]interface{}{"id": "2", "name": "Bob", "ignored": true}},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
mode := tc.safetyMode
|
||||
if mode == "" {
|
||||
mode = "off"
|
||||
}
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", mode)
|
||||
extcs.Register(&emitterSafetyProvider{alert: tc.safetyAlert})
|
||||
t.Cleanup(func() { extcs.Register(nil) })
|
||||
|
||||
legacy := runPaginationOracle(pages, tc.format)
|
||||
current := runEmitterStreamPages(pages, tc.format.String())
|
||||
|
||||
assertEmitterBytes(t, legacy, current)
|
||||
assertEquivalentError(t, legacy.err, current.err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func runPaginationOracle(pages []interface{}, format output.Format) emitterCapture {
|
||||
stdout := &bytes.Buffer{}
|
||||
stderr := &bytes.Buffer{}
|
||||
formatter := output.NewPaginatedFormatter(stdout, format)
|
||||
var emitErr error
|
||||
for _, page := range pages {
|
||||
scanResult := output.ScanForSafety("lark-cli fixture +emit", page, stderr)
|
||||
if scanResult.Blocked {
|
||||
emitErr = scanResult.BlockErr
|
||||
break
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
output.WriteAlertWarning(stderr, scanResult.Alert)
|
||||
}
|
||||
formatter.FormatPage(page)
|
||||
}
|
||||
return emitterCapture{stdout: stdout.String(), stderr: stderr.String(), err: emitErr}
|
||||
}
|
||||
|
||||
func runEmitterStreamPages(pages []interface{}, format string) emitterCapture {
|
||||
stdout := &bytes.Buffer{}
|
||||
stderr := &bytes.Buffer{}
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: stderr,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
Identity: "bot",
|
||||
})
|
||||
var emitErr error
|
||||
for _, page := range pages {
|
||||
if emitErr = emitter.StreamPage(page, output.StreamOptions{Format: format}); emitErr != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return emitterCapture{stdout: stdout.String(), stderr: stderr.String(), err: emitErr}
|
||||
}
|
||||
|
||||
func TestEmitterCapturesNoticeAndColorDependencies(t *testing.T) {
|
||||
previousNotice := output.PendingNotice
|
||||
output.PendingNotice = func() map[string]interface{} {
|
||||
return map[string]interface{}{"source": "global"}
|
||||
}
|
||||
t.Cleanup(func() { output.PendingNotice = previousNotice })
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
|
||||
stdout := &bytes.Buffer{}
|
||||
stderr := &bytes.Buffer{}
|
||||
colorSeen := false
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: stdout,
|
||||
ErrOut: stderr,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
Identity: "bot",
|
||||
ColorEnabled: true,
|
||||
NoticeProvider: func() map[string]interface{} {
|
||||
return map[string]interface{}{"source": "captured"}
|
||||
},
|
||||
})
|
||||
if err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{Format: "json"}); err != nil {
|
||||
t.Fatalf("Emitter.Success() error = %v", err)
|
||||
}
|
||||
if strings.Contains(stdout.String(), "global") || !strings.Contains(stdout.String(), "captured") {
|
||||
t.Fatalf("notice source was not captured by Emitter:\n%s", stdout.String())
|
||||
}
|
||||
|
||||
stdout.Reset()
|
||||
if err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{Format: "pretty",
|
||||
Pretty: func(w io.Writer, colorEnabled bool) error {
|
||||
colorSeen = colorEnabled
|
||||
_, err := fmt.Fprintln(w, "pretty")
|
||||
return err
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("Emitter.Success(pretty) error = %v", err)
|
||||
}
|
||||
if !colorSeen {
|
||||
t.Fatal("PrettyRenderer did not receive captured ColorEnabled value")
|
||||
}
|
||||
|
||||
stdout.Reset()
|
||||
if err := emitter.Success(map[string]interface{}{"ok": true, "id": "1"}, output.EmitOptions{Format: "yaml"}); err != nil {
|
||||
t.Fatalf("Emitter.Success(unknown format) error = %v", err)
|
||||
}
|
||||
if strings.Contains(stdout.String(), "global") || !strings.Contains(stdout.String(), "captured") {
|
||||
t.Fatalf("legacy JSON fallback consulted global notice:\n%s", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
type failingEmitterWriter struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (w failingEmitterWriter) Write([]byte) (int, error) { return 0, w.err }
|
||||
|
||||
func TestEmitterPropagatesOutputError(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "off")
|
||||
sentinel := errors.New("write failed")
|
||||
emitter := output.NewEmitter(output.EmitterConfig{
|
||||
Out: failingEmitterWriter{err: sentinel},
|
||||
ErrOut: io.Discard,
|
||||
CommandPath: "lark-cli fixture +emit",
|
||||
})
|
||||
err := emitter.Success(map[string]interface{}{"id": "1"}, output.EmitOptions{
|
||||
Raw: true, Format: "json",
|
||||
JQ: ".data",
|
||||
})
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("Emitter.Success() error = %v, want preserved writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("Emitter.Success() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEmitterBytes(t *testing.T, legacy, current emitterCapture) {
|
||||
t.Helper()
|
||||
if legacy.stdout != current.stdout {
|
||||
t.Fatalf("stdout byte mismatch\nlegacy (%d bytes):\n%q\nEmitter (%d bytes):\n%q",
|
||||
len(legacy.stdout), legacy.stdout, len(current.stdout), current.stdout)
|
||||
}
|
||||
if legacy.stderr != current.stderr {
|
||||
t.Fatalf("stderr byte mismatch\nlegacy (%d bytes):\n%q\nEmitter (%d bytes):\n%q",
|
||||
len(legacy.stderr), legacy.stderr, len(current.stderr), current.stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEmitterGolden(t *testing.T, want emitterCaptureGolden, current emitterCapture) {
|
||||
t.Helper()
|
||||
if want.Stdout != current.stdout {
|
||||
t.Fatalf("stdout byte mismatch\ngolden (%d bytes):\n%q\ncurrent (%d bytes):\n%q",
|
||||
len(want.Stdout), want.Stdout, len(current.stdout), current.stdout)
|
||||
}
|
||||
if want.Stderr != current.stderr {
|
||||
t.Fatalf("stderr byte mismatch\ngolden (%d bytes):\n%q\ncurrent (%d bytes):\n%q",
|
||||
len(want.Stderr), want.Stderr, len(current.stderr), current.stderr)
|
||||
}
|
||||
got := captureEmitterGolden(t, current)
|
||||
if (want.Error == nil) != (got.Error == nil) {
|
||||
t.Fatalf("error presence mismatch: golden=%#v current=%#v", want.Error, got.Error)
|
||||
}
|
||||
if want.Error == nil {
|
||||
return
|
||||
}
|
||||
if want.Error.GoType != got.Error.GoType || want.Error.Message != got.Error.Message || want.Error.ExitCode != got.Error.ExitCode {
|
||||
t.Fatalf("error mismatch:\ngolden: %#v\ncurrent: %#v", want.Error, got.Error)
|
||||
}
|
||||
var wantJSON interface{}
|
||||
if err := json.Unmarshal(want.Error.JSON, &wantJSON); err != nil {
|
||||
t.Fatalf("decode golden error JSON: %v", err)
|
||||
}
|
||||
var gotJSON interface{}
|
||||
if err := json.Unmarshal(got.Error.JSON, &gotJSON); err != nil {
|
||||
t.Fatalf("decode current error JSON: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(wantJSON, gotJSON) {
|
||||
t.Fatalf("error JSON mismatch:\ngolden: %s\ncurrent: %s", want.Error.JSON, got.Error.JSON)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEquivalentError(t *testing.T, legacy, current error) {
|
||||
t.Helper()
|
||||
if (legacy == nil) != (current == nil) {
|
||||
t.Fatalf("error presence mismatch: legacy=%v Emitter=%v", legacy, current)
|
||||
}
|
||||
if legacy == nil {
|
||||
return
|
||||
}
|
||||
legacyProblem, legacyOK := errs.ProblemOf(legacy)
|
||||
currentProblem, currentOK := errs.ProblemOf(current)
|
||||
if legacyOK != currentOK {
|
||||
t.Fatalf("typed error mismatch: legacy=%T Emitter=%T", legacy, current)
|
||||
}
|
||||
if legacyOK && !reflect.DeepEqual(legacyProblem, currentProblem) {
|
||||
t.Fatalf("problem mismatch:\nlegacy: %#v\nEmitter: %#v", legacyProblem, currentProblem)
|
||||
}
|
||||
}
|
||||
@@ -34,27 +34,17 @@ func SuccessEnvelopeData(result interface{}) interface{} {
|
||||
// JSON output carries content-safety alerts inside the envelope. When jq is
|
||||
// applied, the alert may be filtered away, so warn mode also writes stderr.
|
||||
func WriteSuccessEnvelope(data interface{}, opts SuccessEnvelopeOptions) error {
|
||||
scanResult := ScanForSafety(opts.CommandPath, data, opts.ErrOut)
|
||||
if scanResult.Blocked {
|
||||
return scanResult.BlockErr
|
||||
}
|
||||
|
||||
env := Envelope{
|
||||
OK: true,
|
||||
Identity: opts.Identity,
|
||||
DryRun: opts.DryRun,
|
||||
Data: data,
|
||||
Notice: GetNotice(),
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
env.ContentSafetyAlert = scanResult.Alert
|
||||
}
|
||||
if opts.JqExpr != "" {
|
||||
if scanResult.Alert != nil && opts.ErrOut != nil {
|
||||
WriteAlertWarning(opts.ErrOut, scanResult.Alert)
|
||||
}
|
||||
return JqFilter(opts.Out, env, opts.JqExpr)
|
||||
}
|
||||
PrintJson(opts.Out, env)
|
||||
return nil
|
||||
return NewEmitter(EmitterConfig{
|
||||
Out: opts.Out,
|
||||
ErrOut: opts.ErrOut,
|
||||
CommandPath: opts.CommandPath,
|
||||
Identity: opts.Identity,
|
||||
NoticeProvider: GetNotice,
|
||||
}).Success(data, EmitOptions{
|
||||
Format: "",
|
||||
Raw: false,
|
||||
JQ: opts.JqExpr,
|
||||
DryRun: opts.DryRun,
|
||||
JQSafetyWarning: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -101,34 +101,44 @@ func ExtractItems(data interface{}) []interface{} {
|
||||
|
||||
// FormatValue formats a single response and writes it to w.
|
||||
func FormatValue(w io.Writer, data interface{}, format Format) {
|
||||
err := WriteFormatted(w, data, format)
|
||||
switch {
|
||||
case err == nil:
|
||||
return
|
||||
case isOutputMarshalError(err) && format == FormatNDJSON:
|
||||
legacyStderrf("ndjson marshal error: %v\n", err)
|
||||
case isOutputMarshalError(err):
|
||||
legacyStderrf("json marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteFormatted formats a single response and returns marshal or write errors.
|
||||
func WriteFormatted(w io.Writer, data interface{}, format Format) error {
|
||||
data = toGeneric(data)
|
||||
switch format {
|
||||
case FormatNDJSON:
|
||||
items := ExtractItems(data)
|
||||
if items != nil {
|
||||
PrintNdjson(w, items)
|
||||
} else {
|
||||
PrintNdjson(w, data)
|
||||
return WriteNDJSON(w, items)
|
||||
}
|
||||
return WriteNDJSON(w, data)
|
||||
|
||||
case FormatTable:
|
||||
items := ExtractItems(data)
|
||||
if items != nil {
|
||||
FormatAsTable(w, items)
|
||||
} else {
|
||||
FormatAsTable(w, data)
|
||||
return WriteTable(w, items)
|
||||
}
|
||||
return WriteTable(w, data)
|
||||
|
||||
case FormatCSV:
|
||||
items := ExtractItems(data)
|
||||
if items != nil {
|
||||
FormatAsCSV(w, items)
|
||||
} else {
|
||||
FormatAsCSV(w, data)
|
||||
return WriteCSV(w, items)
|
||||
}
|
||||
return WriteCSV(w, data)
|
||||
|
||||
default: // FormatJSON
|
||||
PrintJson(w, data)
|
||||
return WriteJSON(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,49 +158,63 @@ func NewPaginatedFormatter(w io.Writer, format Format) *PaginatedFormatter {
|
||||
|
||||
// FormatPage formats one page of items.
|
||||
func (pf *PaginatedFormatter) FormatPage(data interface{}) {
|
||||
switch pf.Format {
|
||||
case FormatJSON, FormatNDJSON:
|
||||
if arr, ok := data.([]interface{}); ok {
|
||||
PrintNdjson(pf.W, arr)
|
||||
} else {
|
||||
PrintNdjson(pf.W, data)
|
||||
}
|
||||
|
||||
case FormatTable:
|
||||
pf.formatStructuredPage(data, func(w io.Writer, rows []map[string]string, cols []string, isFirst bool) {
|
||||
widths := computeColumnWidths(rows, cols)
|
||||
if isFirst {
|
||||
writeHeader(w, cols, widths)
|
||||
}
|
||||
for _, row := range rows {
|
||||
writeRow(w, row, cols, widths)
|
||||
}
|
||||
})
|
||||
|
||||
case FormatCSV:
|
||||
pf.formatStructuredPage(data, func(w io.Writer, rows []map[string]string, cols []string, isFirst bool) {
|
||||
writeCSVRows(w, rows, cols, isFirst)
|
||||
})
|
||||
err := pf.WritePage(data)
|
||||
if isOutputMarshalError(err) && (pf.Format == FormatJSON || pf.Format == FormatNDJSON) {
|
||||
legacyStderrf("ndjson marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WritePage formats one page of items and returns marshal or write errors.
|
||||
func (pf *PaginatedFormatter) WritePage(data interface{}) error {
|
||||
switch pf.Format {
|
||||
case FormatJSON, FormatNDJSON:
|
||||
if arr, ok := data.([]interface{}); ok {
|
||||
return WriteNDJSON(pf.W, arr)
|
||||
}
|
||||
return WriteNDJSON(pf.W, data)
|
||||
|
||||
case FormatTable:
|
||||
return pf.formatStructuredPage(data, func(w io.Writer, rows []map[string]string, cols []string, isFirst bool) error {
|
||||
widths := computeColumnWidths(rows, cols)
|
||||
if isFirst {
|
||||
if err := writeHeader(w, cols, widths); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := writeRow(w, row, cols, widths); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
case FormatCSV:
|
||||
return pf.formatStructuredPage(data, func(w io.Writer, rows []map[string]string, cols []string, isFirst bool) error {
|
||||
return writeCSVRows(w, rows, cols, isFirst)
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// formatStructuredPage handles column-locking logic shared by table and csv.
|
||||
func (pf *PaginatedFormatter) formatStructuredPage(data interface{}, emit func(io.Writer, []map[string]string, []string, bool)) {
|
||||
func (pf *PaginatedFormatter) formatStructuredPage(data interface{}, emit func(io.Writer, []map[string]string, []string, bool) error) error {
|
||||
rows, pageCols, isList := prepareRows(data)
|
||||
if len(rows) == 0 {
|
||||
if pf.isFirstPage && isList {
|
||||
fmt.Fprintln(pf.W, "(empty)")
|
||||
_, err := fmt.Fprintln(pf.W, "(empty)")
|
||||
return err
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if pf.isFirstPage {
|
||||
// Lock columns from first page
|
||||
pf.cols = pageCols
|
||||
pf.isFirstPage = false
|
||||
emit(pf.W, rows, pf.cols, true)
|
||||
return emit(pf.W, rows, pf.cols, true)
|
||||
} else {
|
||||
// Reuse first page's columns — missing keys become empty, extra keys ignored
|
||||
emit(pf.W, rows, pf.cols, false)
|
||||
return emit(pf.W, rows, pf.cols, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package output
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -15,12 +16,44 @@ import (
|
||||
// PrintJson prints data as formatted JSON to w.
|
||||
func PrintJson(w io.Writer, data interface{}) {
|
||||
injectNotice(data)
|
||||
if err := WriteJSON(w, data); isOutputMarshalError(err) {
|
||||
legacyStderrf("json marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
type outputMarshalError struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *outputMarshalError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
func (e *outputMarshalError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
func isOutputMarshalError(err error) bool {
|
||||
var marshalErr *outputMarshalError
|
||||
return errors.As(err, &marshalErr)
|
||||
}
|
||||
|
||||
// legacyStderrf reports a leaf-formatter marshal/format failure on os.Stderr,
|
||||
// preserving the pre-Emitter behavior for direct (unmigrated) callers of the
|
||||
// Print*/FormatAs* wrappers. The Emitter never uses this — it returns typed
|
||||
// errors instead. Removed once the remaining direct callers migrate.
|
||||
func legacyStderrf(format string, args ...interface{}) {
|
||||
fmt.Fprintf(os.Stderr, format, args...) //nolint:forbidigo // legacy leaf-formatter stderr; removed in the output-ownership follow-up
|
||||
}
|
||||
|
||||
// WriteJSON writes data as formatted JSON to w and returns marshal or write errors.
|
||||
func WriteJSON(w io.Writer, data interface{}) error {
|
||||
b, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "json marshal error: %v\n", err)
|
||||
return
|
||||
return &outputMarshalError{err: err}
|
||||
}
|
||||
fmt.Fprintln(w, string(b))
|
||||
_, err = fmt.Fprintln(w, string(b))
|
||||
return err
|
||||
}
|
||||
|
||||
// injectNotice adds a "_notice" field into CLI envelope maps.
|
||||
@@ -50,21 +83,38 @@ func injectNotice(data interface{}) {
|
||||
|
||||
// PrintNdjson prints data as NDJSON (Newline Delimited JSON) to w.
|
||||
func PrintNdjson(w io.Writer, data interface{}) {
|
||||
emit := func(item interface{}) {
|
||||
if arr, ok := data.([]interface{}); ok {
|
||||
for _, item := range arr {
|
||||
if err := WriteNDJSON(w, item); isOutputMarshalError(err) {
|
||||
legacyStderrf("ndjson marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := WriteNDJSON(w, data); isOutputMarshalError(err) {
|
||||
legacyStderrf("ndjson marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteNDJSON writes data as NDJSON and returns marshal or write errors.
|
||||
func WriteNDJSON(w io.Writer, data interface{}) error {
|
||||
emit := func(item interface{}) error {
|
||||
b, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ndjson marshal error: %v\n", err)
|
||||
return
|
||||
return &outputMarshalError{err: err}
|
||||
}
|
||||
fmt.Fprintln(w, string(b))
|
||||
_, err = fmt.Fprintln(w, string(b))
|
||||
return err
|
||||
}
|
||||
if arr, ok := data.([]interface{}); ok {
|
||||
for _, item := range arr {
|
||||
emit(item)
|
||||
if err := emit(item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
emit(data)
|
||||
return nil
|
||||
}
|
||||
return emit(data)
|
||||
}
|
||||
|
||||
func cellStr(val interface{}) string {
|
||||
|
||||
@@ -16,50 +16,69 @@ const maxColWidth = 100
|
||||
// - map[string]interface{} (single object) → key-value two-column table
|
||||
// - empty array → "(empty)"
|
||||
func FormatAsTable(w io.Writer, data interface{}) {
|
||||
FormatAsTablePaginated(w, data, true)
|
||||
if err := WriteTable(w, data); isOutputMarshalError(err) {
|
||||
legacyStderrf("json marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteTable formats data as a table and returns marshal or write errors.
|
||||
func WriteTable(w io.Writer, data interface{}) error {
|
||||
return WriteTablePaginated(w, data, true)
|
||||
}
|
||||
|
||||
// FormatAsTablePaginated formats data as a table with pagination awareness.
|
||||
// When isFirstPage is true, outputs the header; otherwise only data rows.
|
||||
func FormatAsTablePaginated(w io.Writer, data interface{}, isFirstPage bool) {
|
||||
if err := WriteTablePaginated(w, data, isFirstPage); isOutputMarshalError(err) {
|
||||
legacyStderrf("json marshal error: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteTablePaginated formats data as a table and returns marshal or write errors.
|
||||
func WriteTablePaginated(w io.Writer, data interface{}, isFirstPage bool) error {
|
||||
rows, cols, isList := prepareRows(data)
|
||||
if cols == nil {
|
||||
if isList {
|
||||
fmt.Fprintln(w, "(empty)")
|
||||
_, err := fmt.Fprintln(w, "(empty)")
|
||||
return err
|
||||
} else {
|
||||
// Not a list and not an object — print as JSON fallback
|
||||
PrintJson(w, data)
|
||||
return WriteJSON(w, data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
if isFirstPage {
|
||||
fmt.Fprintln(w, "(empty)")
|
||||
_, err := fmt.Fprintln(w, "(empty)")
|
||||
return err
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if !isList {
|
||||
// Single object: key-value two-column format
|
||||
formatKeyValueTable(w, rows[0], cols)
|
||||
return
|
||||
return formatKeyValueTable(w, rows[0], cols)
|
||||
}
|
||||
|
||||
// Calculate column widths (clamped to maxColWidth)
|
||||
widths := computeColumnWidths(rows, cols)
|
||||
|
||||
if isFirstPage {
|
||||
writeHeader(w, cols, widths)
|
||||
if err := writeHeader(w, cols, widths); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
writeRow(w, row, cols, widths)
|
||||
if err := writeRow(w, row, cols, widths); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// formatKeyValueTable renders a single object as a two-column key-value table.
|
||||
func formatKeyValueTable(w io.Writer, row map[string]string, cols []string) {
|
||||
func formatKeyValueTable(w io.Writer, row map[string]string, cols []string) error {
|
||||
maxKeyWidth := 0
|
||||
for _, col := range cols {
|
||||
kw := stringWidth(col)
|
||||
@@ -71,8 +90,11 @@ func formatKeyValueTable(w io.Writer, row map[string]string, cols []string) {
|
||||
for _, col := range cols {
|
||||
val := row[col]
|
||||
val = truncateToWidth(val, maxColWidth)
|
||||
fmt.Fprintf(w, "%s %s\n", padToWidth(col, maxKeyWidth), val)
|
||||
if _, err := fmt.Fprintf(w, "%s %s\n", padToWidth(col, maxKeyWidth), val); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// computeColumnWidths returns display widths for each column, clamped to maxColWidth.
|
||||
@@ -99,25 +121,29 @@ func computeColumnWidths(rows []map[string]string, cols []string) []int {
|
||||
}
|
||||
|
||||
// writeHeader writes the header row and separator line.
|
||||
func writeHeader(w io.Writer, cols []string, widths []int) {
|
||||
func writeHeader(w io.Writer, cols []string, widths []int) error {
|
||||
var header []string
|
||||
var sep []string
|
||||
for i, col := range cols {
|
||||
header = append(header, padToWidth(col, widths[i]))
|
||||
sep = append(sep, strings.Repeat("─", widths[i]))
|
||||
}
|
||||
fmt.Fprintln(w, strings.Join(header, " "))
|
||||
fmt.Fprintln(w, strings.Join(sep, " "))
|
||||
if _, err := fmt.Fprintln(w, strings.Join(header, " ")); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := fmt.Fprintln(w, strings.Join(sep, " "))
|
||||
return err
|
||||
}
|
||||
|
||||
// writeRow writes a single data row.
|
||||
func writeRow(w io.Writer, row map[string]string, cols []string, widths []int) {
|
||||
func writeRow(w io.Writer, row map[string]string, cols []string, widths []int) error {
|
||||
var cells []string
|
||||
for i, col := range cols {
|
||||
val := truncateToWidth(row[col], widths[i])
|
||||
cells = append(cells, padToWidth(val, widths[i]))
|
||||
}
|
||||
fmt.Fprintln(w, strings.Join(cells, " "))
|
||||
_, err := fmt.Fprintln(w, strings.Join(cells, " "))
|
||||
return err
|
||||
}
|
||||
|
||||
// padToWidth pads a string with spaces to reach the target display width.
|
||||
|
||||
107
internal/output/testdata/runtime_context_legacy.golden.json
vendored
Normal file
107
internal/output/testdata/runtime_context_legacy.golden.json
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"cases": {
|
||||
"csv": {
|
||||
"stdout": "id,name\n1,Alice\n2,Bob\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"format_raw_json_preserves_html": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"html\": \"\u003cp\u003ea\u0026b\u003c/p\u003e\"\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"jq_invalid_expression": {
|
||||
"stdout": "",
|
||||
"stderr": "error: invalid jq expression: unexpected EOF\n",
|
||||
"error": {
|
||||
"go_type": "*errs.ValidationError",
|
||||
"json": {
|
||||
"type": "validation",
|
||||
"subtype": "invalid_argument",
|
||||
"message": "invalid jq expression: unexpected EOF"
|
||||
},
|
||||
"message": "invalid jq expression: unexpected EOF",
|
||||
"exit_code": 2
|
||||
}
|
||||
},
|
||||
"jq_safety_alert_without_stderr_warning": {
|
||||
"stdout": "1\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"jq_scalar": {
|
||||
"stdout": "Alice\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"json_object": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"enabled\": true,\n \"id\": \"1\"\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"metadata": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": [\n {\n \"id\": \"1\"\n }\n ],\n \"meta\": {\n \"count\": 1,\n \"rollback\": \"lark-cli fixture rollback\"\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"ndjson": {
|
||||
"stdout": "{\"id\":\"1\"}\n{\"id\":\"2\"}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"notice": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"id\": \"1\"\n },\n \"_notice\": {\n \"update\": {\n \"latest\": \"9.9.9\"\n }\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"partial_failure_ok_false": {
|
||||
"stdout": "{\n \"ok\": false,\n \"identity\": \"bot\",\n \"data\": {\n \"failed\": 1,\n \"succeeded\": 1\n }\n}\n",
|
||||
"stderr": "",
|
||||
"error": {
|
||||
"go_type": "*output.PartialFailureError",
|
||||
"json": {
|
||||
"Code": 1
|
||||
},
|
||||
"message": "partial failure (exit 1)",
|
||||
"exit_code": 1
|
||||
}
|
||||
},
|
||||
"pretty": {
|
||||
"stdout": "pretty:fixture\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"pretty_without_renderer": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"name\": \"Alice\"\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"raw_jq_complex": {
|
||||
"stdout": "{\n \"html\": \"\u003cp\u003ea\u0026b\u003c/p\u003e\"\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"raw_json_preserves_html": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"html\": \"\u003cp\u003ea\u0026b\u003c/p\u003e\"\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"scanner_block": {
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"error": {
|
||||
"go_type": "*errs.ContentSafetyError",
|
||||
"json": {
|
||||
"type": "policy",
|
||||
"subtype": "content_safety",
|
||||
"message": "content safety violation detected (rules: fixture-rule)",
|
||||
"rules": [
|
||||
"fixture-rule"
|
||||
]
|
||||
},
|
||||
"message": "content safety violation detected (rules: fixture-rule)",
|
||||
"exit_code": 6
|
||||
}
|
||||
},
|
||||
"scanner_error_fails_open": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"id\": \"1\"\n }\n}\n",
|
||||
"stderr": "warning: content safety scan error: scanner unavailable\n"
|
||||
},
|
||||
"table_with_safety_warning": {
|
||||
"stdout": "id name \n── ─────\n1 Alice\n",
|
||||
"stderr": "warning: content safety alert from emitter-oracle (rules: fixture-rule)\n"
|
||||
},
|
||||
"unknown_format_data_envelope_notice": {
|
||||
"stdout": "{\n \"_notice\": {\n \"skills\": {\n \"current\": \"1.0.0\"\n }\n },\n \"ok\": true,\n \"value\": \"fixture\"\n}\n",
|
||||
"stderr": "warning: unknown format \"yaml\", falling back to json\n"
|
||||
}
|
||||
}
|
||||
}
|
||||
41
internal/output/testdata/write_success_envelope_legacy.golden.json
vendored
Normal file
41
internal/output/testdata/write_success_envelope_legacy.golden.json
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"cases": {
|
||||
"dry_run": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"dry_run\": true,\n \"data\": {\n \"api\": []\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"jq": {
|
||||
"stdout": "1\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"jq_safety_warning": {
|
||||
"stdout": "1\n",
|
||||
"stderr": "warning: content safety alert from emitter-oracle (rules: fixture-rule)\n"
|
||||
},
|
||||
"json": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"id\": \"1\"\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"notice": {
|
||||
"stdout": "{\n \"ok\": true,\n \"identity\": \"bot\",\n \"data\": {\n \"id\": \"1\"\n },\n \"_notice\": {\n \"update\": {\n \"latest\": \"9.9.9\"\n }\n }\n}\n",
|
||||
"stderr": ""
|
||||
},
|
||||
"scanner_block": {
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"error": {
|
||||
"go_type": "*errs.ContentSafetyError",
|
||||
"json": {
|
||||
"type": "policy",
|
||||
"subtype": "content_safety",
|
||||
"message": "content safety violation detected (rules: fixture-rule)",
|
||||
"rules": [
|
||||
"fixture-rule"
|
||||
]
|
||||
},
|
||||
"message": "content safety violation detected (rules: fixture-rule)",
|
||||
"exit_code": 6
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,11 @@ package diff
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/testutil/gitcmd"
|
||||
)
|
||||
|
||||
func TestScopeIncludesChangedSkillAndRelatedDomain(t *testing.T) {
|
||||
@@ -122,8 +123,7 @@ func writeFile(t *testing.T, repo, rel, content string) {
|
||||
|
||||
func runGit(t *testing.T, repo string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repo
|
||||
cmd := gitcmd.Command(repo, args...)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v failed: %v\n%s", args, err, out)
|
||||
}
|
||||
@@ -131,8 +131,7 @@ func runGit(t *testing.T, repo string, args ...string) {
|
||||
|
||||
func gitOutput(t *testing.T, repo string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repo
|
||||
cmd := gitcmd.Command(repo, args...)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
t.Fatalf("git %v failed: %v", args, err)
|
||||
|
||||
@@ -6,10 +6,11 @@ package publiccontent
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/testutil/gitcmd"
|
||||
)
|
||||
|
||||
func TestCollectScansOnlyCurrentContributionAndMetadata(t *testing.T) {
|
||||
@@ -839,8 +840,7 @@ func runGit(t *testing.T, repo string, args ...string) {
|
||||
if len(args) > 0 && args[0] == "commit" {
|
||||
args = append([]string{"commit", "--no-verify"}, args[1:]...)
|
||||
}
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repo
|
||||
cmd := gitcmd.Command(repo, args...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git %v failed: %v\n%s", args, err, out)
|
||||
@@ -849,8 +849,7 @@ func runGit(t *testing.T, repo string, args ...string) {
|
||||
|
||||
func runGitOutput(t *testing.T, repo string, args ...string) []byte {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repo
|
||||
cmd := gitcmd.Command(repo, args...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git %v failed: %v\n%s", args, err, out)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/qualitygate/facts"
|
||||
"github.com/larksuite/cli/internal/qualitygate/manifest"
|
||||
"github.com/larksuite/cli/internal/qualitygate/report"
|
||||
@@ -726,7 +727,11 @@ func appendDryRunArg(raw string) ([]string, error) {
|
||||
return nil, fmt.Errorf("not a lark-cli command")
|
||||
}
|
||||
argv = truncateShellTail(argv)
|
||||
argv = forceDryRunJSONFormat(argv)
|
||||
var jqValid bool
|
||||
argv, jqValid = stripDryRunJQFilter(argv)
|
||||
if jqValid {
|
||||
argv = forceDryRunJSONFormat(argv)
|
||||
}
|
||||
hasDryRunArg := false
|
||||
dryRunEnabled := false
|
||||
for _, arg := range argv[1:] {
|
||||
@@ -775,6 +780,73 @@ func truncateShellTail(argv []string) []string {
|
||||
return argv
|
||||
}
|
||||
|
||||
// stripDryRunJQFilter removes valid output-only jq filters from the synthetic
|
||||
// dry-run invocation. Invalid jq syntax and incompatible output flags are left
|
||||
// untouched so the real CLI execution still rejects the documented command.
|
||||
// The bool reports whether other output normalization remains safe.
|
||||
func stripDryRunJQFilter(argv []string) ([]string, bool) {
|
||||
jqExpr, outputPath, format, hasJQ, jqHasValue := dryRunOutputFlags(argv)
|
||||
if !hasJQ {
|
||||
return argv, true
|
||||
}
|
||||
if !jqHasValue || output.ValidateJqFlags(jqExpr, outputPath, format) != nil {
|
||||
return argv, false
|
||||
}
|
||||
|
||||
out := make([]string, 0, len(argv))
|
||||
for i := 0; i < len(argv); i++ {
|
||||
arg := argv[i]
|
||||
switch {
|
||||
case arg == "--":
|
||||
return append(out, argv[i:]...), true
|
||||
case arg == "--jq" || arg == "-q":
|
||||
i++
|
||||
case strings.HasPrefix(arg, "--jq=") || strings.HasPrefix(arg, "-q="):
|
||||
continue
|
||||
default:
|
||||
out = append(out, arg)
|
||||
}
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func dryRunOutputFlags(argv []string) (jqExpr, outputPath, format string, hasJQ, jqHasValue bool) {
|
||||
for i := 1; i < len(argv); i++ {
|
||||
arg := argv[i]
|
||||
if arg == "--" {
|
||||
break
|
||||
}
|
||||
switch {
|
||||
case arg == "--jq" || arg == "-q":
|
||||
hasJQ = true
|
||||
jqHasValue = i+1 < len(argv)
|
||||
if jqHasValue {
|
||||
jqExpr = argv[i+1]
|
||||
i++
|
||||
}
|
||||
case strings.HasPrefix(arg, "--jq=") || strings.HasPrefix(arg, "-q="):
|
||||
hasJQ = true
|
||||
jqHasValue = true
|
||||
jqExpr = arg[strings.IndexByte(arg, '=')+1:]
|
||||
case arg == "--output":
|
||||
if i+1 < len(argv) {
|
||||
outputPath = argv[i+1]
|
||||
i++
|
||||
}
|
||||
case strings.HasPrefix(arg, "--output="):
|
||||
outputPath = strings.TrimPrefix(arg, "--output=")
|
||||
case arg == "--format":
|
||||
if i+1 < len(argv) {
|
||||
format = argv[i+1]
|
||||
i++
|
||||
}
|
||||
case strings.HasPrefix(arg, "--format="):
|
||||
format = strings.TrimPrefix(arg, "--format=")
|
||||
}
|
||||
}
|
||||
return jqExpr, outputPath, format, hasJQ, jqHasValue
|
||||
}
|
||||
|
||||
func dryRunFlagExplicitlyTrue(arg string) bool {
|
||||
value, ok := strings.CutPrefix(arg, "--dry-run=")
|
||||
if !ok {
|
||||
|
||||
@@ -194,6 +194,38 @@ func TestRunDryRunsIgnoresTrailingShellComment(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDryRunsIgnoresJQFilterWhenValidatingRequestPreview(t *testing.T) {
|
||||
cliBin, argsPath := fakeDryRunCLI(t, `{"api":[{"method":"GET","url":"/open-apis/im/v1/flags"}]}`)
|
||||
m := manifest.Manifest{Commands: []manifest.Command{{
|
||||
Path: "im +flag-list",
|
||||
Runnable: true,
|
||||
Identities: []string{"user"},
|
||||
Flags: []manifest.Flag{
|
||||
{Name: "as", TakesValue: true},
|
||||
{Name: "page-all"},
|
||||
{Name: "jq", Shorthand: "q", TakesValue: true},
|
||||
{Name: "dry-run"},
|
||||
},
|
||||
}}}
|
||||
ex := skillscan.Example{
|
||||
Raw: `lark-cli im +flag-list --as user --page-all -q '.data.flag_items[-1]'`,
|
||||
SourceFile: "skills/lark-im/references/lark-im-flag-list.md",
|
||||
Line: 26,
|
||||
}
|
||||
|
||||
diags, facts := RunDryRuns(context.Background(), cliBin, m, []skillscan.Example{ex})
|
||||
if len(diags) != 0 {
|
||||
t.Fatalf("RunDryRuns() diagnostics = %#v", diags)
|
||||
}
|
||||
if len(facts) != 1 || !facts[0].Executable || facts[0].SkipReason != "" {
|
||||
t.Fatalf("jq example should remain executable: %#v", facts)
|
||||
}
|
||||
wantArgs := []string{"im", "+flag-list", "--as", "user", "--page-all", "--dry-run"}
|
||||
if gotArgs := readArgs(t, argsPath); !reflect.DeepEqual(gotArgs, wantArgs) {
|
||||
t.Fatalf("fake CLI args = %#v, want %#v", gotArgs, wantArgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDryRunsMaterializesPlaceholdersInsideJSONFlags(t *testing.T) {
|
||||
cliBin, argsPath := fakeDryRunCLI(t, `{"api":[{"method":"GET","url":"/open-apis/im/v1/messages","params":{"chat_id":"oc_test123","page_token":"page_test123"}}]}`)
|
||||
m := manifest.Manifest{Commands: []manifest.Command{{
|
||||
@@ -795,6 +827,72 @@ func TestAppendDryRunArgForcesInlineJSONFormat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendDryRunArgRemovesJQFilter(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "short split",
|
||||
raw: `lark-cli im +flag-list --page-all -q '.data.flag_items[-1]'`,
|
||||
want: []string{"im", "+flag-list", "--page-all", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "long split",
|
||||
raw: `lark-cli im +flag-list --jq '.data.flag_items[].item_id' --page-all`,
|
||||
want: []string{"im", "+flag-list", "--page-all", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "short inline",
|
||||
raw: `lark-cli im +flag-list -q='.data.flag_items[-1]' --page-all`,
|
||||
want: []string{"im", "+flag-list", "--page-all", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "long inline",
|
||||
raw: `lark-cli im +flag-list --jq='.data.flag_items[-1]' --page-all`,
|
||||
want: []string{"im", "+flag-list", "--page-all", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "missing value remains invalid",
|
||||
raw: `lark-cli im +flag-list --page-all --jq`,
|
||||
want: []string{"im", "+flag-list", "--page-all", "--jq", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "next flag is not accepted as jq expression",
|
||||
raw: `lark-cli im +flag-list --jq --page-all`,
|
||||
want: []string{"im", "+flag-list", "--jq", "--page-all", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "invalid expression remains invalid",
|
||||
raw: `lark-cli im +flag-list --jq 'invalid[' --page-all`,
|
||||
want: []string{"im", "+flag-list", "--jq", "invalid[", "--page-all", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "incompatible pretty format remains invalid",
|
||||
raw: `lark-cli im +flag-list --jq '.data' --format pretty`,
|
||||
want: []string{"im", "+flag-list", "--jq", ".data", "--format", "pretty", "--dry-run"},
|
||||
},
|
||||
{
|
||||
name: "compatible json format preserves request preview",
|
||||
raw: `lark-cli im +flag-list --jq '.data' --format json`,
|
||||
want: []string{"im", "+flag-list", "--format", "json", "--dry-run"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := appendDryRunArg(tt.raw)
|
||||
if err != nil {
|
||||
t.Fatalf("appendDryRunArg() error = %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("appendDryRunArg() = %#v, want %#v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendDryRunArgPreservesNonPrettyFormat(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"lark-cli mail +watch --format data --dry-run",
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
qdiff "github.com/larksuite/cli/internal/qualitygate/diff"
|
||||
"github.com/larksuite/cli/internal/qualitygate/manifest"
|
||||
"github.com/larksuite/cli/internal/qualitygate/report"
|
||||
"github.com/larksuite/cli/internal/testutil/gitcmd"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
@@ -600,7 +600,8 @@ func TestNormalizeDiagnosticFileHandlesAbsoluteRepo(t *testing.T) {
|
||||
|
||||
func runGit(t *testing.T, repo string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", append([]string{"-c", "core.hooksPath=/dev/null", "-C", repo}, args...)...)
|
||||
commandArgs := append([]string{"-c", "core.hooksPath=/dev/null"}, args...)
|
||||
cmd := gitcmd.Command(repo, commandArgs...)
|
||||
cmd.Env = append(os.Environ(), "GIT_AUTHOR_DATE=2026-06-17T00:00:00Z", "GIT_COMMITTER_DATE=2026-06-17T00:00:00Z")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
|
||||
@@ -101,6 +101,7 @@ func TestSelectRecommendedScope_Empty(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestComputeMinimumScopeSet(t *testing.T) {
|
||||
ensureFreshRegistry(t)
|
||||
minSet := ComputeMinimumScopeSet("user")
|
||||
if len(minSet) == 0 {
|
||||
if len(ListFromMetaProjects()) == 0 {
|
||||
|
||||
72
internal/registry/registrytest/fixture_meta.json
Normal file
72
internal/registry/registrytest/fixture_meta.json
Normal file
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"services": [
|
||||
{
|
||||
"name": "calendar",
|
||||
"version": "v4",
|
||||
"title": "Calendar API",
|
||||
"servicePath": "/open-apis/calendar/v4",
|
||||
"resources": {
|
||||
"events": {
|
||||
"methods": {
|
||||
"create": {
|
||||
"path": "calendars/{calendar_id}/events",
|
||||
"httpMethod": "POST",
|
||||
"risk": "write",
|
||||
"scopes": [
|
||||
"calendar:calendar.event:create"
|
||||
],
|
||||
"parameters": {
|
||||
"calendar_id": {
|
||||
"type": "string",
|
||||
"location": "path",
|
||||
"required": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "im",
|
||||
"version": "v1",
|
||||
"title": "IM API",
|
||||
"servicePath": "/open-apis/im/v1",
|
||||
"resources": {
|
||||
"chat.members": {
|
||||
"methods": {
|
||||
"create": {
|
||||
"path": "chats/{chat_id}/members",
|
||||
"httpMethod": "POST",
|
||||
"risk": "write",
|
||||
"scopes": [
|
||||
"im:chat",
|
||||
"im:chat.members:write_only"
|
||||
],
|
||||
"parameters": {
|
||||
"chat_id": {
|
||||
"type": "string",
|
||||
"location": "path",
|
||||
"required": true
|
||||
},
|
||||
"member_id_type": {
|
||||
"type": "string",
|
||||
"location": "query",
|
||||
"required": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "task",
|
||||
"version": "v2",
|
||||
"title": "Task API",
|
||||
"servicePath": "/open-apis/task/v2",
|
||||
"resources": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
146
internal/registry/registrytest/registrytest.go
Normal file
146
internal/registry/registrytest/registrytest.go
Normal file
@@ -0,0 +1,146 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package registrytest seeds the registry with a tracked metadata fixture so
|
||||
// command-tree tests pass on a clean checkout — no `make fetch_meta`, no
|
||||
// network, no user cache. TestMain funcs of packages that build service
|
||||
// commands call Seed after redirecting LARKSUITE_CLI_CONFIG_DIR.
|
||||
package registrytest
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
// fixtureMetaJSON is a trimmed snapshot of the generated meta_data.json
|
||||
// holding only the calendar, im and task services that registry-backed tests
|
||||
// assert against. Its version is pinned to "0.0.1": newer than the empty
|
||||
// embedded stub ("0.0.0") so it wins on a clean checkout, older than any real
|
||||
// generated catalog ("1.0.0"+) so a `make fetch_meta` build keeps testing the
|
||||
// full embedded data.
|
||||
//
|
||||
//go:embed fixture_meta.json
|
||||
var fixtureMetaJSON []byte
|
||||
|
||||
// Seed writes fixtureMetaJSON into the registry remote-meta cache under
|
||||
// LARKSUITE_CLI_CONFIG_DIR and eagerly initializes the registry. testRoot must
|
||||
// be the temporary root created by the caller's TestMain; Seed rejects a config
|
||||
// directory outside it before performing any write. The cache
|
||||
// meta is stamped fresh so Init never sync-fetches or background-refreshes
|
||||
// over the network. Eager Init pins the catalog for the whole test process before
|
||||
// any individual test can re-point LARKSUITE_CLI_CONFIG_DIR elsewhere.
|
||||
//
|
||||
// The caller's TestMain must set LARKSUITE_CLI_CONFIG_DIR beneath testRoot
|
||||
// first; Seed refuses unset, mismatched, or escaping paths so it can never
|
||||
// write into a developer's real ~/.lark-cli.
|
||||
func Seed(testRoot string) error {
|
||||
configDir := os.Getenv("LARKSUITE_CLI_CONFIG_DIR")
|
||||
if err := validateConfigDir(testRoot, configDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var fixture struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err := json.Unmarshal(fixtureMetaJSON, &fixture); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cacheDir := filepath.Join(configDir, "cache")
|
||||
if err := vfs.MkdirAll(cacheDir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := vfs.WriteFile(filepath.Join(cacheDir, "remote_meta.json"), fixtureMetaJSON, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
cacheMeta, err := json.Marshal(registry.CacheMeta{
|
||||
LastCheckAt: time.Now().Unix(),
|
||||
Version: fixture.Version,
|
||||
Brand: string(core.BrandFeishu),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := vfs.WriteFile(filepath.Join(cacheDir, "remote_meta.meta.json"), cacheMeta, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Neutralize ambient knobs that would defeat the seeding: an inherited
|
||||
// LARKSUITE_CLI_REMOTE_META=off would stop Init from reading the seeded
|
||||
// cache at all, and LARKSUITE_CLI_META_TTL=0 would expire the freshness
|
||||
// stamp and start a background network refresh from inside unit tests.
|
||||
if err := os.Unsetenv("LARKSUITE_CLI_REMOTE_META"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Unsetenv("LARKSUITE_CLI_META_TTL"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
registry.Init()
|
||||
|
||||
// Init is a sync.Once, so the seed is pinned for the whole test process.
|
||||
// Turning remote metadata off afterwards cannot un-seed anything; it is a
|
||||
// guard for any future post-Init code path that might consult the remote
|
||||
// cache again after a test re-points LARKSUITE_CLI_CONFIG_DIR elsewhere.
|
||||
if err := os.Setenv("LARKSUITE_CLI_REMOTE_META", "off"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Self-check: both the fixture and any real generated catalog contain the
|
||||
// im service. If it is missing, the cache seeding silently stopped working
|
||||
// (e.g. the registry cache file names or freshness semantics changed) and
|
||||
// every registry-backed test would fail confusingly — fail loudly here
|
||||
// instead, pointing at this package.
|
||||
merged, ok := registry.ServiceTyped("im")
|
||||
if !ok {
|
||||
return errors.New("registrytest.Seed: registry has no im service after seeding — " +
|
||||
"the remote-cache format in internal/registry/remote.go may have changed; update registrytest to match")
|
||||
}
|
||||
|
||||
// Self-check: on a fetch_meta build the real embedded catalog must win over
|
||||
// the 0.0.1 fixture. If the merged im service diverges from the embedded
|
||||
// one, the version arbitration flipped (e.g. the generated catalog version
|
||||
// stopped parsing as semver) and unit tests would silently run against the
|
||||
// stale trimmed fixture instead of the fresh catalog.
|
||||
for _, service := range registry.EmbeddedServicesTyped() {
|
||||
if service.Name != "im" {
|
||||
continue
|
||||
}
|
||||
if service.Version != merged.Version {
|
||||
return errors.New("registrytest.Seed: the fixture shadowed the real embedded catalog — " +
|
||||
"check the meta_data.json version against the fixture's \"0.0.1\" arbitration in this package")
|
||||
}
|
||||
break
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateConfigDir guards the one real hazard: a TestMain wiring mistake
|
||||
// pointing LARKSUITE_CLI_CONFIG_DIR at a developer's real directory. Both
|
||||
// paths come from the caller's own MkdirTemp, so a plain containment check
|
||||
// is enough.
|
||||
func validateConfigDir(testRoot, configDir string) error {
|
||||
if testRoot == "" || configDir == "" {
|
||||
return errors.New("registrytest.Seed: test root and config dir must be set")
|
||||
}
|
||||
if !filepath.IsAbs(testRoot) || !filepath.IsAbs(configDir) {
|
||||
return errors.New("registrytest.Seed: test root and config dir must be absolute")
|
||||
}
|
||||
rel, err := filepath.Rel(filepath.Clean(testRoot), filepath.Clean(configDir))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return errors.New("registrytest.Seed: config dir must stay inside the test root")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
229
internal/registry/registrytest/registrytest_test.go
Normal file
229
internal/registry/registrytest/registrytest_test.go
Normal file
@@ -0,0 +1,229 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package registrytest
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/meta"
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
)
|
||||
|
||||
func TestValidateConfigDir(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
tests := []struct {
|
||||
name string
|
||||
testRoot string
|
||||
configDir string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "equal", testRoot: root, configDir: root},
|
||||
{name: "child", testRoot: root, configDir: filepath.Join(root, "config")},
|
||||
{
|
||||
name: "sibling",
|
||||
testRoot: root,
|
||||
configDir: filepath.Join(filepath.Dir(root), "outside"),
|
||||
wantErr: true,
|
||||
},
|
||||
{name: "empty root", configDir: root, wantErr: true},
|
||||
{name: "empty config", testRoot: root, wantErr: true},
|
||||
{name: "relative root", testRoot: "relative", configDir: root, wantErr: true},
|
||||
{name: "relative config", testRoot: root, configDir: "relative", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateConfigDir(tt.testRoot, tt.configDir)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("validateConfigDir() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixtureContract(t *testing.T) {
|
||||
if len(fixtureMetaJSON) > 20<<10 {
|
||||
t.Fatalf("fixture size = %d, want <= %d", len(fixtureMetaJSON), 20<<10)
|
||||
}
|
||||
reg, err := meta.Parse(fixtureMetaJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("meta.Parse() error = %v", err)
|
||||
}
|
||||
if reg.Version != "0.0.1" {
|
||||
t.Fatalf("fixture version = %q, want 0.0.1", reg.Version)
|
||||
}
|
||||
|
||||
gotNames := make([]string, 0, len(reg.Services))
|
||||
for _, service := range reg.Services {
|
||||
gotNames = append(gotNames, service.Name)
|
||||
}
|
||||
sort.Strings(gotNames)
|
||||
if !slices.Equal(gotNames, []string{"calendar", "im", "task"}) {
|
||||
t.Fatalf("fixture services = %v, want [calendar im task]", gotNames)
|
||||
}
|
||||
|
||||
calendarCreate := fixtureMethod(t, reg, "calendar", "events", "create")
|
||||
assertMethodContract(t, calendarCreate, "calendars/{calendar_id}/events", http.MethodPost)
|
||||
calendarID, ok := calendarCreate.Parameters["calendar_id"]
|
||||
if !ok || calendarID.Location != "path" || !calendarID.Required {
|
||||
t.Fatalf("calendar_id = %+v, want required path parameter", calendarID)
|
||||
}
|
||||
if !slices.Contains(calendarCreate.Scopes, "calendar:calendar.event:create") {
|
||||
t.Fatalf("calendar create scopes = %v, want calendar:calendar.event:create", calendarCreate.Scopes)
|
||||
}
|
||||
|
||||
imCreate := fixtureMethod(t, reg, "im", "chat.members", "create")
|
||||
assertMethodContract(t, imCreate, "chats/{chat_id}/members", http.MethodPost)
|
||||
chatID, ok := imCreate.Parameters["chat_id"]
|
||||
if !ok || chatID.Location != "path" || !chatID.Required {
|
||||
t.Fatalf("chat_id = %+v, want required path parameter", chatID)
|
||||
}
|
||||
memberIDType, ok := imCreate.Parameters["member_id_type"]
|
||||
if !ok || memberIDType.Location != "query" || memberIDType.Required {
|
||||
t.Fatalf("member_id_type = %+v, want optional query parameter", memberIDType)
|
||||
}
|
||||
if imCreate.Risk != "write" {
|
||||
t.Fatalf("im create risk = %q, want write", imCreate.Risk)
|
||||
}
|
||||
for _, scope := range []string{"im:chat", "im:chat.members:write_only"} {
|
||||
if !slices.Contains(imCreate.Scopes, scope) {
|
||||
t.Fatalf("im create scopes = %v, want %s", imCreate.Scopes, scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fixtureMethod(t *testing.T, reg meta.Registry, serviceName, resourceName, methodName string) meta.Method {
|
||||
t.Helper()
|
||||
for _, service := range reg.Services {
|
||||
if service.Name != serviceName {
|
||||
continue
|
||||
}
|
||||
resource, ok := service.Resource(resourceName)
|
||||
if !ok {
|
||||
t.Fatalf("fixture service %s has no resource %s", serviceName, resourceName)
|
||||
}
|
||||
method, ok := resource.Method(methodName)
|
||||
if !ok {
|
||||
t.Fatalf("fixture resource %s.%s has no method %s", serviceName, resourceName, methodName)
|
||||
}
|
||||
return method
|
||||
}
|
||||
t.Fatalf("fixture has no service %s", serviceName)
|
||||
return meta.Method{}
|
||||
}
|
||||
|
||||
func assertMethodContract(t *testing.T, method meta.Method, path, httpMethod string) {
|
||||
t.Helper()
|
||||
if method.Path != path || method.HTTPMethod != httpMethod {
|
||||
t.Fatalf("method = %s %s, want %s %s", method.HTTPMethod, method.Path, httpMethod, path)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeedRejectsUnsafeConfigDir pins Seed's guard: it must return before
|
||||
// writing anything when LARKSUITE_CLI_CONFIG_DIR is unset or escapes the
|
||||
// caller's test root, so a TestMain wiring mistake can never touch a
|
||||
// developer's real ~/.lark-cli.
|
||||
func TestSeedRejectsUnsafeConfigDir(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
|
||||
t.Run("unset config dir", func(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", "")
|
||||
if err := Seed(root); err == nil {
|
||||
t.Fatal("Seed() error = nil, want unset config dir rejection")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config dir outside test root", func(t *testing.T) {
|
||||
outside := t.TempDir()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", outside)
|
||||
if err := Seed(root); err == nil {
|
||||
t.Fatal("Seed() error = nil, want containment rejection")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(outside, "cache")); err == nil {
|
||||
t.Fatal("Seed wrote into the rejected config dir")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestSeedWritesFixtureAndInitializesRegistry covers the seeding happy path:
|
||||
// cache files land under the config dir, the registry initializes from them,
|
||||
// and both self-checks pass.
|
||||
func TestSeedWritesFixtureAndInitializesRegistry(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
configDir := filepath.Join(root, "config")
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", configDir)
|
||||
|
||||
if err := Seed(root); err != nil {
|
||||
t.Fatalf("Seed() error = %v, want nil", err)
|
||||
}
|
||||
for _, name := range []string{"remote_meta.json", "remote_meta.meta.json"} {
|
||||
if _, err := os.Stat(filepath.Join(configDir, "cache", name)); err != nil {
|
||||
t.Errorf("cache file %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
if got := os.Getenv("LARKSUITE_CLI_REMOTE_META"); got != "off" {
|
||||
t.Errorf("LARKSUITE_CLI_REMOTE_META = %q, want off after seeding", got)
|
||||
}
|
||||
for _, service := range []string{"calendar", "im", "task"} {
|
||||
if _, ok := registry.ServiceTyped(service); !ok {
|
||||
t.Errorf("registry missing service %s after seeding", service)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeedPropagatesCacheSetupFailures pins that filesystem failures while
|
||||
// materializing the cache surface as errors instead of leaving the registry
|
||||
// silently unseeded. Each obstacle is a same-named file/directory in the
|
||||
// way, which fails on every platform without permission tricks.
|
||||
func TestSeedPropagatesCacheSetupFailures(t *testing.T) {
|
||||
seedWith := func(t *testing.T, prepare func(root, configDir string)) error {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
configDir := filepath.Join(root, "config")
|
||||
prepare(root, configDir)
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", configDir)
|
||||
return Seed(root)
|
||||
}
|
||||
|
||||
t.Run("cache dir creation fails", func(t *testing.T) {
|
||||
err := seedWith(t, func(root, configDir string) {
|
||||
// config is a regular file, so MkdirAll(config/cache) fails.
|
||||
if err := os.WriteFile(configDir, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Seed() error = nil, want cache dir creation failure")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fixture write fails", func(t *testing.T) {
|
||||
err := seedWith(t, func(root, configDir string) {
|
||||
// remote_meta.json is a directory, so WriteFile fails.
|
||||
if err := os.MkdirAll(filepath.Join(configDir, "cache", "remote_meta.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Seed() error = nil, want fixture write failure")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cache meta write fails", func(t *testing.T) {
|
||||
err := seedWith(t, func(root, configDir string) {
|
||||
// remote_meta.meta.json is a directory, so WriteFile fails.
|
||||
if err := os.MkdirAll(filepath.Join(configDir, "cache", "remote_meta.meta.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Seed() error = nil, want cache meta write failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
27
internal/registry/testmain_test.go
Normal file
27
internal/registry/testmain_test.go
Normal file
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package registry
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
root, err := os.MkdirTemp("", "lark-cli-registry-test-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.Setenv("LARKSUITE_CLI_CONFIG_DIR", filepath.Join(root, "config")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
code := m.Run()
|
||||
// A test that ran Init without a trailing resetInit can leave a background
|
||||
// refresh goroutine alive; removing the temp root while it writes would
|
||||
// let it recreate the directory after cleanup. Wait it out first.
|
||||
waitBackgroundRefresh()
|
||||
_ = os.RemoveAll(root)
|
||||
os.Exit(code)
|
||||
}
|
||||
55
internal/testutil/gitcmd/gitcmd.go
Normal file
55
internal/testutil/gitcmd/gitcmd.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package gitcmd provides Git process helpers for tests that use temporary
|
||||
// repositories.
|
||||
package gitcmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
maintenanceAutoDetach = "maintenance.autoDetach"
|
||||
gcAutoDetach = "gc.autoDetach"
|
||||
)
|
||||
|
||||
// Command creates a Git command whose automatic maintenance stays in the
|
||||
// command lifecycle, so temporary repository cleanup cannot race a detached
|
||||
// maintenance process.
|
||||
func Command(dir string, args ...string) *exec.Cmd {
|
||||
commandArgs := make([]string, 0, len(args)+4)
|
||||
commandArgs = append(commandArgs,
|
||||
"-c", maintenanceAutoDetach+"=false",
|
||||
"-c", gcAutoDetach+"=false",
|
||||
)
|
||||
commandArgs = append(commandArgs, args...)
|
||||
cmd := exec.Command("git", commandArgs...)
|
||||
cmd.Dir = dir
|
||||
return cmd
|
||||
}
|
||||
|
||||
// SetSynchronousMaintenanceEnv applies the same lifecycle contract to every
|
||||
// Git process started by the current test, including processes created through
|
||||
// production command runners. Tests using it must not run in parallel.
|
||||
func SetSynchronousMaintenanceEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
count := 0
|
||||
if value, ok := os.LookupEnv("GIT_CONFIG_COUNT"); ok {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed < 0 {
|
||||
t.Fatalf("invalid GIT_CONFIG_COUNT %q", value)
|
||||
}
|
||||
count = parsed
|
||||
}
|
||||
for _, key := range []string{maintenanceAutoDetach, gcAutoDetach} {
|
||||
index := strconv.Itoa(count)
|
||||
t.Setenv("GIT_CONFIG_KEY_"+index, key)
|
||||
t.Setenv("GIT_CONFIG_VALUE_"+index, "false")
|
||||
count++
|
||||
}
|
||||
t.Setenv("GIT_CONFIG_COUNT", strconv.Itoa(count))
|
||||
}
|
||||
47
internal/testutil/gitcmd/gitcmd_test.go
Normal file
47
internal/testutil/gitcmd/gitcmd_test.go
Normal file
@@ -0,0 +1,47 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package gitcmd
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCommandDisablesDetachedMaintenance(t *testing.T) {
|
||||
for _, key := range []string{"maintenance.autoDetach", "gc.autoDetach"} {
|
||||
cmd := Command(t.TempDir(), "config", "--get", "--type=bool", key)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git config %s: %v\n%s", key, err, out)
|
||||
}
|
||||
if got := strings.TrimSpace(string(out)); got != "false" {
|
||||
t.Fatalf("%s = %q, want false", key, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetSynchronousMaintenanceEnv(t *testing.T) {
|
||||
t.Setenv("GIT_CONFIG_COUNT", "1")
|
||||
t.Setenv("GIT_CONFIG_KEY_0", "user.name")
|
||||
t.Setenv("GIT_CONFIG_VALUE_0", "Existing Test User")
|
||||
SetSynchronousMaintenanceEnv(t)
|
||||
for key, want := range map[string]string{
|
||||
"user.name": "Existing Test User",
|
||||
maintenanceAutoDetach: "false",
|
||||
gcAutoDetach: "false",
|
||||
} {
|
||||
cmd := exec.Command("git", "config", "--get", "--type=bool", key)
|
||||
if key == "user.name" {
|
||||
cmd = exec.Command("git", "config", "--get", key)
|
||||
}
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git config %s: %v\n%s", key, err, out)
|
||||
}
|
||||
if got := strings.TrimSpace(string(out)); got != want {
|
||||
t.Fatalf("%s = %q, want %q", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,12 @@ func writeFixture(t *testing.T, files fixtureRepo) string {
|
||||
|
||||
func runGit(t *testing.T, root string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
commandArgs := []string{
|
||||
"-c", "maintenance.autoDetach=false",
|
||||
"-c", "gc.autoDetach=false",
|
||||
}
|
||||
commandArgs = append(commandArgs, args...)
|
||||
cmd := exec.Command("git", commandArgs...)
|
||||
cmd.Dir = root
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
@@ -43,6 +48,14 @@ func runGit(t *testing.T, root string, args ...string) string {
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
|
||||
func TestRunGitDisablesDetachedMaintenance(t *testing.T) {
|
||||
for _, key := range []string{"maintenance.autoDetach", "gc.autoDetach"} {
|
||||
if got := runGit(t, t.TempDir(), "config", "--get", "--type=bool", key); got != "false" {
|
||||
t.Fatalf("%s = %q, want false", key, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSubtypeAllowlist_ExtractsTypedConstValues(t *testing.T) {
|
||||
root := writeFixture(t, fixtureRepo{
|
||||
"errs/subtypes.go": `package errs
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@larksuite/cli",
|
||||
"version": "1.0.72",
|
||||
"version": "1.0.74",
|
||||
"description": "The official CLI for Lark/Feishu open platform",
|
||||
"bin": {
|
||||
"lark-cli": "scripts/run.js"
|
||||
|
||||
469
shortcuts/apps/apps_automation_skill_contract_test.go
Normal file
469
shortcuts/apps/apps_automation_skill_contract_test.go
Normal file
@@ -0,0 +1,469 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const automationSkillDoc = "../../skills/lark-apps/references/lark-apps-automation.md"
|
||||
const localDevSkillDoc = "../../skills/lark-apps/references/lark-apps-local-dev.md"
|
||||
const larkAppsSkillDoc = "../../skills/lark-apps/SKILL.md"
|
||||
const releaseGetSkillDoc = "../../skills/lark-apps/references/lark-apps-release-get.md"
|
||||
|
||||
func readAutomationSkillDoc(t *testing.T) string {
|
||||
return readAppsSkillDoc(t, automationSkillDoc)
|
||||
}
|
||||
|
||||
func readLocalDevSkillDoc(t *testing.T) string {
|
||||
return readAppsSkillDoc(t, localDevSkillDoc)
|
||||
}
|
||||
|
||||
func readReleaseGetSkillDoc(t *testing.T) string {
|
||||
return readAppsSkillDoc(t, releaseGetSkillDoc)
|
||||
}
|
||||
|
||||
func readAppsSkillDoc(t *testing.T, path string) string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read skill doc %s: %v", path, err)
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
func skillSection(t *testing.T, doc, heading string) string {
|
||||
t.Helper()
|
||||
start := strings.Index(doc, heading)
|
||||
if start < 0 {
|
||||
t.Fatalf("missing skill section %q", heading)
|
||||
}
|
||||
rest := doc[start+len(heading):]
|
||||
if next := strings.Index(rest, "\n## "); next >= 0 {
|
||||
return rest[:next]
|
||||
}
|
||||
return rest
|
||||
}
|
||||
|
||||
func skillSubsection(t *testing.T, doc, heading string) string {
|
||||
t.Helper()
|
||||
start := strings.Index(doc, heading)
|
||||
if start < 0 {
|
||||
t.Fatalf("missing skill subsection %q", heading)
|
||||
}
|
||||
rest := doc[start+len(heading):]
|
||||
end := len(rest)
|
||||
for _, marker := range []string{"\n### ", "\n## "} {
|
||||
if next := strings.Index(rest, marker); next >= 0 && next < end {
|
||||
end = next
|
||||
}
|
||||
}
|
||||
return rest[:end]
|
||||
}
|
||||
|
||||
func requireInOrder(t *testing.T, text string, tokens ...string) {
|
||||
t.Helper()
|
||||
offset := 0
|
||||
for _, token := range tokens {
|
||||
idx := strings.Index(text[offset:], token)
|
||||
if idx < 0 {
|
||||
t.Fatalf("missing %q after %q", token, text[:offset])
|
||||
}
|
||||
offset += idx + len(token)
|
||||
}
|
||||
}
|
||||
|
||||
func requireFirstOccurrencesInOrder(t *testing.T, text string, tokens ...string) {
|
||||
t.Helper()
|
||||
previous := -1
|
||||
for _, token := range tokens {
|
||||
idx := strings.Index(text, token)
|
||||
if idx < 0 {
|
||||
t.Fatalf("missing %q", token)
|
||||
}
|
||||
if idx <= previous {
|
||||
t.Fatalf("first %q at %d must follow the previous contract token at %d", token, idx, previous)
|
||||
}
|
||||
previous = idx
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_ChangedHandlerStartWaitsForThisRelease(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 实现或更新 handler 后发布并启动/测试")
|
||||
|
||||
requireInOrder(t, section,
|
||||
"仅当本轮确实需要新增或修改 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` handler",
|
||||
"+automation-get",
|
||||
"记录发布前状态",
|
||||
"--name",
|
||||
"项目 guide",
|
||||
"按项目 guide 完成同名业务 handler 并本地验证。",
|
||||
"在 Git 已确认/预授权时 commit,然后执行",
|
||||
"git push origin sprint/default",
|
||||
"临时停用授权",
|
||||
"+automation-disable",
|
||||
"确认 disabled",
|
||||
"+release-create --branch sprint/default",
|
||||
"data.release_id",
|
||||
"+release-get",
|
||||
"data.status=finished",
|
||||
"仅启动",
|
||||
"+automation-enable",
|
||||
"+automation-get",
|
||||
"不制造 runtime probe",
|
||||
"测试",
|
||||
"运行时验证的操作级授权",
|
||||
"完成全部 preflight",
|
||||
"才执行 `+automation-enable`",
|
||||
"真实 runtime",
|
||||
"仅要求测试",
|
||||
"恢复到发布前状态",
|
||||
)
|
||||
requireFirstOccurrencesInOrder(t, section,
|
||||
"+automation-get",
|
||||
"git push origin sprint/default",
|
||||
"临时停用授权",
|
||||
"+automation-disable",
|
||||
"+release-create --branch sprint/default",
|
||||
"data.status=finished",
|
||||
"仅启动",
|
||||
)
|
||||
for _, boundary := range []string{
|
||||
"仅当本轮确实需要新增或修改 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` handler,且用户要求把这次代码发布后启动或测试时,才使用此路径。",
|
||||
"按项目 guide 完成同名业务 handler 并本地验证。",
|
||||
"在 Git 已确认/预授权时 commit,然后执行 `git push origin sprint/default`。",
|
||||
"若该命令本身返回错误或未返回 `data.release_id`:视为确认未创建本轮 release(新代码未上线),原本 enabled 的 trigger 恢复 enabled 并回读、原本 disabled 的保持 disabled 后停止;若因超时等导致结果未知,保持 disabled,先用 `+release-list --status finished --page-size 1` 核对是否已产生新 release 再决定。",
|
||||
"只有 `data.status=finished` 才能继续;`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟。",
|
||||
"确认 `failed` 时报告发布失败,原本 enabled 的 trigger 仅在确认新代码未上线后恢复 enabled,原本 disabled 的保持 disabled。",
|
||||
"发布状态仍不确定时不得进入 enable、probe 或状态恢复分支。",
|
||||
"**仅启动**:取得持续启动授权后执行 `+automation-enable`,并用 `+automation-get` 确认 enabled;到此结束,不制造 runtime probe。",
|
||||
"**测试(含“启动并测试”)**:先按下节“运行时验证的操作级授权”完成全部 preflight",
|
||||
"若用户仅要求测试而不是持续启动,只在本轮 release 已 `finished` 且 probe 成功后恢复到发布前状态",
|
||||
"无论用户是仅测试还是启动并测试,probe 失败、结果不确定或 enable 后提前结束时,一律 `+automation-disable` 并回读 disabled",
|
||||
"不得把“发布前 enabled”当作失败后的恢复依据",
|
||||
"没有通用的 `automation-debug` 或 trigger 日志 shortcut。",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("complete-start section must explain %q boundary", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_BindsTheExactNameAsUser(t *testing.T) {
|
||||
doc := readAutomationSkillDoc(t)
|
||||
for _, boundary := range []string{
|
||||
"全部操作需 `--as user`(AuthType: user)。",
|
||||
"当用户希望触发器实际执行业务代码时,先确认当前工作区是已初始化的应用项目,并读取其中与触发器任务匹配的 guide。",
|
||||
"`--name` 是应用内唯一的 trigger 定位键;代码侧绑定名称必须与它逐字相同。不得用 trigger ID 或方法名代替它。具体 handler 语法和接入方式以项目 guide 为准。",
|
||||
} {
|
||||
if !strings.Contains(doc, boundary) {
|
||||
t.Errorf("automation skill must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_RoutesAndDiagnosesUnfiredTriggers(t *testing.T) {
|
||||
doc := readAutomationSkillDoc(t)
|
||||
routeSection := skillSection(t, doc, "## 何时用本 skill(路由锚点)")
|
||||
errorSection := skillSection(t, doc, "## 常见错误与决策场景")
|
||||
|
||||
if !strings.Contains(routeSection, "「触发器没反应 / enable 了不触发 / 为什么没执行 / 验证一下触发器」→ 先按「未触发时的诊断顺序」诊断;对 UPSERT 和 feishu-approval 仅验证配置边界,不承诺 handler 或 live 验证。") {
|
||||
t.Error("routing anchors must direct unfired triggers to the bounded diagnostic flow")
|
||||
}
|
||||
if !strings.Contains(errorSection, "已证实的 cron、webhook、record-change(INSERT/UPDATE/DELETE)按「未触发时的诊断顺序」排查;UPSERT 和 feishu-approval 仅核对配置边界,不承诺 handler 或 live 验证。") {
|
||||
t.Error("error table must preserve the bounded unfired-trigger diagnostic flow")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_ConfigurationStopsDisabled(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 仅创建/配置触发器")
|
||||
|
||||
for _, boundary := range []string{
|
||||
"用 `+automation-create` 创建,并省略 `--status` 或显式传 `disabled`,然后报告 name 和 disabled 状态。",
|
||||
"不要传 `--status enabled`,也不要写 handler、commit/push、release 或 enable;更不能把创建 API 成功称为“可运行”。",
|
||||
"默认 disabled 是这个意图的终点,不是稍后自动 enable 的待办。",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("configuration-only section must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_EnableExistingTriggerDoesNotPublish(t *testing.T) {
|
||||
doc := readAutomationSkillDoc(t)
|
||||
section := skillSubsection(t, doc, "### 仅启用已有 disabled trigger")
|
||||
routeSection := skillSection(t, doc, "## 何时用本 skill(路由锚点)")
|
||||
|
||||
requireInOrder(t, section,
|
||||
"用户只要求启用已存在且 disabled 的 trigger",
|
||||
"+automation-get",
|
||||
"+release-list --status finished --page-size 1",
|
||||
"已完成线上 release",
|
||||
"当前线上应用",
|
||||
"不能证明该 trigger name 已绑定 handler",
|
||||
"+automation-enable",
|
||||
"+automation-get",
|
||||
"不得修改 handler、commit/push 或 release",
|
||||
"对 UPSERT 或 feishu-approval 只改变配置状态",
|
||||
)
|
||||
if !strings.Contains(section, "未发布时不得自动创建 release,也不得声称 trigger 已开始实际运行") {
|
||||
t.Error("enable-only flow must distinguish configuration enablement from a published runtime")
|
||||
}
|
||||
if !strings.Contains(section, "即使存在 finished release,也只能把 enable 报告为配置激活") {
|
||||
t.Error("enable-only flow must not infer handler provenance from app release history")
|
||||
}
|
||||
if strings.Contains(section, "apps +get") || strings.Contains(section, "`is_published`") {
|
||||
t.Error("enable-only flow must use finished release history instead of an optional app detail field")
|
||||
}
|
||||
for _, forbidden := range []string{"git push", "+release-create"} {
|
||||
if strings.Contains(section, forbidden) {
|
||||
t.Errorf("enable-only flow must not contain %q", forbidden)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(routeSection, "「启用 / 启动已有 trigger」→ 先核对现有状态;只启用时不要修改源码或发布应用。") {
|
||||
t.Error("routing anchors must keep existing-trigger enablement separate from code release")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_TestExistingTriggerDoesNotPublish(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 测试已有线上 trigger(不改代码)")
|
||||
|
||||
requireInOrder(t, section,
|
||||
"用户要求测试已经发布的 trigger",
|
||||
"+automation-get",
|
||||
"+release-list --status finished --page-size 1",
|
||||
"当前线上代码",
|
||||
"不得为测试自动修改源码、commit/push 或 release",
|
||||
"在任何临时 enable 之前完成",
|
||||
"测试请求已明确包含临时 enable,或另行取得 enable 授权",
|
||||
"运行时验证的操作级授权",
|
||||
"无论 probe 成功、失败、结果不确定,还是临时 enable 后提前结束或中断,最终都必须 `+automation-disable` 并回读 disabled",
|
||||
)
|
||||
for _, forbidden := range []string{"git push", "+release-create"} {
|
||||
if strings.Contains(section, forbidden) {
|
||||
t.Errorf("existing-trigger test flow must not contain %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_HandlerOnlyStopsBeforeRelease(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 仅完成 handler(不发布/不启用)")
|
||||
|
||||
for _, boundary := range []string{
|
||||
"创建或定位已明确 name 的 disabled trigger,读取项目 guide,按其要求实现同名业务 handler,完成本地验证。",
|
||||
"只在既有 Git 确认或预授权下 commit/push;停止在 `+release-create` 和 `+automation-enable` 之前。",
|
||||
"用户没有明确“发布好”时,先问,不能默认把完整应用上线。",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("handler-only section must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_HandlerOnlyExcludesUnverifiedRuntimeTypes(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 仅完成 handler(不发布/不启用)")
|
||||
|
||||
if !strings.Contains(section, "仅对 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` 使用此路径。") {
|
||||
t.Error("handler-only flow must exclude UPSERT and feishu-approval without a verified runtime contract")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_PublishedHandlerStaysDisabled(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 把 handler 发布好,但先不要启动")
|
||||
|
||||
for _, boundary := range []string{
|
||||
"仅对 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` 使用此路径。",
|
||||
"先用 `+automation-get` 定位;不存在时用 `+automation-create` 创建同名 disabled trigger,再次回读确认。",
|
||||
"已存在时记录它是否 enabled。",
|
||||
"若 trigger 已 enabled,先说明发布前必须临时停用以及可能造成的运行中断,并取得这次临时停用授权;未获授权时停止在发布前。",
|
||||
"取得授权后,在发布前执行 `+automation-disable`,并再次用 `+automation-get` 确认 disabled。",
|
||||
"按项目 guide 完成同名业务 handler 并本地验证后,commit、`git push origin sprint/default`。",
|
||||
"随后发布完整应用:",
|
||||
"若 `+release-create` 本身返回错误或未返回 `data.release_id`:视为确认未创建本轮 release(新代码未上线),原本 enabled 的 trigger 恢复 enabled 并回读、原本 disabled 的保持 disabled,然后停止;若因超时等导致创建结果未知,保持 disabled,先用 `+release-list --status finished --page-size 1` 核对是否已产生新 release 再决定。",
|
||||
"取得 `data.release_id` 后,对**这一轮** ID 调用 `+release-get`:`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟;超时且状态仍不确定时报告 `release_id` 和当前 status,并保持 disabled;只有 `data.status=finished` 才算完成。",
|
||||
"确认 `failed` 且新代码未上线时,原本 enabled 的 trigger 恢复 enabled 并回读,原本 disabled 的保持 disabled。",
|
||||
"release 是整个应用上线,可能影响既有线上功能;未获得启动或测试授权时,finished 后始终保持 disabled,不执行 `+automation-enable`。",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("publish-without-start section must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
requireFirstOccurrencesInOrder(t, section,
|
||||
"+automation-get",
|
||||
"git push origin sprint/default",
|
||||
"临时停用授权",
|
||||
"+automation-disable",
|
||||
"+release-create",
|
||||
)
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_UPSERTAndApprovalStayConfigurationOnly(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### UPSERT 与飞书审批边界")
|
||||
|
||||
for _, boundary := range []string{
|
||||
"record-change 的 UPSERT 可创建 disabled 配置,但当前没有已证实的运行时代码契约;不得静默按 UPDATE 处理,也不得承诺 handler 或 live 验证。",
|
||||
"feishu-approval 可创建 disabled 配置,并读取或更新 `event_type`、对应 status 和可选 `approval_code`。",
|
||||
"当前没有已证实的运行时 handler 契约或实际投递验证;不要把 enable 或审批 API 成功称为业务代码已执行。",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("UPSERT/approval boundary section must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_RuntimeProbeRequiresOperationScope(t *testing.T) {
|
||||
section := skillSubsection(t, readAutomationSkillDoc(t), "### 运行时验证的操作级授权")
|
||||
|
||||
for _, boundary := range []string{
|
||||
"启用 trigger 的授权不等于制造 runtime 事件的授权,测试授权也不等于任意数据库写入授权。",
|
||||
"record-change 在执行任何 DML 前,必须明确并取得覆盖以下作用域的授权",
|
||||
"环境、表、操作、精确测试记录或筛选条件、payload、预期结果和清理方式",
|
||||
"优先使用专用测试记录",
|
||||
"`DELETE`",
|
||||
"[lark-apps-db-execute.md](lark-apps-db-execute.md)",
|
||||
"先 `SELECT count(*)`、执行 `--dry-run`",
|
||||
"取得针对该删除目标的明确授权",
|
||||
"+automation-list --trigger-type record-change --all",
|
||||
"同一环境、表和操作可能命中的其他 enabled trigger",
|
||||
"聚合业务影响",
|
||||
"恢复 UPDATE 或清理 INSERT 也可能再次触发自动化",
|
||||
"缺少安全、已授权且可清理的事件入口时,记录 blocked",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("runtime probe section must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSkillContract_UsesResolvableSharedSkillLink(t *testing.T) {
|
||||
doc := readAutomationSkillDoc(t)
|
||||
|
||||
if strings.Contains(doc, "](../lark-shared/SKILL.md)") {
|
||||
t.Error("automation reference must not resolve lark-shared inside the lark-apps directory")
|
||||
}
|
||||
if !strings.Contains(doc, "](../../lark-shared/SKILL.md)") {
|
||||
t.Error("automation reference must link to the sibling lark-shared skill")
|
||||
}
|
||||
sharedSkillDoc := filepath.Clean(filepath.Join(filepath.Dir(automationSkillDoc), "../../lark-shared/SKILL.md"))
|
||||
if _, err := os.Stat(sharedSkillDoc); err != nil {
|
||||
t.Fatalf("automation reference target %s must exist: %v", sharedSkillDoc, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsSkillContract_AllSharedSkillLinksResolve(t *testing.T) {
|
||||
docs := []string{larkAppsSkillDoc}
|
||||
references, err := filepath.Glob("../../skills/lark-apps/references/*.md")
|
||||
if err != nil {
|
||||
t.Fatalf("glob lark-apps references: %v", err)
|
||||
}
|
||||
docs = append(docs, references...)
|
||||
sharedLink := regexp.MustCompile(`\]\(([^)]+lark-shared/SKILL\.md)\)`)
|
||||
|
||||
for _, docPath := range docs {
|
||||
doc := readAppsSkillDoc(t, docPath)
|
||||
for _, match := range sharedLink.FindAllStringSubmatch(doc, -1) {
|
||||
target := filepath.Clean(filepath.Join(filepath.Dir(docPath), match[1]))
|
||||
if _, err := os.Stat(target); err != nil {
|
||||
t.Errorf("%s shared-skill link %q resolves to missing target %s: %v", docPath, match[1], target, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDevSkillContract_UsesProjectGuideWithoutSyncInternals(t *testing.T) {
|
||||
section := skillSection(t, readLocalDevSkillDoc(t), "## Trigger guide 的项目边界")
|
||||
|
||||
for _, boundary := range []string{
|
||||
"先查看工作区 `.agents/skills/`,读取与自动化任务匹配的 `trigger-guide`。",
|
||||
"文件缺失或不能覆盖当前任务时,报告项目缺少可用的领域 guide;不要在本 lark-cli reference 中猜测安装命令、版本或包内目录。",
|
||||
} {
|
||||
if !strings.Contains(section, boundary) {
|
||||
t.Errorf("trigger-guide boundary section must explain %q", boundary)
|
||||
}
|
||||
}
|
||||
for _, implementationShape := range []string{
|
||||
"npx ", "skills sync", "data.", "skills_", "_CACHE_DIR", "nestjs-",
|
||||
"@lark-apaas/miaoda-cli", "@lark-apaas/coding-steering", "miaoda-coding", "skills_common/",
|
||||
} {
|
||||
if strings.Contains(section, implementationShape) {
|
||||
t.Errorf("local-dev skill must not expose project-sync implementation shape %q", implementationShape)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsSkillContract_DoesNotExposeSteeringImplementation(t *testing.T) {
|
||||
for name, doc := range map[string]string{
|
||||
"automation": readAutomationSkillDoc(t),
|
||||
"local-dev": readLocalDevSkillDoc(t),
|
||||
} {
|
||||
for _, implementationShape := range []string{
|
||||
"npx ", "skills sync", "@lark-apaas/miaoda-cli", "@lark-apaas/coding-steering", "miaoda-coding", "skills_common/",
|
||||
} {
|
||||
if strings.Contains(doc, implementationShape) {
|
||||
t.Errorf("%s skill must not expose project-sync implementation shape %q", name, implementationShape)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDevSkillContract_UsesEnvironmentAndDefersEnableToAutomationSOP(t *testing.T) {
|
||||
doc := readLocalDevSkillDoc(t)
|
||||
releaseSection := skillSection(t, doc, "## 改完代码后部署上线")
|
||||
for _, legacy := range []string{"--env dev", "--env online"} {
|
||||
if strings.Contains(doc, legacy) {
|
||||
t.Errorf("local-dev skill must not recommend legacy %q", legacy)
|
||||
}
|
||||
}
|
||||
for _, boundary := range []string{
|
||||
"`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟;超时仍未完成时停止本轮轮询、报告 `release_id` 和当前 status。",
|
||||
"若本次改动包含自动化 handler,在执行本节通用 commit/push/release 序列前就转到 [automation SOP](lark-apps-automation.md) 的匹配路径,由该 SOP 负责完整的状态门禁、commit/push、release 和可选 enable/test;不要先按本节发布再补 trigger 状态检查。",
|
||||
"用户只要求启用已有 trigger 时,转到 [automation SOP 的「仅启用已有 disabled trigger」路径](lark-apps-automation.md#仅启用已有-disabled-trigger);不得因 enable 反向修改 handler、commit/push 或 release。",
|
||||
"使用 `--environment dev|online`,不要使用旧的 `--env`。只有确认应用已开启多环境时才引导 `--environment dev`;单环境应用省略 `--environment`(服务端选 online)或显式传 `--environment online`。",
|
||||
} {
|
||||
if !strings.Contains(doc, boundary) {
|
||||
t.Errorf("local-dev skill must preserve %q", boundary)
|
||||
}
|
||||
}
|
||||
routeIndex := strings.Index(releaseSection, "若本次改动包含自动化 handler")
|
||||
releaseIndex := strings.Index(releaseSection, "+release-create")
|
||||
if routeIndex < 0 || releaseIndex < 0 || routeIndex >= releaseIndex {
|
||||
t.Error("automation routing must appear before the generic release sequence")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDevSkillContract_DoesNotRequireOnlineURL(t *testing.T) {
|
||||
section := skillSection(t, readLocalDevSkillDoc(t), "## 改完代码后部署上线")
|
||||
|
||||
if strings.Contains(section, "`finished` 成功时该命令输出已含 `online_url`") {
|
||||
t.Error("release guidance must not claim every finished release includes online_url")
|
||||
}
|
||||
if !strings.Contains(section, "若返回 `online_url`,可直接使用;未返回时不要编造链接。") {
|
||||
t.Error("release guidance must explain that online_url is optional")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDevSkillContract_TreatsErrorLogsAsOptional(t *testing.T) {
|
||||
section := skillSection(t, readLocalDevSkillDoc(t), "## 改完代码后部署上线")
|
||||
|
||||
if !strings.Contains(section, "`failed` 时若返回非空 `error_logs`,据此给出失败原因;否则只报告 `release_id` 和当前 status,不要编造原因") {
|
||||
t.Error("release guidance must not promise error_logs on every failed release")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseSkillContract_TreatsOptionalOutputAsOptional(t *testing.T) {
|
||||
releaseGet := readReleaseGetSkillDoc(t)
|
||||
for _, boundary := range []string{
|
||||
"`finished` 后才可能有 `online_url`。",
|
||||
"若输出含 `online_url`,直接读取它作为本轮发布的线上访问链接;未返回时只报告发布完成,不要编造链接。",
|
||||
"若输出含 `error_logs`(`step`/`error_log`),据此向用户转述关键失败步骤和可行动修复;未返回时不要编造失败原因。",
|
||||
} {
|
||||
if !strings.Contains(releaseGet, boundary) {
|
||||
t.Errorf("release-get skill must preserve optional-output boundary %q", boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
)
|
||||
|
||||
func appsValidationError(format string, args ...any) *errs.ValidationError {
|
||||
@@ -74,32 +73,3 @@ func appsInputPathEntryError(path string, err error) error {
|
||||
func appsFileIOError(err error, format string, args ...any) *errs.InternalError {
|
||||
return errs.NewInternalError(errs.SubtypeFileIO, format, args...).WithCause(err)
|
||||
}
|
||||
|
||||
// enrichHTMLPublishAPIError adapts a typed failure from the HTML publish
|
||||
// endpoint: refines endpoint-scoped business codes, prefixes the message with
|
||||
// command context, and attaches endpoint-specific recovery hints. A
|
||||
// still-untyped error is lifted at the SDK boundary instead.
|
||||
func enrichHTMLPublishAPIError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
return client.WrapDoAPIError(err)
|
||||
}
|
||||
// The HTML publish business codes (90001/90002) are scoped to this
|
||||
// endpoint, not service-global, so their subtype classification lives
|
||||
// here instead of the global errclass code table. Only an
|
||||
// otherwise-unclassified API error is refined; a stronger upstream
|
||||
// classification is never overridden.
|
||||
if p.Category == errs.CategoryAPI && p.Subtype == errs.SubtypeUnknown && p.Code == errCodeAppNotFound {
|
||||
p.Subtype = errs.SubtypeNotFound
|
||||
}
|
||||
if p.Message != "" {
|
||||
p.Message = "html-publish failed: " + p.Message
|
||||
}
|
||||
if hint := buildHTMLPublishFailureHint(p.Code); hint != "" {
|
||||
p.Hint = hint
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -57,57 +57,3 @@ func TestAppsFileIOError_ClassifiesInternalFileIO(t *testing.T) {
|
||||
t.Fatalf("cause chain not preserved: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichHTMLPublishAPIError_LiftsUntypedBoundaryError(t *testing.T) {
|
||||
err := enrichHTMLPublishAPIError(errors.New("connection reset by peer"))
|
||||
|
||||
problem := requireAppsProblem(t, err, errs.CategoryNetwork)
|
||||
if problem.Subtype != errs.SubtypeNetworkTransport {
|
||||
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeNetworkTransport)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichHTMLPublishAPIError_PreservesClassificationAndAddsHint(t *testing.T) {
|
||||
err := errs.NewAPIError(errs.SubtypeUnknown, "build failed").
|
||||
WithCode(errCodeBuildFailed).
|
||||
WithLogID("logid-build-failed")
|
||||
|
||||
got := enrichHTMLPublishAPIError(err)
|
||||
if got != err {
|
||||
t.Fatalf("typed error should be enriched in place")
|
||||
}
|
||||
problem := requireAppsAPIProblem(t, got)
|
||||
if problem.Subtype != errs.SubtypeUnknown {
|
||||
t.Fatalf("subtype = %q, want %q unchanged", problem.Subtype, errs.SubtypeUnknown)
|
||||
}
|
||||
if problem.Code != errCodeBuildFailed {
|
||||
t.Fatalf("code = %d, want %d", problem.Code, errCodeBuildFailed)
|
||||
}
|
||||
if problem.LogID != "logid-build-failed" {
|
||||
t.Fatalf("log_id = %q, want preserved", problem.LogID)
|
||||
}
|
||||
if !strings.Contains(problem.Message, "html-publish failed") {
|
||||
t.Fatalf("message = %q, want html-publish context", problem.Message)
|
||||
}
|
||||
if problem.Hint == "" {
|
||||
t.Fatalf("expected known-code recovery hint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichHTMLPublishAPIError_ClassifiesAppNotFoundLocally(t *testing.T) {
|
||||
err := errs.NewAPIError(errs.SubtypeUnknown, "app not found").WithCode(errCodeAppNotFound)
|
||||
|
||||
problem := requireAppsAPIProblem(t, enrichHTMLPublishAPIError(err))
|
||||
if problem.Subtype != errs.SubtypeNotFound {
|
||||
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichHTMLPublishAPIError_KeepsStrongerClassification(t *testing.T) {
|
||||
err := errs.NewAPIError(errs.SubtypeRateLimit, "throttled").WithCode(errCodeAppNotFound)
|
||||
|
||||
problem := requireAppsAPIProblem(t, enrichHTMLPublishAPIError(err))
|
||||
if problem.Subtype != errs.SubtypeRateLimit {
|
||||
t.Fatalf("subtype = %q, want %q unchanged", problem.Subtype, errs.SubtypeRateLimit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,10 +17,11 @@ import (
|
||||
var AppsGet = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+get",
|
||||
Description: "Get a single app's detail by app ID (returns app_type, name, description, publish status, etc.)",
|
||||
Description: "Get a single app's detail by app ID or meta token (returns app_type, name, description, publish status, etc.)",
|
||||
Risk: "read",
|
||||
Tips: []string{
|
||||
"Example: lark-cli apps +get --app-id <app_id>",
|
||||
"Example: lark-cli apps +get --app-id <meta_token>",
|
||||
"Example: lark-cli apps +get --app-id <app_id> --dry-run",
|
||||
"Tip: extract app type with --jq '.data.app.app_type'",
|
||||
},
|
||||
@@ -28,7 +29,7 @@ var AppsGet = common.Shortcut{
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "app ID", Required: true},
|
||||
{Name: "app-id", Desc: "app ID or meta token", Required: true},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if strings.TrimSpace(rctx.Str("app-id")) == "" {
|
||||
@@ -40,7 +41,7 @@ var AppsGet = common.Shortcut{
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("%s/apps/%s", apiBasePath, validate.EncodePathSegment(appID))).
|
||||
Desc("Get app detail (returns app_id, app_type, name, description, icon_url, created_at, updated_at, is_published)")
|
||||
Desc("Get app detail (returns app_id, meta_token, app_type, name, description, icon_url, created_at, updated_at, is_published)")
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
@@ -54,6 +55,9 @@ var AppsGet = common.Shortcut{
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "app_id: %v\n", app["app_id"])
|
||||
if mt, ok := app["meta_token"].(string); ok && mt != "" {
|
||||
fmt.Fprintf(w, "meta_token: %s\n", mt)
|
||||
}
|
||||
fmt.Fprintf(w, "app_type: %v\n", app["app_type"])
|
||||
fmt.Fprintf(w, "name: %v\n", app["name"])
|
||||
if desc, ok := app["description"].(string); ok && desc != "" {
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
@@ -38,9 +37,13 @@ var AppsHTMLPublish = common.Shortcut{
|
||||
{Name: "allow-sensitive", Type: "bool", Desc: "skip the credential-file scan (allow .env / .npmrc / .aws/credentials / etc. in the publish payload)"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if strings.TrimSpace(rctx.Str("app-id")) == "" {
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
if appID == "" {
|
||||
return appsValidationParamError("--app-id", "--app-id is required")
|
||||
}
|
||||
if err := validateRealAppID(appID); err != nil {
|
||||
return err
|
||||
}
|
||||
path := strings.TrimSpace(rctx.Str("path"))
|
||||
if path == "" {
|
||||
return appsValidationParamError("--path", "--path is required")
|
||||
@@ -73,9 +76,11 @@ var AppsHTMLPublish = common.Shortcut{
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
path := strings.TrimSpace(rctx.Str("path"))
|
||||
dry := common.NewDryRunAPI()
|
||||
dry.Desc("Pack tar.gz and publish HTML app (actual API path determined at runtime by app type; returns url or release_id)")
|
||||
dry.POST(fmt.Sprintf("%s/apps/%s/upload_and_release_html_code", apiBasePath, validate.EncodePathSegment(appID))).
|
||||
Set("content_type", "multipart/form-data")
|
||||
dry.Desc("Pack tar.gz → GET pre_release for TOS upload URL → PUT tar.gz to TOS → POST release-create with tos_path; returns release_id")
|
||||
dry.GET(fmt.Sprintf("%s/apps/%s/pre_release", apiBasePath, validate.EncodePathSegment(appID))).
|
||||
PUT("<presigned_upload_url> (from pre_release response)").
|
||||
POST(fmt.Sprintf(releaseCreatePath, validate.EncodePathSegment(appID))).
|
||||
Body(map[string]string{"tos_path": "<from pre_release response>"})
|
||||
|
||||
candidates, err := walkHTMLPublishCandidates(rctx.FileIO(), path)
|
||||
if err != nil {
|
||||
@@ -123,16 +128,7 @@ var AppsHTMLPublish = common.Shortcut{
|
||||
Path: strings.TrimSpace(rctx.Str("path")),
|
||||
}
|
||||
|
||||
appType := queryAppType(ctx, rctx, spec.AppID)
|
||||
|
||||
var out map[string]interface{}
|
||||
var err error
|
||||
if appType == "modern_html" {
|
||||
out, err = runHTMLPublishTOS(ctx, rctx, spec)
|
||||
} else {
|
||||
client := appsHTMLPublishAPI{runtime: rctx}
|
||||
out, err = runHTMLPublish(ctx, rctx.FileIO(), client, spec)
|
||||
}
|
||||
out, err := runHTMLPublishTOS(ctx, rctx, spec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -264,25 +260,7 @@ func prepareHTMLPublishTarball(fio fileio.FileIO, path string) (*htmlPublishTarb
|
||||
return tarball, nil
|
||||
}
|
||||
|
||||
func runHTMLPublish(ctx context.Context, fio fileio.FileIO, publisher appsHTMLPublishClient, spec appsHTMLPublishSpec) (map[string]interface{}, error) {
|
||||
tarball, err := prepareHTMLPublishTarball(fio, spec.Path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := publisher.HTMLPublish(ctx, spec.AppID, tarball)
|
||||
if err != nil {
|
||||
return nil, client.WrapDoAPIError(err)
|
||||
}
|
||||
|
||||
out := map[string]interface{}{}
|
||||
if resp.URL != "" {
|
||||
out["url"] = resp.URL
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// runHTMLPublishTOS handles the modern_html publish path: validate → tar.gz →
|
||||
// runHTMLPublishTOS handles the publish path: validate → tar.gz →
|
||||
// call pre_release to get TOS upload URL → upload tar.gz to TOS → return
|
||||
// tos_path for +release-create --tos-path.
|
||||
func runHTMLPublishTOS(ctx context.Context, rctx *common.RuntimeContext, spec appsHTMLPublishSpec) (map[string]interface{}, error) {
|
||||
|
||||
@@ -5,7 +5,6 @@ package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -23,20 +22,6 @@ import (
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
type fakeAppsHTMLPublishClient struct {
|
||||
resp *htmlPublishResponse
|
||||
err error
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (f *fakeAppsHTMLPublishClient) HTMLPublish(ctx context.Context, appID string, tarball *htmlPublishTarball) (*htmlPublishResponse, error) {
|
||||
f.calls = append(f.calls, appID)
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return f.resp, nil
|
||||
}
|
||||
|
||||
func writeAppsSampleSite(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
@@ -46,71 +31,19 @@ func writeAppsSampleSite(t *testing.T) string {
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_HappyPath(t *testing.T) {
|
||||
site := writeAppsSampleSite(t)
|
||||
fake := &fakeAppsHTMLPublishClient{
|
||||
resp: &htmlPublishResponse{URL: "https://miaoda/app_x"},
|
||||
}
|
||||
out, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: site})
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if out["url"] != "https://miaoda/app_x" {
|
||||
t.Fatalf("url=%v", out["url"])
|
||||
}
|
||||
if len(fake.calls) != 1 || fake.calls[0] != "app_x" {
|
||||
t.Fatalf("calls=%v", fake.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_OnlyURLInEnvelope(t *testing.T) {
|
||||
// Pin 概要设计 §5.3 不变量 4 "同步语义不会变成异步" (legacy html path only):
|
||||
// envelope 只含 url,未来若有人加 status / release_id 字段会被这个测试拦截。
|
||||
site := writeAppsSampleSite(t)
|
||||
fake := &fakeAppsHTMLPublishClient{
|
||||
resp: &htmlPublishResponse{URL: "https://miaoda/app_x"},
|
||||
}
|
||||
out, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: site})
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(out) != 1 {
|
||||
t.Fatalf("envelope should only contain 'url', got %d keys: %v", len(out), out)
|
||||
}
|
||||
if _, ok := out["url"]; !ok {
|
||||
t.Fatalf("envelope missing 'url': %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_ClientErrorPropagated(t *testing.T) {
|
||||
site := writeAppsSampleSite(t)
|
||||
wantErr := errors.New("server timeout")
|
||||
fake := &fakeAppsHTMLPublishClient{err: wantErr}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: site})
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_PathNotFound(t *testing.T) {
|
||||
fake := &fakeAppsHTMLPublishClient{}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: "/nonexistent"})
|
||||
func TestPrepareHTMLPublishTarball_PathNotFound(t *testing.T) {
|
||||
_, err := prepareHTMLPublishTarball(newTestFIO(), "/nonexistent")
|
||||
if err == nil {
|
||||
t.Fatalf("expected error")
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("client should not be called when path invalid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_DirRequiresIndexHTML(t *testing.T) {
|
||||
// 目录形态:缺 index.html 应该被拦
|
||||
func TestPrepareHTMLPublishTarball_DirRequiresIndexHTML(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "foo.html"), []byte("<html></html>"), 0o644); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
fake := &fakeAppsHTMLPublishClient{}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir})
|
||||
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for missing index.html")
|
||||
}
|
||||
@@ -121,13 +54,9 @@ func TestRunHTMLPublish_DirRequiresIndexHTML(t *testing.T) {
|
||||
if problem.Hint == "" {
|
||||
t.Fatalf("expected non-empty hint")
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("client should not be called when index.html missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_DirWithIndexHTMLPasses(t *testing.T) {
|
||||
// 目录含 index.html 应该正常走完
|
||||
func TestPrepareHTMLPublishTarball_DirWithIndexHTMLPasses(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("<html></html>"), 0o644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
@@ -135,57 +64,49 @@ func TestRunHTMLPublish_DirWithIndexHTMLPasses(t *testing.T) {
|
||||
if err := os.WriteFile(filepath.Join(dir, "extra.html"), []byte("<html></html>"), 0o644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
fake := &fakeAppsHTMLPublishClient{resp: &htmlPublishResponse{URL: "https://miaoda/app_x"}}
|
||||
if _, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir}); err != nil {
|
||||
tarball, err := prepareHTMLPublishTarball(newTestFIO(), dir)
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(fake.calls) != 1 {
|
||||
t.Fatalf("client should be called when index.html present")
|
||||
if tarball == nil || tarball.Size == 0 {
|
||||
t.Fatalf("expected non-empty tarball")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_SingleFileRejectedIfNotNamedIndex(t *testing.T) {
|
||||
// 单文件形态:文件名不是 index.html 也要拦
|
||||
func TestPrepareHTMLPublishTarball_SingleFileRejectedIfNotNamedIndex(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
single := filepath.Join(dir, "foo.html")
|
||||
if err := os.WriteFile(single, []byte("<html></html>"), 0o644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
fake := &fakeAppsHTMLPublishClient{}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: single})
|
||||
_, err := prepareHTMLPublishTarball(newTestFIO(), single)
|
||||
if err == nil {
|
||||
t.Fatalf("single-file path 'foo.html' should be rejected (not named index.html)")
|
||||
}
|
||||
requireAppsValidationProblem(t, err)
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("client must not be called when index.html missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_SingleFileNamedIndexPasses(t *testing.T) {
|
||||
// 单文件形态:文件名恰好就是 index.html → 放行
|
||||
func TestPrepareHTMLPublishTarball_SingleFileNamedIndexPasses(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
single := filepath.Join(dir, "index.html")
|
||||
if err := os.WriteFile(single, []byte("<html></html>"), 0o644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
fake := &fakeAppsHTMLPublishClient{resp: &htmlPublishResponse{URL: "https://miaoda/app_x"}}
|
||||
if _, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: single}); err != nil {
|
||||
tarball, err := prepareHTMLPublishTarball(newTestFIO(), single)
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(fake.calls) != 1 {
|
||||
t.Fatalf("client should be called for single index.html")
|
||||
if tarball == nil || tarball.Size == 0 {
|
||||
t.Fatalf("expected non-empty tarball")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_RejectsOversizeTarball(t *testing.T) {
|
||||
// 把上限调到 100 字节验证拦截,defer 恢复原值避免污染其它测试。
|
||||
func TestPrepareHTMLPublishTarball_RejectsOversizeTarball(t *testing.T) {
|
||||
orig := maxHTMLPublishTarballBytes
|
||||
maxHTMLPublishTarballBytes = 100
|
||||
defer func() { maxHTMLPublishTarballBytes = orig }()
|
||||
|
||||
dir := t.TempDir()
|
||||
// 写 index.html(满足新加的 index 校验)+ 大文件超 100 字节上限。
|
||||
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("<html></html>"), 0o644); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
@@ -194,8 +115,7 @@ func TestRunHTMLPublish_RejectsOversizeTarball(t *testing.T) {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
|
||||
fake := &fakeAppsHTMLPublishClient{}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir})
|
||||
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
|
||||
if err == nil {
|
||||
t.Fatalf("expected oversize error")
|
||||
}
|
||||
@@ -206,9 +126,6 @@ func TestRunHTMLPublish_RejectsOversizeTarball(t *testing.T) {
|
||||
if problem.Hint == "" {
|
||||
t.Fatalf("expected non-empty hint")
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("client should not be called when tarball oversize")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxHTMLPublishTarballBytes_Default(t *testing.T) {
|
||||
@@ -264,8 +181,17 @@ func TestAppsHTMLPublish_DryRunPrintsManifest(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
got := stdout.String()
|
||||
if !strings.Contains(got, "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code") {
|
||||
t.Fatalf("dry-run missing endpoint: %s", got)
|
||||
if !strings.Contains(got, "/open-apis/spark/v1/apps/app_x/pre_release") {
|
||||
t.Fatalf("dry-run missing pre_release endpoint: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "presigned_upload_url") {
|
||||
t.Fatalf("dry-run missing TOS PUT step: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "/open-apis/spark/v1/apps/app_x/releases") {
|
||||
t.Fatalf("dry-run missing release-create endpoint: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "tos_path") {
|
||||
t.Fatalf("dry-run missing tos_path in release-create body: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "index.html") {
|
||||
t.Fatalf("dry-run missing file list: %s", got)
|
||||
@@ -500,9 +426,7 @@ func TestRunHTMLPublish_RejectsOversizeRawCandidates(t *testing.T) {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
|
||||
fake := &fakeAppsHTMLPublishClient{}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake,
|
||||
appsHTMLPublishSpec{AppID: "app_x", Path: dir})
|
||||
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
|
||||
if err == nil {
|
||||
t.Fatalf("expected raw-size cap to fire")
|
||||
}
|
||||
@@ -510,9 +434,6 @@ func TestRunHTMLPublish_RejectsOversizeRawCandidates(t *testing.T) {
|
||||
if !strings.Contains(problem.Message, "raw") || !strings.Contains(problem.Message, "bytes") {
|
||||
t.Fatalf("expected message to explain raw-byte cap, got %q", problem.Message)
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("client must not be called when raw cap hit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOversizeHTMLFiles(t *testing.T) {
|
||||
@@ -555,8 +476,7 @@ func TestRunHTMLPublish_RejectsOversizeHTMLFile(t *testing.T) {
|
||||
if err := os.WriteFile(filepath.Join(dir, "big.html"), []byte(strings.Repeat("x", 4096)), 0o644); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
fake := &fakeAppsHTMLPublishClient{}
|
||||
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir})
|
||||
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
|
||||
if err == nil {
|
||||
t.Fatalf("expected per-file oversize error")
|
||||
}
|
||||
@@ -567,13 +487,9 @@ func TestRunHTMLPublish_RejectsOversizeHTMLFile(t *testing.T) {
|
||||
if problem.Hint == "" {
|
||||
t.Fatalf("expected non-empty hint")
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("client must not be called when an HTML file is oversize")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHTMLPublish_IgnoresOversizeNonHTML(t *testing.T) {
|
||||
// 单 .html 上限调小,但超限文件是 .png → 不被本护栏拦截,正常发布。
|
||||
func TestPrepareHTMLPublishTarball_IgnoresOversizeNonHTML(t *testing.T) {
|
||||
orig := maxHTMLPublishSingleHTMLFileBytes
|
||||
maxHTMLPublishSingleHTMLFileBytes = 100
|
||||
defer func() { maxHTMLPublishSingleHTMLFileBytes = orig }()
|
||||
@@ -585,12 +501,12 @@ func TestRunHTMLPublish_IgnoresOversizeNonHTML(t *testing.T) {
|
||||
if err := os.WriteFile(filepath.Join(dir, "big.png"), []byte(strings.Repeat("x", 4096)), 0o644); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
fake := &fakeAppsHTMLPublishClient{resp: &htmlPublishResponse{URL: "https://miaoda/app_x"}}
|
||||
if _, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir}); err != nil {
|
||||
tarball, err := prepareHTMLPublishTarball(newTestFIO(), dir)
|
||||
if err != nil {
|
||||
t.Fatalf("non-html oversize must not be blocked by the .html cap: %v", err)
|
||||
}
|
||||
if len(fake.calls) != 1 {
|
||||
t.Fatalf("client should be called; calls=%v", fake.calls)
|
||||
if tarball == nil || tarball.Size == 0 {
|
||||
t.Fatalf("expected non-empty tarball")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,15 +74,18 @@ type appTypePolicy struct {
|
||||
// skipSkillsSync skips the conditional `npx ... skills sync --local` step on
|
||||
// the non-empty (`app sync`) scaffold path.
|
||||
skipSkillsSync bool
|
||||
// skipAppSync skips `npx ... app sync` on the non-empty repo path.
|
||||
skipAppSync bool
|
||||
}
|
||||
|
||||
// appTypePolicies maps an app_type to its +init control strategy. Types absent
|
||||
// from the map get the zero-value policy (install runs, env is pulled, skills
|
||||
// are synced).
|
||||
var appTypePolicies = map[string]appTypePolicy{
|
||||
// modern_html is a static HTML site: no dependencies to install, no startup
|
||||
// env vars to pull, and no steering skills to sync.
|
||||
"modern_html": {skipInstall: true, skipEnvPull: true, skipSkillsSync: true},
|
||||
// modern_html / html are static HTML sites: no dependencies to install,
|
||||
// no startup env vars to pull, no steering skills to sync, and no app sync.
|
||||
"modern_html": {skipInstall: true, skipEnvPull: true, skipSkillsSync: true, skipAppSync: true},
|
||||
"html": {skipInstall: true, skipEnvPull: true, skipSkillsSync: true, skipAppSync: true},
|
||||
}
|
||||
|
||||
// policyForAppType returns the +init control strategy for appType. Unlisted
|
||||
@@ -122,9 +125,13 @@ var AppsInit = common.Shortcut{
|
||||
{Name: "source-path", Desc: "path to existing source files (e.g. HTML output from an agent) to incorporate into the initialized project"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if strings.TrimSpace(rctx.Str("app-id")) == "" {
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
if appID == "" {
|
||||
return appsValidationParamError("--app-id", "--app-id is required")
|
||||
}
|
||||
if err := validateRealAppID(appID); err != nil {
|
||||
return err
|
||||
}
|
||||
if sp := strings.TrimSpace(rctx.Str("source-path")); sp != "" {
|
||||
if err := charcheck.RejectControlChars(sp, "--source-path"); err != nil {
|
||||
return appsValidationParamError("--source-path", "%v", err).WithCause(err)
|
||||
@@ -334,11 +341,19 @@ func ensureMetaAppID(dir, appID string) error {
|
||||
// each is not already resolvable from local/global/system config, so a
|
||||
// developer's existing identity is never overwritten. Each key is handled
|
||||
// independently (a machine with only user.name set still gets a default email).
|
||||
func ensureGitIdentity(ctx context.Context, dir string) error {
|
||||
if err := ensureGitConfigValue(ctx, dir, "user.name", defaultGitUserName); err != nil {
|
||||
func ensureGitIdentity(ctx context.Context, dir, authorName, authorEmail string) error {
|
||||
name := strings.TrimSpace(authorName)
|
||||
if name == "" {
|
||||
name = defaultGitUserName
|
||||
}
|
||||
email := strings.TrimSpace(authorEmail)
|
||||
if email == "" {
|
||||
email = defaultGitUserEmail
|
||||
}
|
||||
if err := ensureGitConfigValue(ctx, dir, "user.name", name); err != nil {
|
||||
return err
|
||||
}
|
||||
return ensureGitConfigValue(ctx, dir, "user.email", defaultGitUserEmail)
|
||||
return ensureGitConfigValue(ctx, dir, "user.email", email)
|
||||
}
|
||||
|
||||
// ensureGitConfigValue sets <key>=fallback in the repo-local git config when key
|
||||
@@ -400,13 +415,16 @@ func runScaffold(ctx context.Context, dir, appID, appType, sourcePath string) (s
|
||||
}
|
||||
return scaffoldKindInit, nil
|
||||
}
|
||||
if _, stderr, err := initRunner.Run(ctx, dir, "npx", "-y", "--prefer-online", "--registry", npmRegistry, miaodaCLIPkg, "app", "sync"); err != nil {
|
||||
return "", appsExternalToolError(err, "npx app sync failed: %s", gitErr(stderr, err))
|
||||
policy := policyForAppType(appType)
|
||||
if !policy.skipAppSync {
|
||||
if _, stderr, err := initRunner.Run(ctx, dir, "npx", "-y", "--prefer-online", "--registry", npmRegistry, miaodaCLIPkg, "app", "sync"); err != nil {
|
||||
return "", appsExternalToolError(err, "npx app sync failed: %s", gitErr(stderr, err))
|
||||
}
|
||||
}
|
||||
if err := ensureMetaAppID(dir, appID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !policyForAppType(appType).skipSkillsSync && !hasSteeringSkills(dir) {
|
||||
if !policy.skipSkillsSync && !hasSteeringSkills(dir) {
|
||||
if _, stderr, err := initRunner.Run(ctx, dir, "npx", "-y", "--prefer-online", "--registry", npmRegistry, miaodaCLIPkg, "skills", "sync", "--local"); err != nil {
|
||||
return "", appsExternalToolError(err, "npx skills sync failed: %s", gitErr(stderr, err))
|
||||
}
|
||||
@@ -436,26 +454,38 @@ func scaffoldInitArgs(appType, appID, sourcePath string) []string {
|
||||
return base
|
||||
}
|
||||
|
||||
// parseRepoURLFromEnvelope extracts data.repository_url from a lark-cli JSON
|
||||
// envelope ({"ok":true,"data":{"repository_url":"..."}}). The field name
|
||||
// matches the contract emitted by `apps +git-credential-init`.
|
||||
func parseRepoURLFromEnvelope(stdout string) (string, error) {
|
||||
// credentialInitResult holds the fields parsed from +git-credential-init output.
|
||||
type credentialInitResult struct {
|
||||
RepositoryURL string
|
||||
CommitAuthorName string
|
||||
CommitAuthorEmail string
|
||||
}
|
||||
|
||||
// parseCredentialInitEnvelope extracts fields from a +git-credential-init JSON
|
||||
// envelope ({"ok":true,"data":{"repository_url":"...","commit_author_name":"...","commit_author_email":"..."}}).
|
||||
func parseCredentialInitEnvelope(stdout string) (credentialInitResult, error) {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
RepositoryURL string `json:"repository_url"`
|
||||
RepositoryURL string `json:"repository_url"`
|
||||
CommitAuthorName string `json:"commit_author_name"`
|
||||
CommitAuthorEmail string `json:"commit_author_email"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &env); err != nil {
|
||||
return "", appsSubprocessEnvelopeError("could not parse +git-credential-init output as JSON: %v", err)
|
||||
return credentialInitResult{}, appsSubprocessEnvelopeError("could not parse +git-credential-init output as JSON: %v", err)
|
||||
}
|
||||
if !env.OK {
|
||||
return "", appsSubprocessEnvelopeError("+git-credential-init reported failure")
|
||||
return credentialInitResult{}, appsSubprocessEnvelopeError("+git-credential-init reported failure")
|
||||
}
|
||||
if strings.TrimSpace(env.Data.RepositoryURL) == "" {
|
||||
return "", appsSubprocessEnvelopeError("+git-credential-init returned no repository_url")
|
||||
return credentialInitResult{}, appsSubprocessEnvelopeError("+git-credential-init returned no repository_url")
|
||||
}
|
||||
return env.Data.RepositoryURL, nil
|
||||
return credentialInitResult{
|
||||
RepositoryURL: env.Data.RepositoryURL,
|
||||
CommitAuthorName: env.Data.CommitAuthorName,
|
||||
CommitAuthorEmail: env.Data.CommitAuthorEmail,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseEnvFileFromEnvelope extracts data.env_file from a `+env-pull` success
|
||||
@@ -527,7 +557,10 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
return err
|
||||
}
|
||||
|
||||
appType := queryAppType(ctx, rctx, appID)
|
||||
appType, err := queryAppType(ctx, rctx, appID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policy := policyForAppType(appType)
|
||||
|
||||
// Already-initialized short-circuit: a dir containing .spark/meta.json is an
|
||||
@@ -595,16 +628,16 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
}
|
||||
|
||||
initLogf(rctx, "Issuing repository credentials for %s...", appID)
|
||||
repoURL, err := issueCredentials(ctx, rctx, appID)
|
||||
cred, err := issueCredentials(ctx, rctx, appID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateRepoURLScheme(repoURL); err != nil {
|
||||
if err := validateRepoURLScheme(cred.RepositoryURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
initLogf(rctx, "Cloning into %s...", dir)
|
||||
if _, stderr, err := initRunner.Run(ctx, "", "git", "clone", "--", repoURL, dir); err != nil {
|
||||
if _, stderr, err := initRunner.Run(ctx, "", "git", "clone", "--", cred.RepositoryURL, dir); err != nil {
|
||||
return appsExternalToolError(err, "git clone failed: %s", gitErr(stderr, err))
|
||||
}
|
||||
initLogf(rctx, "Checking out %s...", defaultInitBranch)
|
||||
@@ -612,9 +645,10 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
return appsExternalToolError(err, "git checkout %s failed: %s", defaultInitBranch, gitErr(stderr, err))
|
||||
}
|
||||
|
||||
// Ensure a committer identity exists before the scaffold commit; only sets
|
||||
// repo-local defaults when none is configured (existing identity is kept).
|
||||
if err := ensureGitIdentity(ctx, dir); err != nil {
|
||||
// Ensure a committer identity exists before the scaffold commit. Uses the
|
||||
// author name/email from +git-credential-init when available; falls back
|
||||
// to lark-cli-bot defaults when the server does not provide them.
|
||||
if err := ensureGitIdentity(ctx, dir, cred.CommitAuthorName, cred.CommitAuthorEmail); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -643,7 +677,7 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
|
||||
out := map[string]interface{}{
|
||||
"app_id": appID,
|
||||
"repository_url": redactURLCredentials(repoURL),
|
||||
"repository_url": redactURLCredentials(cred.RepositoryURL),
|
||||
"branch": defaultInitBranch,
|
||||
"clone_path": dir,
|
||||
"scaffold": scaffold,
|
||||
@@ -721,10 +755,10 @@ func pullEnv(ctx context.Context, rctx *common.RuntimeContext, appID, dir string
|
||||
|
||||
// issueCredentials runs `<self> apps +git-credential-init --app-id <id> --format json`
|
||||
// and returns the repo_url it reports. Forwards --as when set.
|
||||
func issueCredentials(ctx context.Context, rctx *common.RuntimeContext, appID string) (string, error) {
|
||||
func issueCredentials(ctx context.Context, rctx *common.RuntimeContext, appID string) (credentialInitResult, error) {
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", errs.NewInternalError(errs.SubtypeUnknown, "cannot locate lark-cli executable: %v", err).WithCause(err)
|
||||
return credentialInitResult{}, errs.NewInternalError(errs.SubtypeUnknown, "cannot locate lark-cli executable: %v", err).WithCause(err)
|
||||
}
|
||||
args := []string{"apps", "+git-credential-init", "--app-id", appID, "--format", "json"}
|
||||
if as := strings.TrimSpace(rctx.Str("as")); as != "" {
|
||||
@@ -732,11 +766,11 @@ func issueCredentials(ctx context.Context, rctx *common.RuntimeContext, appID st
|
||||
}
|
||||
stdout, stderr, err := initRunner.Run(ctx, "", self, args...)
|
||||
if err != nil {
|
||||
return "", appsExternalToolError(err, "apps +git-credential-init failed: %s", gitErr(stderr, err)).
|
||||
return credentialInitResult{}, appsExternalToolError(err, "apps +git-credential-init failed: %s", gitErr(stderr, err)).
|
||||
WithHint("ensure apps +git-credential-init is available and you are logged in").
|
||||
WithCause(err)
|
||||
}
|
||||
return parseRepoURLFromEnvelope(stdout)
|
||||
return parseCredentialInitEnvelope(stdout)
|
||||
}
|
||||
|
||||
// commitAndPushIfDirty commits and pushes only when the working tree has
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/internal/testutil/gitcmd"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
@@ -110,18 +111,24 @@ func TestDefaultCloneDir(t *testing.T) {
|
||||
// --- pure-function tests ---
|
||||
|
||||
func TestParseRepoURL(t *testing.T) {
|
||||
url, err := parseRepoURLFromEnvelope(`{"ok":true,"data":{"repository_url":"http://u:t@h/app_x.git"}}`)
|
||||
result, err := parseCredentialInitEnvelope(`{"ok":true,"data":{"repository_url":"http://u:t@h/app_x.git","commit_author_name":"Alice","commit_author_email":"alice@example.com"}}`)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if url != "http://u:t@h/app_x.git" {
|
||||
t.Errorf("got %q", url)
|
||||
if result.RepositoryURL != "http://u:t@h/app_x.git" {
|
||||
t.Errorf("RepositoryURL got %q", result.RepositoryURL)
|
||||
}
|
||||
if result.CommitAuthorName != "Alice" {
|
||||
t.Errorf("CommitAuthorName got %q", result.CommitAuthorName)
|
||||
}
|
||||
if result.CommitAuthorEmail != "alice@example.com" {
|
||||
t.Errorf("CommitAuthorEmail got %q", result.CommitAuthorEmail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRepoURL_Errors(t *testing.T) {
|
||||
for _, in := range []string{`not json`, `{"ok":false,"data":{}}`, `{"ok":true,"data":{}}`, `{"ok":true,"data":{"repository_url":""}}`} {
|
||||
if _, err := parseRepoURLFromEnvelope(in); err == nil {
|
||||
if _, err := parseCredentialInitEnvelope(in); err == nil {
|
||||
t.Errorf("expected error for %q", in)
|
||||
}
|
||||
}
|
||||
@@ -149,6 +156,22 @@ func withFakeRunner(t *testing.T, f *fakeCommandRunner) {
|
||||
t.Cleanup(func() { initRunner = orig })
|
||||
}
|
||||
|
||||
func stubAppType(reg *httpmock.Registry, appID, appType string) {
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/spark/v1/apps/" + appID,
|
||||
Body: map[string]interface{}{
|
||||
"code": float64(0),
|
||||
"data": map[string]interface{}{
|
||||
"app": map[string]interface{}{
|
||||
"app_id": appID,
|
||||
"app_type": appType,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func credInitOK(repoURL string) fakeCallResult {
|
||||
return fakeCallResult{stdout: `{"ok":true,"data":{"repository_url":"` + repoURL + `"}}`}
|
||||
}
|
||||
@@ -313,7 +336,8 @@ func TestAppsInit_EmptyRepo_EndToEnd(t *testing.T) {
|
||||
"git status": {stdout: " M src/app.ts\n"}, // scaffold produced changes
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
@@ -354,7 +378,8 @@ func TestAppsInit_AlreadyInitialized_ShortCircuit(t *testing.T) {
|
||||
}
|
||||
f := &fakeCommandRunner{results: map[string]fakeCallResult{"env-pull": envPullOK(filepath.Join(abs, ".env.local"))}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
}
|
||||
@@ -423,7 +448,8 @@ func TestAppsInit_HappyPathCleanTree(t *testing.T) {
|
||||
"git status": {}, // clean tree after scaffold -> no commit/push
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
|
||||
err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout)
|
||||
@@ -472,7 +498,8 @@ func TestAppsInit_DirtyTreeCommitPush(t *testing.T) {
|
||||
"git status": {stdout: " M file.txt"},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
|
||||
err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout)
|
||||
@@ -542,7 +569,8 @@ func TestAppsInit_CloneFailure(t *testing.T) {
|
||||
"git clone": {stderr: "fatal: unable to access 'http://u:t@h/r.git'", err: errors.New("exit 128")},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
|
||||
err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout)
|
||||
@@ -616,7 +644,8 @@ func TestAppsInit_AsPassthrough(t *testing.T) {
|
||||
"git status": {},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
|
||||
// AppsInit.AuthTypes is ["user"], so the framework rejects --as bot. Use
|
||||
@@ -722,7 +751,7 @@ func TestIsEmptyRepo(t *testing.T) {
|
||||
// newAppsExecuteFactoryWithStderr mirrors newAppsExecuteFactory but also returns
|
||||
// the stderr buffer, so tests can assert on the +init progress log lines that
|
||||
// initLogf writes to IO().ErrOut.
|
||||
func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffer) {
|
||||
func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffer, *httpmock.Registry) {
|
||||
t.Helper()
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
@@ -732,12 +761,12 @@ func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buf
|
||||
Brand: core.BrandFeishu,
|
||||
UserOpenId: "ou_test",
|
||||
}
|
||||
factory, stdout, stderr, _ := cmdutil.TestFactory(t, cfg)
|
||||
return factory, stdout, stderr
|
||||
factory, stdout, stderr, reg := cmdutil.TestFactory(t, cfg)
|
||||
return factory, stdout, stderr, reg
|
||||
}
|
||||
|
||||
func TestAppsInit_Req1_Wording(t *testing.T) {
|
||||
factory, stdout, _ := newAppsExecuteFactoryWithStderr(t)
|
||||
factory, stdout, _, _ := newAppsExecuteFactoryWithStderr(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--as", "user", "--dry-run"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
@@ -766,7 +795,8 @@ func TestAppsInit_Req1_Wording(t *testing.T) {
|
||||
"git status": {},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory2, stdout2, stderr2 := newAppsExecuteFactoryWithStderr(t)
|
||||
factory2, stdout2, stderr2, reg2 := newAppsExecuteFactoryWithStderr(t)
|
||||
stubAppType(reg2, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory2, stdout2); err != nil {
|
||||
t.Fatalf("run err=%v", err)
|
||||
@@ -829,7 +859,8 @@ func TestAppsInit_EmptyRepo_TwoCommits(t *testing.T) {
|
||||
"git status": {stdout: " A src/app.ts\n A .spark/meta.json\n A .agent/skills/steering/x.md\n"},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
@@ -870,7 +901,8 @@ func TestAppsInit_EmptyRepo_AppCodeOnly_SingleCommit(t *testing.T) {
|
||||
"git status": {stdout: " A src/app.ts\n"},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
@@ -890,7 +922,8 @@ func TestAppsInit_EmptyRepo_ConfigOnly_SingleCommit(t *testing.T) {
|
||||
"git status": {stdout: " A .spark/meta.json\n"},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
@@ -910,7 +943,8 @@ func TestAppsInit_NonEmpty_SingleInitCommit(t *testing.T) {
|
||||
"git status": {stdout: " M file.txt\n M .spark/meta.json\n"},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
@@ -929,8 +963,7 @@ func TestAppsInit_NonEmpty_SingleInitCommit(t *testing.T) {
|
||||
// gitMust runs a git command in dir with a real binary, failing the test on error.
|
||||
func gitMust(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
cmd := gitcmd.Command(dir, args...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git %v in %s failed: %v\n%s", args, dir, err, out)
|
||||
@@ -946,6 +979,7 @@ func TestCommitAndPushIfDirty_RealGit_IgnoredAgentDir(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not available")
|
||||
}
|
||||
gitcmd.SetSynchronousMaintenanceEnv(t)
|
||||
// Bare remote so `git push origin sprint/default` succeeds.
|
||||
remote := t.TempDir()
|
||||
gitMust(t, remote, "init", "--bare", "-q", "--initial-branch", defaultInitBranch)
|
||||
@@ -1067,6 +1101,7 @@ func TestCommitAndPushIfDirty_RealGit_NonEmptyUpgrade(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not available")
|
||||
}
|
||||
gitcmd.SetSynchronousMaintenanceEnv(t)
|
||||
remote := t.TempDir()
|
||||
gitMust(t, remote, "init", "--bare", "-q", "--initial-branch", defaultInitBranch)
|
||||
|
||||
@@ -1289,7 +1324,8 @@ func TestAppsInit_EnvPull_Success(t *testing.T) {
|
||||
"env-pull": envPullOK("/abs/app_x/.env.local"),
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
@@ -1327,7 +1363,8 @@ func TestAppsInit_EnvPull_NonFatal(t *testing.T) {
|
||||
},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
dir := relCloneDir(t)
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("env-pull failure must be non-fatal, got: %v", err)
|
||||
@@ -1366,7 +1403,8 @@ func TestAppsInit_AlreadyInitialized_RunsEnvPull(t *testing.T) {
|
||||
envFile := filepath.Join(abs, ".env.local")
|
||||
f := &fakeCommandRunner{results: map[string]fakeCallResult{"env-pull": envPullOK(envFile)}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
@@ -1413,7 +1451,8 @@ func TestAppsInit_AlreadyInitialized_EnvPullFailure_NonFatal(t *testing.T) {
|
||||
},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
stubAppType(reg, "app_x", "FULL_STACK")
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("env-pull failure must be non-fatal, got: %v", err)
|
||||
}
|
||||
@@ -1705,13 +1744,15 @@ func TestScaffoldInitArgs_WithAppType(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPolicyForAppType(t *testing.T) {
|
||||
// modern_html decouples all control points: skip install, env-pull, skills sync.
|
||||
if p := policyForAppType("modern_html"); !p.skipInstall || !p.skipEnvPull || !p.skipSkillsSync {
|
||||
t.Errorf("modern_html policy = %+v, want all skip flags set", p)
|
||||
// modern_html and html decouple all control points: skip install, env-pull, skills sync, app sync.
|
||||
for _, at := range []string{"modern_html", "html"} {
|
||||
if p := policyForAppType(at); !p.skipInstall || !p.skipEnvPull || !p.skipSkillsSync || !p.skipAppSync {
|
||||
t.Errorf("%s policy = %+v, want all skip flags set", at, p)
|
||||
}
|
||||
}
|
||||
// Unlisted types (including "") get the zero-value policy: everything runs.
|
||||
for _, at := range []string{"full_stack", "", "backend"} {
|
||||
if p := policyForAppType(at); p.skipInstall || p.skipEnvPull || p.skipSkillsSync {
|
||||
if p := policyForAppType(at); p.skipInstall || p.skipEnvPull || p.skipSkillsSync || p.skipAppSync {
|
||||
t.Errorf("policy for %q = %+v, want zero value", at, p)
|
||||
}
|
||||
}
|
||||
@@ -1757,7 +1798,7 @@ func configSetValue(calls [][]string, key string) (string, bool) {
|
||||
func TestEnsureGitIdentity_SetsDefaultsWhenUnset(t *testing.T) {
|
||||
f := &fakeCommandRunner{} // no "git config" result → `--get` returns empty stdout
|
||||
withFakeRunner(t, f)
|
||||
if err := ensureGitIdentity(context.Background(), "/repo"); err != nil {
|
||||
if err := ensureGitIdentity(context.Background(), "/repo", "", ""); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if v, ok := configSetValue(f.calls, "user.name"); !ok || v != defaultGitUserName {
|
||||
@@ -1774,7 +1815,7 @@ func TestEnsureGitIdentity_RespectsExisting(t *testing.T) {
|
||||
"git config": {stdout: "Existing Dev\n"},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
if err := ensureGitIdentity(context.Background(), "/repo"); err != nil {
|
||||
if err := ensureGitIdentity(context.Background(), "/repo", "", ""); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if _, ok := configSetValue(f.calls, "user.name"); ok {
|
||||
@@ -1790,7 +1831,7 @@ func TestEnsureGitIdentity_SetFailurePropagates(t *testing.T) {
|
||||
"git config": {stderr: "boom", err: errors.New("exit 1")},
|
||||
}}
|
||||
withFakeRunner(t, f)
|
||||
if err := ensureGitIdentity(context.Background(), "/repo"); err == nil {
|
||||
if err := ensureGitIdentity(context.Background(), "/repo", "", ""); err == nil {
|
||||
t.Error("expected error when git config set fails")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,22 +13,25 @@ import (
|
||||
)
|
||||
|
||||
// queryAppType fetches the app's type string from the server via
|
||||
// GET /open-apis/spark/v1/apps/{appID}. The server returns uppercase
|
||||
// values ("HTML", "FULL_STACK", "MODERN_HTML"); this function normalizes
|
||||
// to lowercase. Returns "" when the API is unavailable or returns an
|
||||
// error — callers fall back to legacy behavior.
|
||||
func queryAppType(ctx context.Context, rctx *common.RuntimeContext, appID string) string {
|
||||
path := fmt.Sprintf("%s/apps/%s", apiBasePath, validate.EncodePathSegment(appID))
|
||||
// GET /open-apis/spark/v1/apps/{identifier}. The identifier can be either
|
||||
// an app_id or a meta_token — the server resolves both. The server returns
|
||||
// uppercase app_type values ("HTML", "FULL_STACK", "MODERN_HTML");
|
||||
// this function normalizes to lowercase. Returns an error when the API
|
||||
// is unavailable or the response is malformed — callers must not proceed
|
||||
// with a fallback type to avoid creating the wrong project scaffold.
|
||||
func queryAppType(ctx context.Context, rctx *common.RuntimeContext, identifier string) (string, error) {
|
||||
path := fmt.Sprintf("%s/apps/%s", apiBasePath, validate.EncodePathSegment(identifier))
|
||||
data, err := rctx.CallAPITyped("GET", path, nil, nil)
|
||||
if err != nil {
|
||||
fmt.Fprintf(rctx.IO().ErrOut, "→ Could not query app type: %v\n", err)
|
||||
return ""
|
||||
return "", err
|
||||
}
|
||||
appRaw, _ := data["app"].(map[string]interface{})
|
||||
if appRaw == nil {
|
||||
fmt.Fprintf(rctx.IO().ErrOut, "→ Could not query app type: response missing app object\n")
|
||||
return ""
|
||||
return "", appsSubprocessEnvelopeError("query app type: response missing app object")
|
||||
}
|
||||
appType, _ := appRaw["app_type"].(string)
|
||||
return strings.ToLower(appType)
|
||||
if strings.TrimSpace(appType) == "" {
|
||||
return "", appsSubprocessEnvelopeError("query app type: response missing app_type")
|
||||
}
|
||||
return strings.ToLower(appType), nil
|
||||
}
|
||||
|
||||
@@ -43,7 +43,10 @@ func TestQueryAppType_Success(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
result := queryAppType(context.Background(), rt, "app_test")
|
||||
result, err := queryAppType(context.Background(), rt, "app_test")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result != "modern_html" {
|
||||
t.Errorf("queryAppType = %q, want modern_html", result)
|
||||
}
|
||||
@@ -65,7 +68,10 @@ func TestQueryAppType_FullStack(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
result := queryAppType(context.Background(), rt, "app_fs")
|
||||
result, err := queryAppType(context.Background(), rt, "app_fs")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result != "full_stack" {
|
||||
t.Errorf("queryAppType = %q, want full_stack", result)
|
||||
}
|
||||
@@ -87,7 +93,10 @@ func TestQueryAppType_Html(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
result := queryAppType(context.Background(), rt, "app_html")
|
||||
result, err := queryAppType(context.Background(), rt, "app_html")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result != "html" {
|
||||
t.Errorf("queryAppType = %q, want html", result)
|
||||
}
|
||||
@@ -102,9 +111,9 @@ func TestQueryAppType_APIError(t *testing.T) {
|
||||
Body: map[string]interface{}{"code": float64(99999), "msg": "internal error"},
|
||||
})
|
||||
|
||||
result := queryAppType(context.Background(), rt, "app_bad")
|
||||
if result != "" {
|
||||
t.Errorf("queryAppType = %q, want empty on error", result)
|
||||
_, err := queryAppType(context.Background(), rt, "app_bad")
|
||||
if err == nil {
|
||||
t.Error("expected error on API failure")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,9 +128,9 @@ func TestQueryAppType_MissingAppObject(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
result := queryAppType(context.Background(), rt, "app_no")
|
||||
if result != "" {
|
||||
t.Errorf("queryAppType = %q, want empty when app object missing", result)
|
||||
_, err := queryAppType(context.Background(), rt, "app_no")
|
||||
if err == nil {
|
||||
t.Error("expected error when app object missing")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,8 +150,8 @@ func TestQueryAppType_EmptyAppType(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
result := queryAppType(context.Background(), rt, "app_empty")
|
||||
if result != "" {
|
||||
t.Errorf("queryAppType = %q, want empty when app_type is empty", result)
|
||||
_, err := queryAppType(context.Background(), rt, "app_empty")
|
||||
if err == nil {
|
||||
t.Error("expected error when app_type is empty")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,9 +31,13 @@ var AppsReleaseCreate = common.Shortcut{
|
||||
{Name: "branch", Desc: "release branch (server uses default if omitted)"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if strings.TrimSpace(rctx.Str("app-id")) == "" {
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
if appID == "" {
|
||||
return appsValidationParamError("--app-id", "--app-id is required")
|
||||
}
|
||||
if err := validateRealAppID(appID); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
|
||||
@@ -30,9 +30,13 @@ var AppsReleaseGet = common.Shortcut{
|
||||
{Name: "release-id", Desc: "release ID (the release_id returned by +release-create)", Required: true},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if strings.TrimSpace(rctx.Str("app-id")) == "" {
|
||||
appID := strings.TrimSpace(rctx.Str("app-id"))
|
||||
if appID == "" {
|
||||
return appsValidationParamError("--app-id", "--app-id is required")
|
||||
}
|
||||
if err := validateRealAppID(appID); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(rctx.Str("release-id")) == "" {
|
||||
return appsValidationParamError("--release-id", "--release-id is required")
|
||||
}
|
||||
|
||||
@@ -41,6 +41,21 @@ func withAppsHint(err error, hint string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// validateRealAppID checks that --app-id is a real app ID (app_ prefix).
|
||||
// meta_token values are rejected with a hint to resolve via +get first.
|
||||
func validateRealAppID(appID string) error {
|
||||
if !strings.HasPrefix(appID, "app_") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
`--app-id must be an app_id starting with "app_".`,
|
||||
).WithParam("--app-id").WithHint(
|
||||
`If you have a meta_token or a /page/<token>/ link, first resolve it:
|
||||
lark-cli apps +get --app-id <meta_token> -q '.data.app.app_id'
|
||||
Then retry this command with the returned app_id.`,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rejectOutputTraversal is a defense-in-depth pre-check on a user-supplied
|
||||
// --output path. The authoritative guard is the local FileIO layer
|
||||
// (validate.SafeOutputPath sandboxes every write to the cwd, resolving .. and
|
||||
|
||||
@@ -75,6 +75,7 @@ var AppsGitCredentialInit = common.Shortcut{
|
||||
"save the issued PAT in the local system credential store",
|
||||
"write app-scoped git credential metadata",
|
||||
"configure a URL-scoped Git credential helper in global git config when possible",
|
||||
"return commit_author_name and commit_author_email for repo-local git identity",
|
||||
}).
|
||||
Params(gitCredentialIssueParams(appID))
|
||||
},
|
||||
@@ -90,6 +91,12 @@ var AppsGitCredentialInit = common.Shortcut{
|
||||
"repository_url": result.GitHTTPURL,
|
||||
"status": initStatus(result),
|
||||
}
|
||||
if result.CommitAuthorName != "" {
|
||||
payload["commit_author_name"] = result.CommitAuthorName
|
||||
}
|
||||
if result.CommitAuthorEmail != "" {
|
||||
payload["commit_author_email"] = result.CommitAuthorEmail
|
||||
}
|
||||
if result.ConfigWarning != "" {
|
||||
payload["git_config_warning"] = result.ConfigWarning
|
||||
}
|
||||
@@ -461,11 +468,13 @@ func issuedFromData(appID string, data map[string]interface{}) (*gitcred.IssuedC
|
||||
}
|
||||
}
|
||||
issued := &gitcred.IssuedCredential{
|
||||
AppID: firstString(source, "app_id", appID),
|
||||
GitHTTPURL: firstString(source, "gitURL", "GitURL", "GitUrl", "gitUrl", "git_url", "git_http_url", "repository_url"),
|
||||
Username: firstString(source, "username"),
|
||||
PAT: firstString(source, "token", "Token", "pat", "password"),
|
||||
ExpiresAt: firstInt64(source, "expiredTime", "ExpiredTime", "expired_time", "expires_at"),
|
||||
AppID: firstString(source, "app_id", appID),
|
||||
GitHTTPURL: firstString(source, "gitURL", "GitURL", "GitUrl", "gitUrl", "git_url", "git_http_url", "repository_url"),
|
||||
Username: firstString(source, "username"),
|
||||
PAT: firstString(source, "token", "Token", "pat", "password"),
|
||||
ExpiresAt: firstInt64(source, "expiredTime", "ExpiredTime", "expired_time", "expires_at"),
|
||||
CommitAuthorName: firstString(source, "commit_author_name"),
|
||||
CommitAuthorEmail: firstString(source, "commit_author_email"),
|
||||
}
|
||||
if issued.AppID == "" {
|
||||
issued.AppID = appID
|
||||
|
||||
@@ -87,6 +87,7 @@ func TestAppsGitCredentialInitDryRunRequestShape(t *testing.T) {
|
||||
"save the issued PAT in the local system credential store",
|
||||
"write app-scoped git credential metadata",
|
||||
"configure a URL-scoped Git credential helper in global git config when possible",
|
||||
"return commit_author_name and commit_author_email for repo-local git identity",
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +129,13 @@ func (m *Manager) Init(ctx context.Context, profile ProfileContext, appID string
|
||||
if previous != nil && previous.PATRef != "" && previous.PATRef != ref {
|
||||
_ = m.Secrets.Remove(previous.PATRef)
|
||||
}
|
||||
result := &InitResult{AppID: appID, GitHTTPURL: url, Refreshed: previous != nil}
|
||||
result := &InitResult{
|
||||
AppID: appID,
|
||||
GitHTTPURL: url,
|
||||
Refreshed: previous != nil,
|
||||
CommitAuthorName: issued.CommitAuthorName,
|
||||
CommitAuthorEmail: issued.CommitAuthorEmail,
|
||||
}
|
||||
if m.GitConfig != nil {
|
||||
if err := m.GitConfig.SetHelper(ctx, url, appID); err != nil {
|
||||
result.ConfigWarning = err.Error()
|
||||
|
||||
@@ -51,18 +51,22 @@ type CredentialRecord struct {
|
||||
}
|
||||
|
||||
type IssuedCredential struct {
|
||||
AppID string
|
||||
GitHTTPURL string
|
||||
Username string
|
||||
PAT string
|
||||
ExpiresAt int64
|
||||
AppID string
|
||||
GitHTTPURL string
|
||||
Username string
|
||||
PAT string
|
||||
ExpiresAt int64
|
||||
CommitAuthorName string
|
||||
CommitAuthorEmail string
|
||||
}
|
||||
|
||||
type InitResult struct {
|
||||
AppID string
|
||||
GitHTTPURL string
|
||||
Refreshed bool
|
||||
ConfigWarning string
|
||||
AppID string
|
||||
GitHTTPURL string
|
||||
Refreshed bool
|
||||
ConfigWarning string
|
||||
CommitAuthorName string
|
||||
CommitAuthorEmail string
|
||||
}
|
||||
|
||||
type RemoveResult struct {
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
type htmlPublishResponse struct {
|
||||
URL string
|
||||
}
|
||||
|
||||
type appsHTMLPublishClient interface {
|
||||
HTMLPublish(ctx context.Context, appID string, tarball *htmlPublishTarball) (*htmlPublishResponse, error)
|
||||
}
|
||||
|
||||
type appsHTMLPublishAPI struct {
|
||||
runtime *common.RuntimeContext
|
||||
}
|
||||
|
||||
func (api appsHTMLPublishAPI) HTMLPublish(ctx context.Context, appID string, tarball *htmlPublishTarball) (*htmlPublishResponse, error) {
|
||||
fd := larkcore.NewFormdata()
|
||||
fd.AddFile("file", bytes.NewReader(tarball.Body))
|
||||
|
||||
apiResp, err := api.runtime.DoAPI(&larkcore.ApiReq{
|
||||
HttpMethod: http.MethodPost,
|
||||
ApiPath: fmt.Sprintf("%s/apps/%s/upload_and_release_html_code", apiBasePath, validate.EncodePathSegment(appID)),
|
||||
Body: fd,
|
||||
}, larkcore.WithFileUpload())
|
||||
if err != nil {
|
||||
return nil, client.WrapDoAPIError(err)
|
||||
}
|
||||
data, err := api.runtime.ClassifyAPIResponse(apiResp)
|
||||
if err != nil {
|
||||
return nil, enrichHTMLPublishAPIError(err)
|
||||
}
|
||||
url, _ := data["url"].(string)
|
||||
if url == "" {
|
||||
return nil, errs.NewInternalError(errs.SubtypeInvalidResponse,
|
||||
"html-publish response is missing the published app url")
|
||||
}
|
||||
return &htmlPublishResponse{URL: url}, nil
|
||||
}
|
||||
|
||||
// OAPI business error codes returned by the
|
||||
// /apps/{id}/upload_and_release_html_code endpoint. Owned by the backend
|
||||
// service; update when new codes are documented in the OAPI spec.
|
||||
const (
|
||||
errCodeBuildFailed = 90001 // tar.gz uploaded but server-side build failed
|
||||
errCodeAppNotFound = 90002 // app_id unknown or caller lacks permission
|
||||
)
|
||||
|
||||
func buildHTMLPublishFailureHint(code int) string {
|
||||
switch code {
|
||||
case errCodeBuildFailed:
|
||||
return "server-side build failed: run `lark-cli apps +html-publish --app-id <your-app-id> --path <path> --dry-run` to inspect the packaged file list"
|
||||
case errCodeAppNotFound:
|
||||
return "the app does not exist or the caller has no access; ask the user to confirm the app_id (extract it from the app URL https://miaoda.feishu.cn/app/app_xxx after /app/, or take the app_xxx string directly)"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
func newAppsClientRuntime(t *testing.T) (*common.RuntimeContext, *httpmock.Registry) {
|
||||
t.Helper()
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
cfg := &core.CliConfig{
|
||||
AppID: "test-app-" + strings.ToLower(t.Name()),
|
||||
AppSecret: "test-secret",
|
||||
Brand: core.BrandFeishu,
|
||||
UserOpenId: "ou_test",
|
||||
}
|
||||
factory, _, _, reg := cmdutil.TestFactory(t, cfg)
|
||||
rctx := common.TestNewRuntimeContextForAPI(context.Background(), nil, cfg, factory, core.AsUser)
|
||||
return rctx, reg
|
||||
}
|
||||
|
||||
func TestAppsHTMLPublishAPI_Success(t *testing.T) {
|
||||
rctx, reg := newAppsClientRuntime(t)
|
||||
stub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"url": "https://miaoda.feishu.cn/app/app_x",
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(stub)
|
||||
|
||||
api := appsHTMLPublishAPI{runtime: rctx}
|
||||
tarball := &htmlPublishTarball{Body: []byte("fake"), Size: 4, SHA256: "abc"}
|
||||
resp, err := api.HTMLPublish(context.Background(), "app_x", tarball)
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if resp.URL != "https://miaoda.feishu.cn/app/app_x" {
|
||||
t.Fatalf("url=%q", resp.URL)
|
||||
}
|
||||
|
||||
ct := stub.CapturedHeaders.Get("Content-Type")
|
||||
mt, params, err := mime.ParseMediaType(ct)
|
||||
if err != nil || mt != "multipart/form-data" {
|
||||
t.Fatalf("content type %q wrong", ct)
|
||||
}
|
||||
mr := multipart.NewReader(bytes.NewReader(stub.CapturedBody), params["boundary"])
|
||||
saw := false
|
||||
for {
|
||||
p, err := mr.NextPart()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if p.FormName() == "file" {
|
||||
saw = true
|
||||
}
|
||||
}
|
||||
if !saw {
|
||||
t.Fatalf("multipart missing 'file' part")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsHTMLPublishAPI_BusinessErrorHasHint(t *testing.T) {
|
||||
rctx, reg := newAppsClientRuntime(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
|
||||
Body: map[string]interface{}{
|
||||
"code": 90001,
|
||||
"msg": "build failed: dependency conflict",
|
||||
},
|
||||
})
|
||||
|
||||
api := appsHTMLPublishAPI{runtime: rctx}
|
||||
_, err := api.HTMLPublish(context.Background(), "app_x", &htmlPublishTarball{Body: []byte("fake")})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error")
|
||||
}
|
||||
problem := requireAppsAPIProblem(t, err)
|
||||
if problem.Code != errCodeBuildFailed {
|
||||
t.Fatalf("code = %d, want %d", problem.Code, errCodeBuildFailed)
|
||||
}
|
||||
if problem.Hint == "" {
|
||||
t.Fatalf("expected non-empty hint on code 90001")
|
||||
}
|
||||
if !strings.Contains(problem.Message, "build failed") {
|
||||
t.Fatalf("missing failure message: %v", problem.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsHTMLPublishAPI_AppNotFoundClassified(t *testing.T) {
|
||||
rctx, reg := newAppsClientRuntime(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/spark/v1/apps/app_missing/upload_and_release_html_code",
|
||||
Body: map[string]interface{}{
|
||||
"code": errCodeAppNotFound,
|
||||
"msg": "app not found",
|
||||
},
|
||||
})
|
||||
|
||||
api := appsHTMLPublishAPI{runtime: rctx}
|
||||
_, err := api.HTMLPublish(context.Background(), "app_missing", &htmlPublishTarball{Body: []byte("fake")})
|
||||
problem := requireAppsAPIProblem(t, err)
|
||||
if problem.Subtype != errs.SubtypeNotFound {
|
||||
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeNotFound)
|
||||
}
|
||||
if problem.Hint == "" {
|
||||
t.Fatalf("expected app-not-found recovery hint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsHTMLPublishAPI_MissingURLIsInvalidResponse(t *testing.T) {
|
||||
rctx, reg := newAppsClientRuntime(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": map[string]interface{}{},
|
||||
},
|
||||
})
|
||||
|
||||
api := appsHTMLPublishAPI{runtime: rctx}
|
||||
_, err := api.HTMLPublish(context.Background(), "app_x", &htmlPublishTarball{Body: []byte("fake")})
|
||||
problem := requireAppsProblem(t, err, errs.CategoryInternal)
|
||||
if problem.Subtype != errs.SubtypeInvalidResponse {
|
||||
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeInvalidResponse)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildHTMLPublishFailureHint_UnknownCodeReturnsEmpty(t *testing.T) {
|
||||
// 默认分支:未识别的 code 返回空 hint,让 Agent 用 message 兜底。
|
||||
if hint := buildHTMLPublishFailureHint(99999); hint != "" {
|
||||
t.Fatalf("unknown code should return empty hint, got %q", hint)
|
||||
}
|
||||
if hint := buildHTMLPublishFailureHint(0); hint != "" {
|
||||
t.Fatalf("zero code should return empty hint, got %q", hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildHTMLPublishFailureHint_KnownCodes(t *testing.T) {
|
||||
if hint := buildHTMLPublishFailureHint(90001); hint == "" {
|
||||
t.Fatalf("code 90001 should return non-empty hint")
|
||||
}
|
||||
if hint := buildHTMLPublishFailureHint(90002); hint == "" {
|
||||
t.Fatalf("code 90002 should return non-empty hint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildHTMLPublishFailureHint_NotFoundHintNoLongerMentionsList(t *testing.T) {
|
||||
hint := buildHTMLPublishFailureHint(90002)
|
||||
if hint == "" {
|
||||
t.Fatalf("code 90002 should return non-empty hint")
|
||||
}
|
||||
if strings.Contains(hint, "+list") {
|
||||
t.Fatalf("hint must not point at hidden +list command, got: %q", hint)
|
||||
}
|
||||
if !strings.Contains(hint, "app_id") {
|
||||
t.Fatalf("hint should reference app_id, got: %q", hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsHTMLPublishAPI_MalformedResponseIsInvalidResponse(t *testing.T) {
|
||||
rctx, reg := newAppsClientRuntime(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
|
||||
RawBody: []byte("{not json"),
|
||||
})
|
||||
|
||||
api := appsHTMLPublishAPI{runtime: rctx}
|
||||
_, err := api.HTMLPublish(context.Background(), "app_x", &htmlPublishTarball{Body: []byte("fake")})
|
||||
problem := requireAppsProblem(t, err, errs.CategoryInternal)
|
||||
if problem.Subtype != errs.SubtypeInvalidResponse {
|
||||
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeInvalidResponse)
|
||||
}
|
||||
}
|
||||
@@ -2014,16 +2014,14 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"has_more": false,
|
||||
"record_id_list": []interface{}{"rec_1"},
|
||||
"update": map[string]interface{}{"Status": "Done"},
|
||||
"ignored_fields": []interface{}{"Formula"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseRecordBatchUpdate, []string{"+record-batch-update", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"record_id_list":["rec_1"],"patch":{"Status":"Done"}}`}, factory, stdout); err != nil {
|
||||
if err := runShortcut(t, BaseRecordBatchUpdate, []string{"+record-batch-update", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"update_records":{"rec_1":{"Status":["Done"]}}}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"update"`) || !strings.Contains(got, `"Done"`) {
|
||||
if got := stdout.String(); !strings.Contains(got, `"ignored_fields"`) || !strings.Contains(got, `"Formula"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
@@ -2035,20 +2033,16 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_update",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"record_id_list": []interface{}{"rec_1"},
|
||||
},
|
||||
"data": map[string]interface{}{},
|
||||
},
|
||||
}
|
||||
reg.Register(updateStub)
|
||||
if err := runShortcut(t, BaseRecordBatchUpdate, []string{"+record-batch-update", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"record_id_list":["rec_1"],"patch":{"Name":"Alice","Status":"Done"}}`}, factory, stdout); err != nil {
|
||||
input := `{"update_records":{"recA":{"Status":["Done"]},"recB":{"Score":20}}}`
|
||||
if err := runShortcut(t, BaseRecordBatchUpdate, []string{"+record-batch-update", "--base-token", "app_x", "--table-id", "tbl_x", "--json", input}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
body := string(updateStub.CapturedBody)
|
||||
if !strings.Contains(body, `"record_id_list":["rec_1"]`) || !strings.Contains(body, `"patch":{"Name":"Alice","Status":"Done"}`) {
|
||||
if !strings.Contains(body, `"update_records":{"recA":{"Status":["Done"]},"recB":{"Score":20}}`) {
|
||||
t.Fatalf("request body=%s", body)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -786,7 +786,8 @@ func TestBaseJSONExamplesLiveInFlagDescriptions(t *testing.T) {
|
||||
name: "record batch update json",
|
||||
shortcut: BaseRecordBatchUpdate,
|
||||
wantHelp: []string{
|
||||
`batch update JSON object, e.g. {"record_id_list":["rec_xxx"],"patch":{"Status":"Done"}}; same patch applies to all records`,
|
||||
"update_records maps each record ID to its field map",
|
||||
`{"update_records":{"recA":{"Status":["Done"]},"recB":{"Score":20}}}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -854,9 +855,11 @@ func TestBaseRecordWriteHelpGuidesAgents(t *testing.T) {
|
||||
name: "record batch update",
|
||||
shortcut: BaseRecordBatchUpdate,
|
||||
wantTips: []string{
|
||||
"Happy path fields: record_id_list is the target record IDs",
|
||||
"patch is a field map applied unchanged to every target record",
|
||||
"Do not use +record-batch-update for per-row different values",
|
||||
"Happy path field: update_records",
|
||||
"update_records maps each record ID to its own field map",
|
||||
`{"update_records":{"recA":{"Status":["Done"]},"recB":{"Score":20}}}`,
|
||||
"contains only optional ignored_fields",
|
||||
"does not check whether record IDs exist",
|
||||
"use +field-list to confirm real writable fields",
|
||||
"Batch update supports max 200 records per call",
|
||||
"CellValue happy path: text/phone/url",
|
||||
|
||||
@@ -12,18 +12,19 @@ import (
|
||||
var BaseRecordBatchUpdate = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+record-batch-update",
|
||||
Description: "Batch update records",
|
||||
Description: "Batch update records with record-specific fields",
|
||||
Risk: "write",
|
||||
Scopes: []string{"base:record:update"},
|
||||
AuthTypes: authTypes(),
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "json", Desc: `batch update JSON object, e.g. {"record_id_list":["rec_xxx"],"patch":{"Status":"Done"}}; same patch applies to all records`, Required: true},
|
||||
{Name: "json", Desc: `batch update JSON object; update_records maps each record ID to its field map, e.g. {"update_records":{"recA":{"Status":["Done"]},"recB":{"Score":20}}}`, Required: true},
|
||||
},
|
||||
Tips: append([]string{
|
||||
"Happy path fields: record_id_list is the target record IDs; patch is a field map applied unchanged to every target record.",
|
||||
"Do not use +record-batch-update for per-row different values; call +record-upsert per record or use another supported flow.",
|
||||
"Happy path field: update_records maps each record ID to its own field map.",
|
||||
`Example: {"update_records":{"recA":{"Status":["Done"]},"recB":{"Score":20}}}.`,
|
||||
"The response contains only optional ignored_fields and does not check whether record IDs exist; read records back when confirmation is required.",
|
||||
"Before writing, use +field-list to confirm real writable fields; do not write system fields, formula, lookup, or attachment fields as normal CellValue.",
|
||||
"Batch update supports max 200 records per call; use the record-batch-update guide for command limits and edge cases.",
|
||||
}, recordCellValueHappyPathTips...),
|
||||
|
||||
790
shortcuts/calendar/calendar_room_check.go
Normal file
790
shortcuts/calendar/calendar_room_check.go
Normal file
@@ -0,0 +1,790 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// calendar +update room-availability pre-check helpers.
|
||||
//
|
||||
// Uses /open-apis/calendar/v4/freebusy/room_availability_check to warn the
|
||||
// caller before an update either adds a new room attendee or shifts the time
|
||||
// of a slot that already has a room reservation. --skip-room-check bypasses
|
||||
// the check for callers that want to move fast.
|
||||
|
||||
package calendar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
const (
|
||||
flagSkipRoomCheck = "skip-room-check"
|
||||
roomCheckPath = "/open-apis/calendar/v4/freebusy/room_availability_check"
|
||||
)
|
||||
|
||||
// roomAvailability mirrors a single room result from the API.
|
||||
type roomAvailability struct {
|
||||
RoomID string `json:"room_id,omitempty"`
|
||||
RoomName string `json:"room_name,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
UnavailableReasonType string `json:"unavailable_reason_type,omitempty"`
|
||||
Strategy *roomStrategy `json:"room_strategy,omitempty"`
|
||||
Requisition *roomRequisition `json:"room_requisition,omitempty"`
|
||||
ApprovalInfo *roomApprovalInfo `json:"room_approval_info,omitempty"`
|
||||
}
|
||||
|
||||
// roomStrategy mirrors the room_strategy block returned by the API on
|
||||
// unavailable rooms. Every field is optional: the server only fills in the
|
||||
// entries relevant to the current unavailable_reason_type.
|
||||
type roomStrategy struct {
|
||||
SingleMaxDuration string `json:"single_max_duration,omitempty"`
|
||||
MaxAdvanceBookingTime string `json:"max_advance_booking_time,omitempty"`
|
||||
DailyStartTime string `json:"daily_start_time,omitempty"`
|
||||
DailyEndTime string `json:"daily_end_time,omitempty"`
|
||||
Timezone string `json:"timezone,omitempty"`
|
||||
DailyAdvanceWindowReleaseTime string `json:"daily_advance_window_release_time,omitempty"`
|
||||
}
|
||||
|
||||
// roomRequisition mirrors room_requisition, returned by the API only when
|
||||
// unavailable_reason_type == "during_requisition". Both fields are RFC3339
|
||||
// strings and either may be empty if the server has no exact bound.
|
||||
type roomRequisition struct {
|
||||
StartTime string `json:"start_time,omitempty"`
|
||||
EndTime string `json:"end_time,omitempty"`
|
||||
}
|
||||
|
||||
// roomApprovalInfo mirrors room_approval_info, returned when the room requires
|
||||
// (or may require) an approval submission before it can be booked.
|
||||
//
|
||||
// - ApprovalMode: "none" (no approval), "over_duration" (only when the
|
||||
// booking exceeds the threshold), or "all" (every booking needs approval).
|
||||
// - ApprovalDurationThreshold: seconds; only meaningful when
|
||||
// ApprovalMode == "over_duration". The server returns it as a numeric
|
||||
// string, matching the shape of the other duration fields.
|
||||
//
|
||||
// When the pre-check returns status == "need_approval" the caller renders a
|
||||
// friendly reminder derived from these two fields plus the current event
|
||||
// duration, so the agent knows whether to switch rooms/times or route the
|
||||
// user through an approval flow.
|
||||
type roomApprovalInfo struct {
|
||||
ApprovalMode string `json:"approval_mode,omitempty"`
|
||||
ApprovalDurationThreshold string `json:"approval_duration_threshold,omitempty"`
|
||||
}
|
||||
|
||||
// eventSnapshot carries only the fields room-check needs from the current
|
||||
// event: existing room IDs, current start/end (unix seconds string), timezone,
|
||||
// and rrule.
|
||||
type eventSnapshot struct {
|
||||
RoomIDs []string
|
||||
StartTs string
|
||||
EndTs string
|
||||
Timezone string
|
||||
Recurrent string
|
||||
}
|
||||
|
||||
// unavailableReasonHint maps API-declared unavailable reasons to a short
|
||||
// English phrase suitable for embedding in the block message. Unknown or
|
||||
// future reasons fall back to a single stable phrase so the CLI's blocked
|
||||
// message stays predictable for agents that parse it.
|
||||
func unavailableReasonHint(reason string) string {
|
||||
switch reason {
|
||||
case "reserved_by_other_event":
|
||||
return "already reserved by another event"
|
||||
case "past_time":
|
||||
return "cannot book a room in the past"
|
||||
case "beyond_advance_booking_window":
|
||||
return "beyond the room's advance-booking window"
|
||||
case "over_max_duration":
|
||||
return "exceeds the room's max single-booking duration"
|
||||
case "not_in_usable_time":
|
||||
return "outside the room's daily bookable window"
|
||||
case "during_requisition":
|
||||
return "the room is disabled during this time and cannot be booked"
|
||||
case "before_daily_advance_window_release":
|
||||
return "the target date is outside the room's currently unlocked advance-booking window; the window extends by one calendar day at the daily release time"
|
||||
case "recurring_exceed_approval_limit":
|
||||
return "recurring event duration exceeds the limit for booking this approval-required room — shorten the duration or pick a different room"
|
||||
default:
|
||||
return "currently unbookable"
|
||||
}
|
||||
}
|
||||
|
||||
// strategyDetail renders the human-readable suffix appended to the reason
|
||||
// phrase for a given (reason, strategy) pair. It returns an empty string when
|
||||
// no strategy data is available or when the fields relevant to this reason
|
||||
// are missing / invalid, so callers can safely concatenate the result.
|
||||
func strategyDetail(reason string, s *roomStrategy) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
switch reason {
|
||||
case "over_max_duration":
|
||||
if d := formatDurationSeconds(s.SingleMaxDuration); d != "" {
|
||||
return "the max single-booking duration is " + d
|
||||
}
|
||||
case "beyond_advance_booking_window":
|
||||
// The API returns max_advance_booking_time as RFC3339 already;
|
||||
// surface it verbatim so agents don't lose the exact instant.
|
||||
if t := strings.TrimSpace(s.MaxAdvanceBookingTime); t != "" {
|
||||
return "the latest bookable end time is " + t
|
||||
}
|
||||
case "not_in_usable_time":
|
||||
start := formatDaySeconds(s.DailyStartTime)
|
||||
end := formatDaySeconds(s.DailyEndTime)
|
||||
zone := roomZoneLabel(s.Timezone)
|
||||
switch {
|
||||
case start != "" && end != "":
|
||||
return fmt.Sprintf("the daily bookable window is %s - %s (%s)", start, end, zone)
|
||||
case start != "":
|
||||
return fmt.Sprintf("the daily bookable window starts at %s (%s)", start, zone)
|
||||
case end != "":
|
||||
return fmt.Sprintf("the daily bookable window ends at %s (%s)", end, zone)
|
||||
}
|
||||
case "before_daily_advance_window_release":
|
||||
if t := formatDaySeconds(s.DailyAdvanceWindowReleaseTime); t != "" {
|
||||
return fmt.Sprintf("the next unlock happens today at %s (%s), which advances the window by one day", t, roomZoneLabel(s.Timezone))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// requisitionDetail renders the suffix describing the room's scheduled
|
||||
// disable window for a `during_requisition` block. The API sends both bounds
|
||||
// as RFC3339 already, so we surface them verbatim to keep the exact instant.
|
||||
// Returns "" when both bounds are missing so the caller falls back to the
|
||||
// generic "pick a different time or a different room" recovery hint.
|
||||
func requisitionDetail(reason string, r *roomRequisition) string {
|
||||
if reason != "during_requisition" || r == nil {
|
||||
return ""
|
||||
}
|
||||
start := strings.TrimSpace(r.StartTime)
|
||||
end := strings.TrimSpace(r.EndTime)
|
||||
switch {
|
||||
case start != "" && end != "":
|
||||
return fmt.Sprintf("the disabled period is %s to %s", start, end)
|
||||
case start != "":
|
||||
return "the disabled period starts at " + start
|
||||
case end != "":
|
||||
return "the disabled period ends at " + end
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// formatDurationSeconds renders a whole-second string like "10800" as a
|
||||
// compact "H hours [M minutes]" phrase. Returns "" when the value is
|
||||
// missing, non-numeric, or non-positive.
|
||||
func formatDurationSeconds(raw string) string {
|
||||
sec, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil || sec <= 0 {
|
||||
return ""
|
||||
}
|
||||
d := time.Duration(sec) * time.Second
|
||||
h := int(d / time.Hour)
|
||||
m := int((d % time.Hour) / time.Minute)
|
||||
switch {
|
||||
case h > 0 && m > 0:
|
||||
return fmt.Sprintf("%d hours %d minutes", h, m)
|
||||
case h > 0:
|
||||
return fmt.Sprintf("%d hours", h)
|
||||
case m > 0:
|
||||
return fmt.Sprintf("%d minutes", m)
|
||||
default:
|
||||
return fmt.Sprintf("%d seconds", sec)
|
||||
}
|
||||
}
|
||||
|
||||
// formatDaySeconds renders a "seconds since midnight" string as "HH:MM".
|
||||
// Returns "" when raw is missing, non-numeric, or outside [0, 24h). Seconds
|
||||
// are truncated because the API only guarantees minute-level meaning for
|
||||
// daily windows and release times.
|
||||
func formatDaySeconds(raw string) string {
|
||||
sec, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil || sec < 0 || sec >= 24*3600 {
|
||||
return ""
|
||||
}
|
||||
h := sec / 3600
|
||||
m := (sec % 3600) / 60
|
||||
return fmt.Sprintf("%02d:%02d", h, m)
|
||||
}
|
||||
|
||||
// roomZoneLabel renders the room's timezone as either a "GMT±X" string
|
||||
// anchored to today (so DST is respected) when the IANA name resolves, or
|
||||
// the IANA name itself as a fallback so agents always see the source of
|
||||
// truth. Returns the local device timezone's label when raw is empty.
|
||||
func roomZoneLabel(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return gmtOffsetLabel(time.Now())
|
||||
}
|
||||
loc, err := time.LoadLocation(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return gmtOffsetLabel(time.Now().In(loc))
|
||||
}
|
||||
|
||||
// gmtOffsetLabel formats t's zone offset as "GMT+8" / "GMT-5:30" / "GMT".
|
||||
// Minute-precision is included only when the offset has a non-zero minute
|
||||
// component so the common whole-hour case stays terse.
|
||||
func gmtOffsetLabel(t time.Time) string {
|
||||
_, offsetSec := t.Zone()
|
||||
if offsetSec == 0 {
|
||||
return "GMT"
|
||||
}
|
||||
sign := "+"
|
||||
if offsetSec < 0 {
|
||||
sign = "-"
|
||||
offsetSec = -offsetSec
|
||||
}
|
||||
h := offsetSec / 3600
|
||||
m := (offsetSec % 3600) / 60
|
||||
if m == 0 {
|
||||
return fmt.Sprintf("GMT%s%d", sign, h)
|
||||
}
|
||||
return fmt.Sprintf("GMT%s%d:%02d", sign, h, m)
|
||||
}
|
||||
|
||||
// collectAttendeeRoomIDs extracts omm_ prefixed IDs from a comma-separated
|
||||
// flag value. Empty / whitespace input returns nil.
|
||||
func collectAttendeeRoomIDs(raw string) []string {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return nil
|
||||
}
|
||||
var rooms []string
|
||||
seen := map[string]struct{}{}
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
id := strings.TrimSpace(part)
|
||||
if !strings.HasPrefix(id, "omm_") {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
rooms = append(rooms, id)
|
||||
}
|
||||
return rooms
|
||||
}
|
||||
|
||||
// fetchEventSnapshot GETs the event with attendees so we can read the current
|
||||
// start / end / recurrence and the room IDs already booked on the event. It is
|
||||
// best-effort: any error bubbles up so the caller can降级放行 by warning.
|
||||
//
|
||||
// One retry is baked in: a `{uid}_{original_time}` event_id refers to a
|
||||
// specific instance of a recurring series, but until that instance is edited
|
||||
// and materialised as an exception, the server only knows the master
|
||||
// (`{uid}_0`) and answers 193001 (event not found). We detect that shape and
|
||||
// re-issue the GET against the master so the room-check pipeline still has a
|
||||
// snapshot to work with.
|
||||
func fetchEventSnapshot(_ context.Context, runtime *common.RuntimeContext, calendarID, eventID string) (*eventSnapshot, error) {
|
||||
data, err := callEventGet(runtime, calendarID, eventID)
|
||||
if err != nil {
|
||||
if masterID, ok := recurringMasterEventID(eventID); ok && isEventNotFound(err) {
|
||||
data, err = callEventGet(runtime, calendarID, masterID)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
event, _ := data["event"].(map[string]interface{})
|
||||
if event == nil {
|
||||
return nil, errs.NewInternalError(errs.SubtypeInvalidResponse, "calendar event response missing 'event' field")
|
||||
}
|
||||
snap := &eventSnapshot{}
|
||||
if start, _ := event["start_time"].(map[string]interface{}); start != nil {
|
||||
if ts, _ := start["timestamp"].(string); ts != "" {
|
||||
snap.StartTs = ts
|
||||
}
|
||||
if tz, _ := start["timezone"].(string); tz != "" {
|
||||
snap.Timezone = tz
|
||||
}
|
||||
}
|
||||
if end, _ := event["end_time"].(map[string]interface{}); end != nil {
|
||||
if ts, _ := end["timestamp"].(string); ts != "" {
|
||||
snap.EndTs = ts
|
||||
}
|
||||
if snap.Timezone == "" {
|
||||
if tz, _ := end["timezone"].(string); tz != "" {
|
||||
snap.Timezone = tz
|
||||
}
|
||||
}
|
||||
}
|
||||
if r, _ := event["recurrence"].(string); r != "" {
|
||||
snap.Recurrent = r
|
||||
}
|
||||
attendees, _ := event["attendees"].([]interface{})
|
||||
seen := map[string]struct{}{}
|
||||
for _, raw := range attendees {
|
||||
m, ok := raw.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if t, _ := m["type"].(string); t != "resource" {
|
||||
continue
|
||||
}
|
||||
id, _ := m["room_id"].(string)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if status, _ := m["rsvp_status"].(string); status == "removed" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
snap.RoomIDs = append(snap.RoomIDs, id)
|
||||
}
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
// callEventGet issues the calendar event GET used by fetchEventSnapshot. It
|
||||
// is factored out so the 193001 fallback can re-issue the request against
|
||||
// the master event without duplicating the params / path plumbing.
|
||||
func callEventGet(runtime *common.RuntimeContext, calendarID, eventID string) (map[string]interface{}, error) {
|
||||
path := fmt.Sprintf("/open-apis/calendar/v4/calendars/%s/events/%s",
|
||||
validate.EncodePathSegment(calendarID), validate.EncodePathSegment(eventID))
|
||||
params := map[string]interface{}{
|
||||
"user_id_type": "open_id",
|
||||
"need_attendee": true,
|
||||
"max_attendee_num": 20,
|
||||
}
|
||||
return runtime.CallAPITyped("GET", path, params, nil)
|
||||
}
|
||||
|
||||
// recurringMasterEventID inspects a calendar event_id shaped like
|
||||
// `{uid}_{original_time}` and returns `{uid}_0` when original_time is a
|
||||
// positive integer, plus true so callers know a fallback is worth trying.
|
||||
// Any other shape (missing underscore, non-numeric suffix, already `_0`, or
|
||||
// suffix `0` / negative) returns "", false so we don't retry pointlessly.
|
||||
func recurringMasterEventID(eventID string) (string, bool) {
|
||||
idx := strings.LastIndex(eventID, "_")
|
||||
if idx <= 0 || idx == len(eventID)-1 {
|
||||
return "", false
|
||||
}
|
||||
uid := eventID[:idx]
|
||||
suffix := eventID[idx+1:]
|
||||
n, err := strconv.ParseInt(suffix, 10, 64)
|
||||
if err != nil || n <= 0 {
|
||||
return "", false
|
||||
}
|
||||
return uid + "_0", true
|
||||
}
|
||||
|
||||
// isEventNotFound returns true when err is a calendar 193001 (event not
|
||||
// found) API error. Kept in this file rather than shared with
|
||||
// unwrapCalendarAPIError because that helper returns a user-facing hint —
|
||||
// here we only need the classification, not the copy.
|
||||
func isEventNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var ae *errs.APIError
|
||||
if !errors.As(err, &ae) {
|
||||
return false
|
||||
}
|
||||
return ae.Code == 193001
|
||||
}
|
||||
|
||||
// roomCheckPlan bundles the resolved inputs for the pre-check API call.
|
||||
type roomCheckPlan struct {
|
||||
RoomIDs []string
|
||||
StartTs string
|
||||
EndTs string
|
||||
StartTimezone string
|
||||
Rrule string
|
||||
}
|
||||
|
||||
// resolveRoomCheckPlan works out which rooms to check and the target time
|
||||
// window. It applies the降级放行 policy: if the event snapshot fails to load
|
||||
// but we can proceed with only user-provided inputs (i.e., time changed and a
|
||||
// new room is added), the pre-check still runs against those. Otherwise it
|
||||
// warns and returns (nil, nil) so the caller skips the check.
|
||||
//
|
||||
// Returns (nil, nil) when no check is warranted.
|
||||
func resolveRoomCheckPlan(ctx context.Context, runtime *common.RuntimeContext, calendarID, eventID string, newStartTs, newEndTs string, timeChanged, rruleChanged bool) (*roomCheckPlan, error) {
|
||||
newRooms := collectAttendeeRoomIDs(runtime.Str("add-attendee-ids"))
|
||||
removeSet := map[string]struct{}{}
|
||||
for _, id := range collectAttendeeRoomIDs(runtime.Str("remove-attendee-ids")) {
|
||||
removeSet[id] = struct{}{}
|
||||
}
|
||||
|
||||
// Fast path: only trigger the check when it can find something to look at.
|
||||
// - New room attendees → always check.
|
||||
// - Time or rrule change → check existing rooms if any.
|
||||
if len(newRooms) == 0 && !timeChanged && !rruleChanged {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
newRrule := strings.TrimSpace(runtime.Str("rrule"))
|
||||
|
||||
// If we don't need existing rooms and have both start/end, skip the GET.
|
||||
needSnapshot := timeChanged || rruleChanged || !timeChanged && len(newRooms) > 0
|
||||
|
||||
var snap *eventSnapshot
|
||||
if needSnapshot {
|
||||
var err error
|
||||
snap, err = fetchEventSnapshot(ctx, runtime, calendarID, eventID)
|
||||
if err != nil {
|
||||
fmt.Fprintf(runtime.IO().ErrOut,
|
||||
"[calendar +update] warning: failed to fetch current event for room-availability check (%v); precheck runs only against user-supplied inputs — pass --%s to silence\n",
|
||||
err, flagSkipRoomCheck)
|
||||
snap = nil
|
||||
}
|
||||
}
|
||||
|
||||
plan := &roomCheckPlan{
|
||||
StartTs: newStartTs,
|
||||
EndTs: newEndTs,
|
||||
Rrule: newRrule,
|
||||
}
|
||||
if plan.StartTs == "" && snap != nil {
|
||||
plan.StartTs = snap.StartTs
|
||||
}
|
||||
if plan.EndTs == "" && snap != nil {
|
||||
plan.EndTs = snap.EndTs
|
||||
}
|
||||
if plan.Rrule == "" && snap != nil {
|
||||
plan.Rrule = snap.Recurrent
|
||||
}
|
||||
if snap != nil {
|
||||
plan.StartTimezone = snap.Timezone
|
||||
}
|
||||
|
||||
seen := map[string]struct{}{}
|
||||
addRoom := func(id string) {
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := removeSet[id]; ok {
|
||||
return
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
plan.RoomIDs = append(plan.RoomIDs, id)
|
||||
}
|
||||
for _, id := range newRooms {
|
||||
addRoom(id)
|
||||
}
|
||||
if snap != nil && (timeChanged || rruleChanged) {
|
||||
for _, id := range snap.RoomIDs {
|
||||
addRoom(id)
|
||||
}
|
||||
}
|
||||
|
||||
if len(plan.RoomIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
// Without a target window the server has no basis to check anything;
|
||||
// prefer degrading gracefully to blocking legitimate updates.
|
||||
if plan.StartTs == "" || plan.EndTs == "" {
|
||||
fmt.Fprintf(runtime.IO().ErrOut,
|
||||
"[calendar +update] warning: room-availability check skipped because start/end could not be resolved; pass --%s to silence\n",
|
||||
flagSkipRoomCheck)
|
||||
return nil, nil
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// roomCheckPlanDurationSec returns the current booking duration in whole
|
||||
// seconds derived from the resolved plan's Unix-second window, or 0 when
|
||||
// either bound is missing or unparseable. Used to compare against
|
||||
// approval_duration_threshold when the API asks for approval.
|
||||
func roomCheckPlanDurationSec(plan *roomCheckPlan) int64 {
|
||||
if plan == nil {
|
||||
return 0
|
||||
}
|
||||
start, err := strconv.ParseInt(strings.TrimSpace(plan.StartTs), 10, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
end, err := strconv.ParseInt(strings.TrimSpace(plan.EndTs), 10, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
if end <= start {
|
||||
return 0
|
||||
}
|
||||
return end - start
|
||||
}
|
||||
|
||||
// buildRoomCheckBody assembles the request body for room_availability_check.
|
||||
// The pre-check API expects start/end as RFC3339 timestamps; we take the
|
||||
// Unix-second strings used elsewhere in the update flow and render them in
|
||||
// the event's own timezone when available, falling back to the local device
|
||||
// timezone so agents on different machines still produce a valid request.
|
||||
// start_timezone is an IANA name (e.g. "Asia/Shanghai") copied from the event
|
||||
// snapshot; it is omitted when unknown so the server can fall back to its own
|
||||
// default.
|
||||
func buildRoomCheckBody(calendarID, eventID string, plan *roomCheckPlan) map[string]interface{} {
|
||||
loc := time.Local
|
||||
if plan.StartTimezone != "" {
|
||||
if l, err := time.LoadLocation(plan.StartTimezone); err == nil {
|
||||
loc = l
|
||||
}
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"calendar_id": calendarID,
|
||||
"event_id": eventID,
|
||||
"start_time": formatRoomCheckTime(plan.StartTs, loc),
|
||||
"end_time": formatRoomCheckTime(plan.EndTs, loc),
|
||||
"room_ids": plan.RoomIDs,
|
||||
}
|
||||
if plan.StartTimezone != "" {
|
||||
body["start_timezone"] = plan.StartTimezone
|
||||
}
|
||||
if plan.Rrule != "" {
|
||||
body["event_rrule"] = plan.Rrule
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// formatRoomCheckTime renders a Unix-second string as RFC3339 in loc.
|
||||
// Non-numeric input is returned unchanged so anomalies stay visible instead
|
||||
// of being silently rewritten to the epoch.
|
||||
func formatRoomCheckTime(unixStr string, loc *time.Location) string {
|
||||
sec, err := strconv.ParseInt(strings.TrimSpace(unixStr), 10, 64)
|
||||
if err != nil {
|
||||
return unixStr
|
||||
}
|
||||
return time.Unix(sec, 0).In(loc).Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// callRoomAvailabilityCheck posts the availability request and returns per-room
|
||||
// results.
|
||||
func callRoomAvailabilityCheck(runtime *common.RuntimeContext, body map[string]interface{}) ([]roomAvailability, error) {
|
||||
data, err := runtime.CallAPITyped("POST", roomCheckPath, nil, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawList, _ := data["room_availabilitys"].([]interface{})
|
||||
out := make([]roomAvailability, 0, len(rawList))
|
||||
for _, raw := range rawList {
|
||||
m, ok := raw.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
item := roomAvailability{}
|
||||
if v, ok := m["room_id"].(string); ok {
|
||||
item.RoomID = v
|
||||
}
|
||||
if v, ok := m["room_name"].(string); ok {
|
||||
item.RoomName = v
|
||||
}
|
||||
if v, ok := m["status"].(string); ok {
|
||||
item.Status = v
|
||||
}
|
||||
if v, ok := m["unavailable_reason_type"].(string); ok {
|
||||
item.UnavailableReasonType = v
|
||||
}
|
||||
if strat, ok := m["room_strategy"].(map[string]interface{}); ok {
|
||||
item.Strategy = parseRoomStrategy(strat)
|
||||
}
|
||||
if req, ok := m["room_requisition"].(map[string]interface{}); ok {
|
||||
item.Requisition = parseRoomRequisition(req)
|
||||
}
|
||||
if info, ok := m["room_approval_info"].(map[string]interface{}); ok {
|
||||
item.ApprovalInfo = parseRoomApprovalInfo(info)
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parseRoomStrategy extracts the optional strategy fields from a raw API
|
||||
// map. Missing / non-string values are dropped so callers only see what the
|
||||
// server actually sent.
|
||||
func parseRoomStrategy(m map[string]interface{}) *roomStrategy {
|
||||
s := &roomStrategy{}
|
||||
if v, ok := m["single_max_duration"].(string); ok {
|
||||
s.SingleMaxDuration = v
|
||||
}
|
||||
if v, ok := m["max_advance_booking_time"].(string); ok {
|
||||
s.MaxAdvanceBookingTime = v
|
||||
}
|
||||
if v, ok := m["daily_start_time"].(string); ok {
|
||||
s.DailyStartTime = v
|
||||
}
|
||||
if v, ok := m["daily_end_time"].(string); ok {
|
||||
s.DailyEndTime = v
|
||||
}
|
||||
if v, ok := m["timezone"].(string); ok {
|
||||
s.Timezone = v
|
||||
}
|
||||
if v, ok := m["daily_advance_window_release_time"].(string); ok {
|
||||
s.DailyAdvanceWindowReleaseTime = v
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// parseRoomRequisition extracts the optional room_requisition block from a
|
||||
// raw API map. Missing / non-string values are dropped.
|
||||
func parseRoomRequisition(m map[string]interface{}) *roomRequisition {
|
||||
r := &roomRequisition{}
|
||||
if v, ok := m["start_time"].(string); ok {
|
||||
r.StartTime = v
|
||||
}
|
||||
if v, ok := m["end_time"].(string); ok {
|
||||
r.EndTime = v
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// parseRoomApprovalInfo extracts the optional room_approval_info block from a
|
||||
// raw API map. Missing / non-string values are dropped.
|
||||
func parseRoomApprovalInfo(m map[string]interface{}) *roomApprovalInfo {
|
||||
info := &roomApprovalInfo{}
|
||||
if v, ok := m["approval_mode"].(string); ok {
|
||||
info.ApprovalMode = v
|
||||
}
|
||||
if v, ok := m["approval_duration_threshold"].(string); ok {
|
||||
info.ApprovalDurationThreshold = v
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// approvalReasonHint composes the per-line phrase for a `need_approval`
|
||||
// status. The API returns `room_approval_info` with:
|
||||
//
|
||||
// - "all" → every reservation on this room must be approved.
|
||||
// - "over_duration" → only bookings longer than approval_duration_threshold
|
||||
// need approval. The current event duration (eventDurationSec) is compared
|
||||
// against the threshold so agents can see exactly why approval is being
|
||||
// asked for — and, when the current duration is below the threshold, the
|
||||
// message points at the "shorten it" recovery path.
|
||||
// - anything else → generic reminder so unknown modes still surface.
|
||||
//
|
||||
// This function only produces the per-room fragment. The shared recovery
|
||||
// clause (attendees-create, client fallback, shorten, pick another room) is
|
||||
// appended once by blockOnUnavailableRooms into `.WithHint(...)` so a message
|
||||
// with several approval-required rooms doesn't repeat the same recovery
|
||||
// paragraph on every line.
|
||||
func approvalReasonHint(info *roomApprovalInfo, eventDurationSec int64) string {
|
||||
mode := ""
|
||||
if info != nil {
|
||||
mode = strings.TrimSpace(info.ApprovalMode)
|
||||
}
|
||||
switch mode {
|
||||
case "all":
|
||||
return "this room requires approval for every reservation"
|
||||
case "over_duration":
|
||||
threshold, _ := strconv.ParseInt(strings.TrimSpace(info.ApprovalDurationThreshold), 10, 64)
|
||||
if threshold <= 0 {
|
||||
// Server said approval-by-duration but didn't give a threshold —
|
||||
// keep the mode label so agents don't lose the classification.
|
||||
return "this room requires approval when the booking exceeds a duration threshold"
|
||||
}
|
||||
thresholdPhrase := formatDurationSeconds(info.ApprovalDurationThreshold)
|
||||
if thresholdPhrase == "" {
|
||||
thresholdPhrase = fmt.Sprintf("%d seconds", threshold)
|
||||
}
|
||||
base := fmt.Sprintf("this room requires approval when the booking exceeds %s", thresholdPhrase)
|
||||
if eventDurationSec > 0 {
|
||||
currentPhrase := formatDurationSeconds(strconv.FormatInt(eventDurationSec, 10))
|
||||
if currentPhrase == "" {
|
||||
currentPhrase = fmt.Sprintf("%d seconds", eventDurationSec)
|
||||
}
|
||||
if eventDurationSec >= threshold {
|
||||
base += fmt.Sprintf(" (current duration is %s)", currentPhrase)
|
||||
} else {
|
||||
// Server flagged approval but our duration reads as below the
|
||||
// threshold — surface both so the agent can reconcile rather
|
||||
// than guess.
|
||||
base += fmt.Sprintf(" (current duration reads as %s; server still flagged approval)", currentPhrase)
|
||||
}
|
||||
}
|
||||
return base
|
||||
default:
|
||||
return "this room requires approval before it can be booked"
|
||||
}
|
||||
}
|
||||
|
||||
// roomLabel renders the room identifier for the block message. When the API
|
||||
// returns a human-readable name it becomes `<room_id>[<room_name>]`; a blank
|
||||
// name (or an entirely blank id, defensive) degrades to whichever is present
|
||||
// so agents can still address the room. The room_id is kept as the primary
|
||||
// identifier because callers act on it programmatically. Square brackets are
|
||||
// used (rather than parentheses) so a room name that itself contains
|
||||
// parentheses — e.g. "Room A (west wing)" — doesn't produce ambiguous nesting
|
||||
// like `omm_1(Room A (west wing))`.
|
||||
func roomLabel(id, name string) string {
|
||||
id = strings.TrimSpace(id)
|
||||
name = strings.TrimSpace(name)
|
||||
switch {
|
||||
case id != "" && name != "":
|
||||
return fmt.Sprintf("%s[%s]", id, name)
|
||||
case id != "":
|
||||
return id
|
||||
default:
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
// blockOnUnavailableRooms returns a typed validation error when any room in
|
||||
// results is unavailable or requires approval, or nil when everything is
|
||||
// bookable. The error text carries per-room reasons plus the retry command
|
||||
// hint from the PRD. When the API returns a room_strategy for a blocked room,
|
||||
// the relevant limit (max duration, latest bookable time, daily window, or
|
||||
// daily release time) is appended after the reason so agents can relay it to
|
||||
// the user without making a follow-up request. For a `during_requisition`
|
||||
// block, the disabled period (from room_requisition) is appended if available;
|
||||
// a "pick a different time or a different room" recovery clause is always
|
||||
// appended so the message reads coherently whether or not exact bounds are
|
||||
// known.
|
||||
//
|
||||
// `need_approval` results are treated as blocking (the CLI cannot submit an
|
||||
// approval on the user's behalf, so silently PATCHing would surprise the
|
||||
// user). The line uses room_approval_info + eventDurationSec to explain the
|
||||
// mode ("all" / "over_duration"), the threshold, and — for over_duration —
|
||||
// how the current booking compares. The shared "how do I actually recover
|
||||
// from approval" clause is folded into the hint once (not per line), so
|
||||
// several approval-required rooms don't repeat the same paragraph.
|
||||
func blockOnUnavailableRooms(results []roomAvailability, eventDurationSec int64) error {
|
||||
var blocked []roomAvailability
|
||||
for _, r := range results {
|
||||
if r.Status != "available" {
|
||||
blocked = append(blocked, r)
|
||||
}
|
||||
}
|
||||
if len(blocked) == 0 {
|
||||
return nil
|
||||
}
|
||||
var lines []string
|
||||
hasNeedApproval := false
|
||||
for _, r := range blocked {
|
||||
var reason string
|
||||
switch r.Status {
|
||||
case "need_approval":
|
||||
hasNeedApproval = true
|
||||
reason = approvalReasonHint(r.ApprovalInfo, eventDurationSec)
|
||||
default:
|
||||
reason = unavailableReasonHint(r.UnavailableReasonType)
|
||||
}
|
||||
line := fmt.Sprintf("%s: %s", roomLabel(r.RoomID, r.RoomName), reason)
|
||||
if detail := strategyDetail(r.UnavailableReasonType, r.Strategy); detail != "" {
|
||||
line += ", " + detail
|
||||
}
|
||||
if detail := requisitionDetail(r.UnavailableReasonType, r.Requisition); detail != "" {
|
||||
line += ", " + detail
|
||||
}
|
||||
if r.UnavailableReasonType == "during_requisition" {
|
||||
line += "; pick a different time or a different room"
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
msg := "meeting room booking will fail after this event change:\n " + strings.Join(lines, "\n ")
|
||||
hint := fmt.Sprintf("do NOT auto-retry: relay the room IDs and reasons above to the user and get explicit confirmation before re-running with --%s.",
|
||||
flagSkipRoomCheck)
|
||||
if hasNeedApproval {
|
||||
hint += " Rooms flagged need_approval: the CLI cannot submit approvals; DO NOT auto-run any recovery — ask the user first, then pick one: (a) newly added room → after the user confirms and provides `approval_reason`, run `lark-cli calendar event.attendees create --as user`; (b) time/rrule change re-triggers approval on an existing room → ask the user to update through the client; (c) shorten the meeting below the threshold or pick a different room."
|
||||
}
|
||||
return errs.NewValidationError(errs.SubtypeFailedPrecondition, "%s", msg).WithHint("%s", hint)
|
||||
}
|
||||
@@ -3368,3 +3368,952 @@ func TestGet_MissingEventField_TypedInternal(t *testing.T) {
|
||||
t.Errorf("subtype=%q, want invalid_response", ie.Subtype)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CalendarUpdate room-availability precheck tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// eventSnapshotStub builds a GET-event fixture with the given rooms + window
|
||||
// so room-check helpers can read a plausible snapshot.
|
||||
func eventSnapshotStub(calendarID, eventID, startTs, endTs string, roomIDs ...string) *httpmock.Stub {
|
||||
attendees := make([]interface{}, 0, len(roomIDs))
|
||||
for _, id := range roomIDs {
|
||||
attendees = append(attendees, map[string]interface{}{
|
||||
"type": "resource",
|
||||
"room_id": id,
|
||||
})
|
||||
}
|
||||
return &httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/calendar/v4/calendars/" + calendarID + "/events/" + eventID,
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"event": map[string]interface{}{
|
||||
"event_id": eventID,
|
||||
"summary": "Existing",
|
||||
"start_time": map[string]interface{}{"timestamp": startTs, "timezone": "Asia/Shanghai"},
|
||||
"end_time": map[string]interface{}{"timestamp": endTs, "timezone": "Asia/Shanghai"},
|
||||
"attendees": attendees,
|
||||
},
|
||||
},
|
||||
},
|
||||
Reusable: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_SkipFlag_BypassesAPI(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
// Register the PATCH stub but no room-check stub — the test asserts that no
|
||||
// unmatched request is made.
|
||||
patchStub := &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc1",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "evt_rc1"}},
|
||||
},
|
||||
}
|
||||
reg.Register(patchStub)
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc1",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--summary", "Skip",
|
||||
"--start", "2025-03-21T00:00:00+08:00",
|
||||
"--end", "2025-03-21T01:00:00+08:00",
|
||||
"--skip-room-check",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(patchStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected PATCH to be captured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_TitleOnly_SkipsCheck(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
// Only registered PATCH; title-only changes should never trigger room-check
|
||||
// and never fetch the event snapshot.
|
||||
patchStub := &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc2",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "evt_rc2"}},
|
||||
},
|
||||
}
|
||||
reg.Register(patchStub)
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc2",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--summary", "New title only",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(patchStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected PATCH to be captured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_NewRoomAvailable_Allows(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
// Snapshot has no existing rooms; we're adding omm_new.
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc3", "1742515200", "1742518800"))
|
||||
|
||||
checkStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{"room_id": "omm_new", "status": "available"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(checkStub)
|
||||
|
||||
addStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc3/attendees",
|
||||
Body: map[string]interface{}{"code": 0, "msg": "ok", "data": map[string]interface{}{}},
|
||||
}
|
||||
reg.Register(addStub)
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc3",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_new",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(checkStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected room-availability-check to be called")
|
||||
}
|
||||
body := decodeCalendarCapturedBody(t, checkStub)
|
||||
rooms, _ := body["room_ids"].([]interface{})
|
||||
if len(rooms) != 1 || rooms[0] != "omm_new" {
|
||||
t.Fatalf("room_ids should be [omm_new], got %#v", rooms)
|
||||
}
|
||||
if body["calendar_id"] != "cal_rc" || body["event_id"] != "evt_rc3" {
|
||||
t.Fatalf("room-check body missing ids: %#v", body)
|
||||
}
|
||||
if body["start_timezone"] != "Asia/Shanghai" {
|
||||
t.Fatalf("start_timezone should carry snapshot value, got %#v", body["start_timezone"])
|
||||
}
|
||||
if body["start_time"] != "2025-03-21T08:00:00+08:00" {
|
||||
t.Fatalf("start_time should be RFC3339 in event tz, got %#v", body["start_time"])
|
||||
}
|
||||
if body["end_time"] != "2025-03-21T09:00:00+08:00" {
|
||||
t.Fatalf("end_time should be RFC3339 in event tz, got %#v", body["end_time"])
|
||||
}
|
||||
if len(addStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected add-attendees POST to run")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_NewRoomUnavailable_Blocks(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc4", "1742515200", "1742518800"))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{
|
||||
"room_id": "omm_busy",
|
||||
"status": "unavailable",
|
||||
"unavailable_reason_type": "reserved_by_other_event",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc4",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_busy",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected block error when room is unavailable")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
|
||||
}
|
||||
if ve.Subtype != errs.SubtypeFailedPrecondition {
|
||||
t.Errorf("subtype=%q, want failed_precondition", ve.Subtype)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "omm_busy") {
|
||||
t.Errorf("message should list blocked room id, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, "--skip-room-check") {
|
||||
t.Errorf("hint should mention --skip-room-check, got: %q", ve.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_TimeChanged_ChecksExistingRoom(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
// Existing event already has omm_existing booked.
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc5", "1742515200", "1742518800", "omm_existing"))
|
||||
|
||||
checkStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{"room_id": "omm_existing", "status": "available"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(checkStub)
|
||||
|
||||
patchStub := &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc5",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "evt_rc5"}},
|
||||
},
|
||||
}
|
||||
reg.Register(patchStub)
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc5",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--start", "2025-03-21T02:00:00+08:00",
|
||||
"--end", "2025-03-21T03:00:00+08:00",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(checkStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected room-check to run for existing room on time change")
|
||||
}
|
||||
body := decodeCalendarCapturedBody(t, checkStub)
|
||||
rooms, _ := body["room_ids"].([]interface{})
|
||||
if len(rooms) != 1 || rooms[0] != "omm_existing" {
|
||||
t.Fatalf("room_ids should be [omm_existing], got %#v", rooms)
|
||||
}
|
||||
if len(patchStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected PATCH to run after check passes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_APIFailure_DegradesGracefully(t *testing.T) {
|
||||
f, _, stderr, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc6", "1742515200", "1742518800"))
|
||||
// Simulate room-check API failure (e.g., not yet rolled out) so the CLI
|
||||
// degrades gracefully instead of blocking the update.
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 190001,
|
||||
"msg": "permission denied",
|
||||
},
|
||||
})
|
||||
addStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc6/attendees",
|
||||
Body: map[string]interface{}{"code": 0, "msg": "ok", "data": map[string]interface{}{}},
|
||||
}
|
||||
reg.Register(addStub)
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc6",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_new",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(addStub.CapturedBody) == 0 {
|
||||
t.Fatalf("expected add-attendees POST to run despite check failure")
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "room availability check failed") {
|
||||
t.Errorf("stderr should warn about degraded check, got: %q", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_DryRun_IncludesPrecheckStep(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc7",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_dryrun",
|
||||
"--start", "2025-03-21T00:00:00+08:00",
|
||||
"--end", "2025-03-21T01:00:00+08:00",
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "room_availability_check") {
|
||||
t.Fatalf("dry-run should preview room_availability_check, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "Pre-check meeting room availability") {
|
||||
t.Fatalf("dry-run should describe pre-check step, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoomCheck_DryRun_SkipFlagOmitsStep(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc8",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_dryrun2",
|
||||
"--start", "2025-03-21T00:00:00+08:00",
|
||||
"--end", "2025-03-21T01:00:00+08:00",
|
||||
"--skip-room-check",
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if strings.Contains(out, "room_availability_check") {
|
||||
t.Fatalf("dry-run with --skip-room-check should not preview room_availability_check, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStrategyDetail_ByReason exercises the human-readable strategy suffix
|
||||
// appended to each blocked-room line. Timezone-anchored fields use a fixed
|
||||
// IANA name so the offset ("GMT+8") is deterministic across machines.
|
||||
func TestStrategyDetail_ByReason(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
reason string
|
||||
strategy *roomStrategy
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "over_max_duration renders as hours",
|
||||
reason: "over_max_duration",
|
||||
strategy: &roomStrategy{SingleMaxDuration: "10800"},
|
||||
want: "the max single-booking duration is 3 hours",
|
||||
},
|
||||
{
|
||||
name: "over_max_duration mixed hours and minutes",
|
||||
reason: "over_max_duration",
|
||||
strategy: &roomStrategy{SingleMaxDuration: "5400"},
|
||||
want: "the max single-booking duration is 1 hours 30 minutes",
|
||||
},
|
||||
{
|
||||
name: "beyond_advance_booking_window surfaces rfc3339 verbatim",
|
||||
reason: "beyond_advance_booking_window",
|
||||
strategy: &roomStrategy{MaxAdvanceBookingTime: "2026-07-13T18:00:00+08:00", Timezone: "Asia/Shanghai"},
|
||||
want: "the latest bookable end time is 2026-07-13T18:00:00+08:00",
|
||||
},
|
||||
{
|
||||
name: "not_in_usable_time renders day-seconds and zone",
|
||||
reason: "not_in_usable_time",
|
||||
strategy: &roomStrategy{DailyStartTime: "36000", DailyEndTime: "72000", Timezone: "Asia/Shanghai"},
|
||||
want: "the daily bookable window is 10:00 - 20:00 (GMT+8)",
|
||||
},
|
||||
{
|
||||
name: "before_daily_advance_window_release renders unlock time and zone",
|
||||
reason: "before_daily_advance_window_release",
|
||||
strategy: &roomStrategy{DailyAdvanceWindowReleaseTime: "28800", Timezone: "Asia/Shanghai"},
|
||||
want: "the next unlock happens today at 08:00 (GMT+8), which advances the window by one day",
|
||||
},
|
||||
{
|
||||
name: "past_time has no strategy suffix",
|
||||
reason: "past_time",
|
||||
strategy: &roomStrategy{SingleMaxDuration: "10800"},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "nil strategy returns empty",
|
||||
reason: "over_max_duration",
|
||||
strategy: nil,
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "invalid duration returns empty",
|
||||
reason: "over_max_duration",
|
||||
strategy: &roomStrategy{SingleMaxDuration: "not-a-number"},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "day-seconds out of range returns empty",
|
||||
reason: "not_in_usable_time",
|
||||
strategy: &roomStrategy{DailyStartTime: "-1", DailyEndTime: "999999", Timezone: "Asia/Shanghai"},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "unresolvable timezone falls back to iana name",
|
||||
reason: "before_daily_advance_window_release",
|
||||
strategy: &roomStrategy{DailyAdvanceWindowReleaseTime: "28800", Timezone: "Not/AReal_Zone"},
|
||||
want: "the next unlock happens today at 08:00 (Not/AReal_Zone), which advances the window by one day",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := strategyDetail(tt.reason, tt.strategy)
|
||||
if got != tt.want {
|
||||
t.Errorf("strategyDetail(%q) = %q, want %q", tt.reason, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdate_RoomCheck_StrategyDetailInMessage pins that when the API returns a
|
||||
// room_strategy alongside the unavailable_reason_type, blockOnUnavailableRooms
|
||||
// surfaces the specific limit inline so agents can relay it to the user
|
||||
// without an extra round trip.
|
||||
func TestUpdate_RoomCheck_StrategyDetailInMessage(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_strategy", "1742515200", "1742525200"))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{
|
||||
"room_id": "omm_toolong",
|
||||
"status": "unavailable",
|
||||
"unavailable_reason_type": "over_max_duration",
|
||||
"room_strategy": map[string]interface{}{
|
||||
"single_max_duration": "10800",
|
||||
"timezone": "Asia/Shanghai",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc_strategy",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_toolong",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected block error when strategy limit is hit")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "the max single-booking duration is 3 hours") {
|
||||
t.Errorf("message should surface the max-duration limit, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "omm_toolong") {
|
||||
t.Errorf("message should still list the room id, got: %q", ve.Message)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequisitionDetail_ByBounds pins the human-readable suffix rendered for a
|
||||
// `during_requisition` block. Every variant (both bounds, start only, end
|
||||
// only, none, nil requisition, non-matching reason) must degrade coherently.
|
||||
func TestRequisitionDetail_ByBounds(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
req *roomRequisition
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "both bounds surface as verbatim rfc3339 range",
|
||||
req: &roomRequisition{StartTime: "2026-07-13T09:00:00+08:00", EndTime: "2026-07-13T18:00:00+08:00"},
|
||||
want: "the disabled period is 2026-07-13T09:00:00+08:00 to 2026-07-13T18:00:00+08:00",
|
||||
},
|
||||
{
|
||||
name: "start only",
|
||||
req: &roomRequisition{StartTime: "2026-07-13T09:00:00+08:00"},
|
||||
want: "the disabled period starts at 2026-07-13T09:00:00+08:00",
|
||||
},
|
||||
{
|
||||
name: "end only",
|
||||
req: &roomRequisition{EndTime: "2026-07-13T18:00:00+08:00"},
|
||||
want: "the disabled period ends at 2026-07-13T18:00:00+08:00",
|
||||
},
|
||||
{
|
||||
name: "empty bounds return no detail",
|
||||
req: &roomRequisition{},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "nil requisition returns empty",
|
||||
req: nil,
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := requisitionDetail("during_requisition", tt.req)
|
||||
if got != tt.want {
|
||||
t.Errorf("requisitionDetail(during_requisition) = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Non-matching reason should always short-circuit even with a full payload.
|
||||
if got := requisitionDetail("reserved_by_other_event", &roomRequisition{StartTime: "x", EndTime: "y"}); got != "" {
|
||||
t.Errorf("requisitionDetail should ignore requisition for non-during_requisition reasons, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdate_RoomCheck_RequisitionDetailInMessage pins that when the API
|
||||
// returns room_requisition alongside a during_requisition block, the disabled
|
||||
// period is surfaced inline and the recovery clause is always present.
|
||||
func TestUpdate_RoomCheck_RequisitionDetailInMessage(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_req", "1742515200", "1742525200"))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{
|
||||
"room_id": "omm_req",
|
||||
"room_name": "Meeting Room A",
|
||||
"status": "unavailable",
|
||||
"unavailable_reason_type": "during_requisition",
|
||||
"room_requisition": map[string]interface{}{
|
||||
"start_time": "2026-07-13T09:00:00+08:00",
|
||||
"end_time": "2026-07-13T18:00:00+08:00",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc_req",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_req",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected block error for during_requisition")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "the disabled period is 2026-07-13T09:00:00+08:00 to 2026-07-13T18:00:00+08:00") {
|
||||
t.Errorf("message should surface the disabled period, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "pick a different time or a different room") {
|
||||
t.Errorf("message should always include recovery hint, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "omm_req[Meeting Room A]") {
|
||||
t.Errorf("message should render room id with human-readable name, got: %q", ve.Message)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoomLabel_ByFields pins the room identifier rendering used in the block
|
||||
// message. `<room_id>(<room_name>)` when both are present; degrades to
|
||||
// whichever is non-empty when the other is missing.
|
||||
func TestRoomLabel_ByFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
id string
|
||||
room string
|
||||
want string
|
||||
}{
|
||||
{name: "both present", id: "omm_1", room: "Meeting Room A", want: "omm_1[Meeting Room A]"},
|
||||
{name: "id only", id: "omm_2", room: "", want: "omm_2"},
|
||||
{name: "id only with whitespace name", id: "omm_3", room: " ", want: "omm_3"},
|
||||
{name: "name only degrades to name", id: "", room: "Room B", want: "Room B"},
|
||||
{name: "both blank returns empty", id: "", room: "", want: ""},
|
||||
{name: "name with parens does not create ambiguous nesting", id: "omm_4", room: "Room A (west wing)", want: "omm_4[Room A (west wing)]"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := roomLabel(tt.id, tt.room); got != tt.want {
|
||||
t.Errorf("roomLabel(%q, %q) = %q, want %q", tt.id, tt.room, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecurringMasterEventID_Shapes pins the recurringMasterEventID contract:
|
||||
// only `{uid}_{positive int}` collapses to `{uid}_0`; everything else opts out.
|
||||
func TestRecurringMasterEventID_Shapes(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
wantID string
|
||||
wantOK bool
|
||||
scenario string
|
||||
}{
|
||||
{in: "abc_1742515200", wantID: "abc_0", wantOK: true, scenario: "positive suffix collapses to master"},
|
||||
{in: "abc_1", wantID: "abc_0", wantOK: true, scenario: "positive one collapses to master"},
|
||||
{in: "abc_0", wantID: "", wantOK: false, scenario: "already master"},
|
||||
{in: "abc", wantID: "", wantOK: false, scenario: "no underscore"},
|
||||
{in: "_1742515200", wantID: "", wantOK: false, scenario: "empty uid"},
|
||||
{in: "abc_", wantID: "", wantOK: false, scenario: "empty suffix"},
|
||||
{in: "abc_-1", wantID: "", wantOK: false, scenario: "negative suffix"},
|
||||
{in: "abc_xyz", wantID: "", wantOK: false, scenario: "non-numeric suffix"},
|
||||
{in: "abc_def_1742515200", wantID: "abc_def_0", wantOK: true, scenario: "uid may contain underscore"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.scenario, func(t *testing.T) {
|
||||
gotID, gotOK := recurringMasterEventID(tt.in)
|
||||
if gotID != tt.wantID || gotOK != tt.wantOK {
|
||||
t.Errorf("recurringMasterEventID(%q) = (%q, %v), want (%q, %v)", tt.in, gotID, gotOK, tt.wantID, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdate_RoomCheck_EventNotFound_FallsBackToMaster pins the 193001
|
||||
// fallback: when the event_id is `{uid}_{original_time}` and the server
|
||||
// answers "event not found", the snapshot GET retries against `{uid}_0`
|
||||
// (the recurring master), so the room-check pipeline can still proceed.
|
||||
func TestUpdate_RoomCheck_EventNotFound_FallsBackToMaster(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
// First GET on the instance event: 193001.
|
||||
instanceStub := &httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/uid_master_1742515200",
|
||||
Body: map[string]interface{}{
|
||||
"code": 193001,
|
||||
"msg": "event not found",
|
||||
},
|
||||
}
|
||||
reg.Register(instanceStub)
|
||||
|
||||
// Fallback GET on the master event: 200 with an existing room attendee, so
|
||||
// the pre-check has something to reason about.
|
||||
masterStub := &httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/uid_master_0",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"event": map[string]interface{}{
|
||||
"event_id": "uid_master_0",
|
||||
"summary": "Weekly sync",
|
||||
"start_time": map[string]interface{}{"timestamp": "1742515200", "timezone": "Asia/Shanghai"},
|
||||
"end_time": map[string]interface{}{"timestamp": "1742518800", "timezone": "Asia/Shanghai"},
|
||||
"attendees": []interface{}{map[string]interface{}{"type": "resource", "room_id": "omm_from_master"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(masterStub)
|
||||
|
||||
// Time change → precheck runs against existing room from the master snapshot.
|
||||
precheckStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{
|
||||
"room_id": "omm_from_master",
|
||||
"status": "available",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(precheckStub)
|
||||
|
||||
// PATCH succeeds.
|
||||
patchStub := &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/uid_master_1742515200",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "uid_master_1742515200"}},
|
||||
},
|
||||
}
|
||||
reg.Register(patchStub)
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "uid_master_1742515200",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--start", "2025-03-21T08:00:00+08:00",
|
||||
"--end", "2025-03-21T09:00:00+08:00",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("expected update to succeed after master fallback, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApprovalReasonHint_ByMode pins the copy for each supported approval
|
||||
// mode, including the over_duration current-vs-threshold branches. The exact
|
||||
// phrase matters because agents parse it to decide next steps (relay to user,
|
||||
// shorten the meeting, pick another room).
|
||||
func TestApprovalReasonHint_ByMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
info *roomApprovalInfo
|
||||
duration int64
|
||||
mustContain []string
|
||||
mustNotContain []string
|
||||
}{
|
||||
{
|
||||
name: "all mode always needs approval",
|
||||
info: &roomApprovalInfo{ApprovalMode: "all"},
|
||||
duration: 3600,
|
||||
mustContain: []string{
|
||||
"requires approval for every reservation",
|
||||
},
|
||||
mustNotContain: []string{
|
||||
"the CLI cannot submit approvals",
|
||||
"lark-cli calendar event.attendees create",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "over_duration with current above threshold cites both",
|
||||
info: &roomApprovalInfo{ApprovalMode: "over_duration", ApprovalDurationThreshold: "3600"},
|
||||
duration: 7200,
|
||||
mustContain: []string{
|
||||
"exceeds 1 hours",
|
||||
"current duration is 2 hours",
|
||||
},
|
||||
mustNotContain: []string{
|
||||
"lark-cli calendar event.attendees create",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "over_duration with current exactly at threshold treated as over",
|
||||
info: &roomApprovalInfo{ApprovalMode: "over_duration", ApprovalDurationThreshold: "3600"},
|
||||
duration: 3600,
|
||||
mustContain: []string{
|
||||
"exceeds 1 hours",
|
||||
"current duration is 1 hours",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "over_duration with current below threshold surfaces reconciliation",
|
||||
info: &roomApprovalInfo{ApprovalMode: "over_duration", ApprovalDurationThreshold: "3600"},
|
||||
duration: 1800,
|
||||
mustContain: []string{
|
||||
"exceeds 1 hours",
|
||||
"current duration reads as 30 minutes",
|
||||
"server still flagged approval",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "over_duration without threshold keeps mode label",
|
||||
info: &roomApprovalInfo{ApprovalMode: "over_duration"},
|
||||
duration: 3600,
|
||||
mustContain: []string{
|
||||
"exceeds a duration threshold",
|
||||
},
|
||||
mustNotContain: []string{
|
||||
"the CLI cannot submit approvals",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unknown mode falls back to generic reminder",
|
||||
info: &roomApprovalInfo{ApprovalMode: "future_mode"},
|
||||
duration: 3600,
|
||||
mustContain: []string{
|
||||
"requires approval before it can be booked",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "nil approval info still yields a reminder",
|
||||
info: nil,
|
||||
duration: 3600,
|
||||
mustContain: []string{
|
||||
"requires approval before it can be booked",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := approvalReasonHint(tt.info, tt.duration)
|
||||
for _, needle := range tt.mustContain {
|
||||
if !strings.Contains(got, needle) {
|
||||
t.Errorf("approvalReasonHint(%+v, %d) missing %q, got: %q", tt.info, tt.duration, needle, got)
|
||||
}
|
||||
}
|
||||
for _, needle := range tt.mustNotContain {
|
||||
if strings.Contains(got, needle) {
|
||||
t.Errorf("approvalReasonHint(%+v, %d) should not contain %q (that clause belongs in the hint, not the per-line reason), got: %q", tt.info, tt.duration, needle, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdate_RoomCheck_NeedApproval_Blocks pins that a status=="need_approval"
|
||||
// result blocks the update with a friendly, structured message: mode,
|
||||
// threshold, current duration comparison, and the "CLI can't approve" clause.
|
||||
// The block error also carries the same retry hint as the unavailable branch
|
||||
// so agents don't auto-retry with --skip-room-check.
|
||||
func TestUpdate_RoomCheck_NeedApproval_Blocks(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
// Snapshot window: 1742515200 -> 1742522400 (2h). Threshold is 1h, so the
|
||||
// current duration is over threshold.
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_approval", "1742515200", "1742522400"))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{
|
||||
"room_id": "omm_approval",
|
||||
"room_name": "Executive Room",
|
||||
"status": "need_approval",
|
||||
"room_approval_info": map[string]interface{}{
|
||||
"approval_mode": "over_duration",
|
||||
"approval_duration_threshold": "3600",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc_approval",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_approval",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected need_approval to block the update")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "omm_approval[Executive Room]") {
|
||||
t.Errorf("message should render room label, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "requires approval when the booking exceeds 1 hours") {
|
||||
t.Errorf("message should carry approval threshold, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "current duration is 2 hours") {
|
||||
t.Errorf("message should carry current-vs-threshold comparison, got: %q", ve.Message)
|
||||
}
|
||||
if strings.Contains(ve.Message, "the CLI cannot submit approvals inline") {
|
||||
t.Errorf("recovery clause should live in the hint (not repeated per line in the message), got message: %q", ve.Message)
|
||||
}
|
||||
if strings.Contains(ve.Message, "lark-cli calendar event.attendees create --as user") {
|
||||
t.Errorf("attendees-create recovery clause should live in the hint (not per line), got message: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, "the CLI cannot submit approvals") {
|
||||
t.Errorf("hint should carry the approval recovery clause once, got: %q", ve.Hint)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, "DO NOT auto-run") {
|
||||
t.Errorf("hint should forbid auto-running any approval recovery path without user confirmation, got: %q", ve.Hint)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, "ask the user first") {
|
||||
t.Errorf("hint should require asking the user before picking a recovery path, got: %q", ve.Hint)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, "lark-cli calendar event.attendees create --as user") {
|
||||
t.Errorf("hint should point at the attendees-create recovery path, got: %q", ve.Hint)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, "update through the client") {
|
||||
t.Errorf("hint should mention the client-side fallback for re-approval on existing rooms, got: %q", ve.Hint)
|
||||
}
|
||||
if !strings.Contains(ve.Hint, flagSkipRoomCheck) {
|
||||
t.Errorf("hint should still mention --%s, got: %q", flagSkipRoomCheck, ve.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdate_RoomCheck_RequisitionMissingBoundsStillCoherent pins that when
|
||||
// the API returns during_requisition without room_requisition, the recovery
|
||||
// hint keeps the line coherent on its own.
|
||||
func TestUpdate_RoomCheck_RequisitionMissingBoundsStillCoherent(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_req2", "1742515200", "1742525200"))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"room_availabilitys": []interface{}{
|
||||
map[string]interface{}{
|
||||
"room_id": "omm_req_nobounds",
|
||||
"status": "unavailable",
|
||||
"unavailable_reason_type": "during_requisition",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRun(t, CalendarUpdate, []string{
|
||||
"+update",
|
||||
"--event-id", "evt_rc_req2",
|
||||
"--calendar-id", "cal_rc",
|
||||
"--add-attendee-ids", "omm_req_nobounds",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected block error for during_requisition without bounds")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
|
||||
}
|
||||
if strings.Contains(ve.Message, "the disabled period") {
|
||||
t.Errorf("message should not fabricate a disabled period, got: %q", ve.Message)
|
||||
}
|
||||
if !strings.Contains(ve.Message, "pick a different time or a different room") {
|
||||
t.Errorf("message should always include recovery hint, got: %q", ve.Message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ var CalendarUpdate = common.Shortcut{
|
||||
{Name: "add-attendee-ids", Desc: "attendee IDs to add, comma-separated (supports user ou_, chat oc_, room omm_)"},
|
||||
{Name: "remove-attendee-ids", Desc: "attendee IDs to remove, comma-separated (supports user ou_, chat oc_, room omm_)"},
|
||||
{Name: "notify", Type: "bool", Default: "true", Desc: "send update notification to attendees"},
|
||||
{Name: flagSkipRoomCheck, Type: "bool", Default: "false", Hidden: true, Desc: "skip meeting-room availability precheck (default checks rooms whenever a new room is added or the time/rrule of a room-attached event changes)"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateCalendarUpdate(runtime)
|
||||
@@ -219,6 +220,50 @@ func calendarUpdateAttendeesPath(calendarID, eventID string) string {
|
||||
return calendarUpdateEventPath(calendarID, eventID) + "/attendees"
|
||||
}
|
||||
|
||||
// runRoomAvailabilityPrecheck checks any room affected by this update (new
|
||||
// room attendees, or existing rooms when the time/rrule shifts) against the
|
||||
// server before the PATCH is issued. It returns nil to allow the update to
|
||||
// proceed and a typed error to block it. Called only when --skip-room-check
|
||||
// is false.
|
||||
func runRoomAvailabilityPrecheck(ctx context.Context, runtime *common.RuntimeContext, calendarID, eventID string, body map[string]interface{}) error {
|
||||
timeChanged := runtime.Cmd.Flags().Changed("start") && runtime.Cmd.Flags().Changed("end")
|
||||
rruleChanged := runtime.Cmd.Flags().Changed("rrule")
|
||||
|
||||
var newStartTs, newEndTs string
|
||||
if timeChanged {
|
||||
if m, _ := body["start_time"].(map[string]string); m != nil {
|
||||
newStartTs = m["timestamp"]
|
||||
}
|
||||
if m, _ := body["end_time"].(map[string]string); m != nil {
|
||||
newEndTs = m["timestamp"]
|
||||
}
|
||||
}
|
||||
|
||||
plan, err := resolveRoomCheckPlan(ctx, runtime, calendarID, eventID, newStartTs, newEndTs, timeChanged, rruleChanged)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
results, err := callRoomAvailabilityCheck(runtime, buildRoomCheckBody(calendarID, eventID, plan))
|
||||
if err != nil {
|
||||
// Degrade gracefully: warn on stderr and let the update proceed so the
|
||||
// pre-check API doesn't gate legitimate updates when it hiccups. For
|
||||
// 190014 (invalid_parameters) surface the server-supplied field-level
|
||||
// detail so agents can see why the precheck refused.
|
||||
msg := unwrapCalendarAPIError(err)
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
fmt.Fprintf(runtime.IO().ErrOut,
|
||||
"[calendar +update] warning: room availability check failed (%s); proceeding with update — pass --%s to silence\n",
|
||||
msg, flagSkipRoomCheck)
|
||||
return nil
|
||||
}
|
||||
return blockOnUnavailableRooms(results, roomCheckPlanDurationSec(plan))
|
||||
}
|
||||
|
||||
func dryRunCalendarUpdate(runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
calendarID, eventID := calendarUpdateIDs(runtime)
|
||||
displayCalendarID := calendarID
|
||||
@@ -246,6 +291,33 @@ func dryRunCalendarUpdate(runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
d.Desc("multi-step update: event fields, attendee removal, and attendee addition run in order when requested")
|
||||
}
|
||||
steps := 0
|
||||
|
||||
if !runtime.Bool(flagSkipRoomCheck) {
|
||||
newRooms := collectAttendeeRoomIDs(runtime.Str("add-attendee-ids"))
|
||||
timeChanged := runtime.Cmd.Flags().Changed("start") && runtime.Cmd.Flags().Changed("end")
|
||||
rruleChanged := runtime.Cmd.Flags().Changed("rrule")
|
||||
if len(newRooms) > 0 || timeChanged || rruleChanged {
|
||||
steps++
|
||||
desc := fmt.Sprintf("[%d] Pre-check meeting room availability (default; pass --%s to skip)", steps, flagSkipRoomCheck)
|
||||
previewBody := map[string]interface{}{
|
||||
"calendar_id": displayCalendarID,
|
||||
"event_id": eventID,
|
||||
"room_ids": newRooms,
|
||||
"start_timezone": "<inherited from event>",
|
||||
}
|
||||
if start, _ := body["start_time"].(map[string]string); start != nil {
|
||||
previewBody["start_time"] = formatRoomCheckTime(start["timestamp"], time.Local)
|
||||
}
|
||||
if end, _ := body["end_time"].(map[string]string); end != nil {
|
||||
previewBody["end_time"] = formatRoomCheckTime(end["timestamp"], time.Local)
|
||||
}
|
||||
if rrule, _ := body["recurrence"].(string); rrule != "" {
|
||||
previewBody["event_rrule"] = rrule
|
||||
}
|
||||
d.POST(roomCheckPath).Desc(desc).Body(previewBody)
|
||||
}
|
||||
}
|
||||
|
||||
if hasEventFields {
|
||||
steps++
|
||||
d.PATCH("/open-apis/calendar/v4/calendars/:calendar_id/events/:event_id").
|
||||
@@ -278,7 +350,7 @@ func dryRunCalendarUpdate(runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return d
|
||||
}
|
||||
|
||||
func executeCalendarUpdate(_ context.Context, runtime *common.RuntimeContext) error {
|
||||
func executeCalendarUpdate(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
calendarID, eventID := calendarUpdateIDs(runtime)
|
||||
if eventID == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "specify --event-id").WithParam("--event-id")
|
||||
@@ -289,6 +361,12 @@ func executeCalendarUpdate(_ context.Context, runtime *common.RuntimeContext) er
|
||||
return err
|
||||
}
|
||||
|
||||
if !runtime.Bool(flagSkipRoomCheck) {
|
||||
if err := runRoomAvailabilityPrecheck(ctx, runtime, calendarID, eventID, body); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
completed := []string{}
|
||||
event := map[string]interface{}{}
|
||||
if hasEventFields {
|
||||
|
||||
@@ -665,16 +665,59 @@ func (ctx *RuntimeContext) ValidatePath(path string) error {
|
||||
|
||||
// ── Output helpers ──
|
||||
|
||||
func (ctx *RuntimeContext) newEmitter() *output.Emitter {
|
||||
streams := ctx.IO()
|
||||
return output.NewEmitter(output.EmitterConfig{
|
||||
Out: streams.Out,
|
||||
ErrOut: streams.ErrOut,
|
||||
CommandPath: ctx.Cmd.CommandPath(),
|
||||
Identity: string(ctx.As()),
|
||||
ColorEnabled: streams.OutIsTerminal,
|
||||
NoticeProvider: output.GetNotice,
|
||||
})
|
||||
}
|
||||
|
||||
func (ctx *RuntimeContext) handleEmitterError(err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
var cs *errs.ContentSafetyError
|
||||
if ctx.JqExpr != "" && !errors.As(err, &cs) {
|
||||
fmt.Fprintf(ctx.IO().ErrOut, "error: %v\n", err)
|
||||
}
|
||||
ctx.outputErrOnce.Do(func() { ctx.outputErr = err })
|
||||
}
|
||||
|
||||
func wrapLegacyPrettyRenderer(prettyFn func(w io.Writer)) output.PrettyRenderer {
|
||||
if prettyFn == nil {
|
||||
return nil
|
||||
}
|
||||
return func(w io.Writer, _ bool) error {
|
||||
prettyFn(w)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Out prints a success JSON envelope to stdout.
|
||||
func (ctx *RuntimeContext) Out(data interface{}, meta *output.Meta) {
|
||||
ctx.emit(data, meta, false, true)
|
||||
ctx.handleEmitterError(ctx.newEmitter().Success(data, output.EmitOptions{
|
||||
Format: "",
|
||||
Raw: false,
|
||||
JQ: ctx.JqExpr,
|
||||
Meta: meta,
|
||||
}))
|
||||
}
|
||||
|
||||
// OutRaw prints a success JSON envelope to stdout with HTML escaping disabled.
|
||||
// Use this instead of Out when the data contains XML/HTML content (e.g. document bodies)
|
||||
// that should be preserved as-is in JSON output.
|
||||
func (ctx *RuntimeContext) OutRaw(data interface{}, meta *output.Meta) {
|
||||
ctx.emit(data, meta, true, true)
|
||||
ctx.handleEmitterError(ctx.newEmitter().Success(data, output.EmitOptions{
|
||||
Format: "",
|
||||
Raw: true,
|
||||
JQ: ctx.JqExpr,
|
||||
Meta: meta,
|
||||
}))
|
||||
}
|
||||
|
||||
// OutPartialFailure writes an ok:false multi-status result envelope to stdout
|
||||
@@ -688,112 +731,42 @@ func (ctx *RuntimeContext) OutRaw(data interface{}, meta *output.Meta) {
|
||||
// ok:true, and the exit signal is distinct from ErrBare (the
|
||||
// stdout-carries-the-answer silent-exit signal).
|
||||
func (ctx *RuntimeContext) OutPartialFailure(data interface{}, meta *output.Meta) error {
|
||||
ctx.emit(data, meta, false, false)
|
||||
ctx.handleEmitterError(ctx.newEmitter().PartialFailure(data, output.EmitOptions{
|
||||
Format: "",
|
||||
Raw: false,
|
||||
JQ: ctx.JqExpr,
|
||||
Meta: meta,
|
||||
}))
|
||||
if ctx.outputErr != nil {
|
||||
return ctx.outputErr
|
||||
}
|
||||
return output.PartialFailure(output.ExitAPI)
|
||||
}
|
||||
|
||||
// emit is the shared stdout envelope emitter; ok sets the envelope's ok field
|
||||
// (true for success, false for a partial-failure result). raw=true disables JSON
|
||||
// HTML escaping so XML/HTML payloads (e.g. DocxXML bodies) are preserved
|
||||
// verbatim; otherwise behavior
|
||||
// is identical — content-safety scanning and race-safe first-error capture via
|
||||
// outputErrOnce apply in both modes.
|
||||
func (ctx *RuntimeContext) emit(data interface{}, meta *output.Meta, raw, ok bool) {
|
||||
scanResult := output.ScanForSafety(ctx.Cmd.CommandPath(), data, ctx.IO().ErrOut)
|
||||
if scanResult.Blocked {
|
||||
ctx.outputErrOnce.Do(func() { ctx.outputErr = scanResult.BlockErr })
|
||||
return
|
||||
}
|
||||
|
||||
env := output.Envelope{OK: ok, Identity: string(ctx.As()), Data: data, Meta: meta, Notice: output.GetNotice()}
|
||||
if scanResult.Alert != nil {
|
||||
env.ContentSafetyAlert = scanResult.Alert
|
||||
}
|
||||
|
||||
if ctx.JqExpr != "" {
|
||||
filter := output.JqFilter
|
||||
if raw {
|
||||
filter = output.JqFilterRaw
|
||||
}
|
||||
if err := filter(ctx.IO().Out, env, ctx.JqExpr); err != nil {
|
||||
fmt.Fprintf(ctx.IO().ErrOut, "error: %v\n", err)
|
||||
ctx.outputErrOnce.Do(func() { ctx.outputErr = err })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if raw {
|
||||
enc := json.NewEncoder(ctx.IO().Out)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(env)
|
||||
return
|
||||
}
|
||||
b, _ := json.MarshalIndent(env, "", " ")
|
||||
fmt.Fprintln(ctx.IO().Out, string(b))
|
||||
}
|
||||
|
||||
// OutFormat prints output based on --format flag.
|
||||
// "json" (default) outputs JSON envelope; "pretty" calls prettyFn; others delegate to FormatValue.
|
||||
// When JqExpr is set, routes through Out() regardless of format.
|
||||
// For json/"" and jq paths, Out() handles content safety scanning.
|
||||
// For pretty/table/csv/ndjson, scanning is done here and the alert is written to stderr.
|
||||
// When JqExpr is set, envelope filtering takes precedence over format.
|
||||
// The Emitter handles content safety scanning for every format.
|
||||
func (ctx *RuntimeContext) OutFormat(data interface{}, meta *output.Meta, prettyFn func(w io.Writer)) {
|
||||
ctx.outFormat(data, meta, prettyFn, false)
|
||||
ctx.handleEmitterError(ctx.newEmitter().Success(data, output.EmitOptions{
|
||||
Format: ctx.Format,
|
||||
Raw: false,
|
||||
JQ: ctx.JqExpr,
|
||||
Meta: meta,
|
||||
Pretty: wrapLegacyPrettyRenderer(prettyFn),
|
||||
}))
|
||||
}
|
||||
|
||||
// OutFormatRaw is like OutFormat but with HTML escaping disabled in JSON output.
|
||||
// Use this when the data contains XML/HTML content that should be preserved as-is.
|
||||
func (ctx *RuntimeContext) OutFormatRaw(data interface{}, meta *output.Meta, prettyFn func(w io.Writer)) {
|
||||
ctx.outFormat(data, meta, prettyFn, true)
|
||||
}
|
||||
|
||||
func (ctx *RuntimeContext) outFormat(data interface{}, meta *output.Meta, prettyFn func(w io.Writer), raw bool) {
|
||||
outFn := ctx.Out
|
||||
if raw {
|
||||
outFn = ctx.OutRaw
|
||||
}
|
||||
if ctx.JqExpr != "" {
|
||||
outFn(data, meta)
|
||||
return
|
||||
}
|
||||
switch ctx.Format {
|
||||
case "pretty":
|
||||
scanResult := output.ScanForSafety(ctx.Cmd.CommandPath(), data, ctx.IO().ErrOut)
|
||||
if scanResult.Blocked {
|
||||
ctx.outputErrOnce.Do(func() { ctx.outputErr = scanResult.BlockErr })
|
||||
return
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
output.WriteAlertWarning(ctx.IO().ErrOut, scanResult.Alert)
|
||||
}
|
||||
if prettyFn != nil {
|
||||
prettyFn(ctx.IO().Out)
|
||||
} else {
|
||||
outFn(data, meta)
|
||||
}
|
||||
case "json", "":
|
||||
outFn(data, meta)
|
||||
default:
|
||||
// table, csv, ndjson — pass data directly; FormatValue handles both
|
||||
// plain arrays and maps with array fields (e.g. {"members":[…]})
|
||||
scanResult := output.ScanForSafety(ctx.Cmd.CommandPath(), data, ctx.IO().ErrOut)
|
||||
if scanResult.Blocked {
|
||||
ctx.outputErrOnce.Do(func() { ctx.outputErr = scanResult.BlockErr })
|
||||
return
|
||||
}
|
||||
if scanResult.Alert != nil {
|
||||
output.WriteAlertWarning(ctx.IO().ErrOut, scanResult.Alert)
|
||||
}
|
||||
format, formatOK := output.ParseFormat(ctx.Format)
|
||||
if !formatOK {
|
||||
fmt.Fprintf(ctx.IO().ErrOut, "warning: unknown format %q, falling back to json\n", ctx.Format)
|
||||
}
|
||||
output.FormatValue(ctx.IO().Out, data, format)
|
||||
}
|
||||
ctx.handleEmitterError(ctx.newEmitter().Success(data, output.EmitOptions{
|
||||
Format: ctx.Format,
|
||||
Raw: true,
|
||||
JQ: ctx.JqExpr,
|
||||
Meta: meta,
|
||||
Pretty: wrapLegacyPrettyRenderer(prettyFn),
|
||||
}))
|
||||
}
|
||||
|
||||
// ── Scope pre-check ──
|
||||
|
||||
@@ -7,10 +7,12 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
extcs "github.com/larksuite/cli/extension/contentsafety"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
@@ -71,7 +73,7 @@ func TestOut_ContentSafetyBlock(t *testing.T) {
|
||||
extcs.Register(&csTestProvider{alert: alert})
|
||||
defer extcs.Register(nil)
|
||||
|
||||
rctx, stdout, _ := newCSTestContext(t)
|
||||
rctx, stdout, stderr := newCSTestContext(t)
|
||||
rctx.Out(map[string]any{"msg": "hello"}, nil)
|
||||
|
||||
if stdout.Len() > 0 {
|
||||
@@ -80,6 +82,16 @@ func TestOut_ContentSafetyBlock(t *testing.T) {
|
||||
if rctx.outputErr == nil {
|
||||
t.Error("block mode should set outputErr")
|
||||
}
|
||||
if stderr.Len() != 0 {
|
||||
t.Fatalf("block mode stderr = %q, want empty", stderr.String())
|
||||
}
|
||||
var safetyErr *errs.ContentSafetyError
|
||||
if !errors.As(rctx.outputErr, &safetyErr) {
|
||||
t.Fatalf("block mode output error = %T, want *errs.ContentSafetyError", rctx.outputErr)
|
||||
}
|
||||
if got := output.ExitCodeOf(rctx.outputErr); got != output.ExitContentSafety {
|
||||
t.Fatalf("block mode exit code = %d, want %d", got, output.ExitContentSafety)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOut_ContentSafetyOff(t *testing.T) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
lark "github.com/larksuite/oapi-sdk-go/v3"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
@@ -102,6 +104,72 @@ func TestRuntimeContext_Out_WithJq_InvalidExpr_WritesStderr(t *testing.T) {
|
||||
if !strings.Contains(stderr.String(), "error") {
|
||||
t.Errorf("expected error on stderr for runtime jq error, got: %s", stderr.String())
|
||||
}
|
||||
problem, ok := errs.ProblemOf(rctx.outputErr)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("output error problem = %#v, %v; want validation/invalid_argument", problem, ok)
|
||||
}
|
||||
if got := output.ExitCodeOf(rctx.outputErr); got != output.ExitValidation {
|
||||
t.Fatalf("output error exit code = %d, want %d", got, output.ExitValidation)
|
||||
}
|
||||
}
|
||||
|
||||
type failingRuntimeOutputWriter struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (w failingRuntimeOutputWriter) Write([]byte) (int, error) {
|
||||
return 0, w.err
|
||||
}
|
||||
|
||||
func TestRuntimeContext_OutRaw_PropagatesWriteError(t *testing.T) {
|
||||
rctx, _, stderr := newJqTestContext("", "")
|
||||
sentinel := errors.New("write failed")
|
||||
rctx.Factory.IOStreams.Out = failingRuntimeOutputWriter{err: sentinel}
|
||||
|
||||
rctx.OutRaw(map[string]interface{}{"id": "1"}, nil)
|
||||
|
||||
if !errors.Is(rctx.outputErr, sentinel) {
|
||||
t.Fatalf("OutRaw() output error = %v, want preserved writer cause", rctx.outputErr)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(rctx.outputErr)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("OutRaw() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
if got := output.ExitCodeOf(rctx.outputErr); got != output.ExitInternal {
|
||||
t.Fatalf("OutRaw() exit code = %d, want %d", got, output.ExitInternal)
|
||||
}
|
||||
if stderr.Len() != 0 {
|
||||
t.Fatalf("OutRaw() stderr = %q, want empty", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunShortcut_OutRawWriteErrorPropagates(t *testing.T) {
|
||||
sentinel := errors.New("write failed")
|
||||
f := newTestFactory()
|
||||
f.IOStreams.Out = failingRuntimeOutputWriter{err: sentinel}
|
||||
s := &Shortcut{
|
||||
Service: "test",
|
||||
Command: "test-shortcut",
|
||||
AuthTypes: []string{"bot"},
|
||||
Execute: func(_ context.Context, rctx *RuntimeContext) error {
|
||||
rctx.OutRaw(map[string]interface{}{"id": "1"}, nil)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd := newTestShortcutCmd(s, f)
|
||||
cmd.Flags().Set("as", "bot")
|
||||
|
||||
err := runShortcut(cmd, f, s, true)
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("runShortcut() error = %v, want preserved writer cause", err)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryInternal {
|
||||
t.Fatalf("runShortcut() problem = %#v, %v; want internal typed error", problem, ok)
|
||||
}
|
||||
if got := output.ExitCodeOf(err); got != output.ExitInternal {
|
||||
t.Fatalf("runShortcut() exit code = %d, want %d", got, output.ExitInternal)
|
||||
}
|
||||
}
|
||||
|
||||
type testResolvedFileIO struct{}
|
||||
|
||||
@@ -27,8 +27,8 @@ var ImFlagList = common.Shortcut{
|
||||
Flags: []common.Flag{
|
||||
{Name: "page-size", Type: "int", Default: "50", Desc: "page size (1-50)"},
|
||||
{Name: "page-token", Desc: "pagination token for next page"},
|
||||
{Name: "page-all", Type: "bool", Desc: "automatically paginate through all pages"},
|
||||
{Name: "page-limit", Type: "int", Default: "20", Desc: "max pages when auto-pagination is enabled (default 20, max 1000)"},
|
||||
{Name: "page-all", Type: "bool", Desc: "automatically paginate, capped by --page-limit"},
|
||||
{Name: "page-limit", Type: "int", Default: "20", Desc: "max pages with --page-all (default 20; configurable range 1-1000)"},
|
||||
{Name: "enrich-feed-thread", Type: "bool", Default: "true", Desc: "fetch message content for feed-type thread entries (default true; may call messages/mget and require im:message.group_msg:get_as_user/im:message.p2p_msg:get_as_user; use --enrich-feed-thread=false to avoid extra scopes)"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
@@ -278,6 +278,10 @@ func executeListAllPages(rt *common.RuntimeContext) error {
|
||||
fmt.Fprintf(rt.IO().ErrOut, "warning: page_token did not change, stopping pagination to avoid infinite loop\n")
|
||||
break
|
||||
}
|
||||
if page+1 >= maxPages {
|
||||
fmt.Fprintf(rt.IO().ErrOut, "[pagination] reached page limit (%d) while has_more=true; result is incomplete. Increase --page-limit up to 1000 or resume with the page_token returned in stdout.\n", maxPages)
|
||||
break
|
||||
}
|
||||
prevPageToken = lastPageToken
|
||||
}
|
||||
|
||||
|
||||
@@ -1536,6 +1536,9 @@ func TestExecuteListAllPages(t *testing.T) {
|
||||
if callCount != 2 {
|
||||
t.Fatalf("expected 2 API calls, got %d", callCount)
|
||||
}
|
||||
if stderr := rt.IO().ErrOut.(*bytes.Buffer).String(); strings.Contains(stderr, "reached page limit") {
|
||||
t.Fatalf("natural pagination completion must not warn about a page limit, got %q", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteListAllPages_EnrichFeedThread(t *testing.T) {
|
||||
@@ -1625,6 +1628,73 @@ func TestExecuteListAllPages_PageLimit(t *testing.T) {
|
||||
if callCount != 3 {
|
||||
t.Fatalf("expected 3 API calls (page limit), got %d", callCount)
|
||||
}
|
||||
stderr := rt.IO().ErrOut.(*bytes.Buffer).String()
|
||||
for _, want := range []string{"reached page limit (3)", "has_more=true", "result is incomplete", "up to 1000", "page_token returned in stdout"} {
|
||||
if !strings.Contains(stderr, want) {
|
||||
t.Fatalf("stderr = %q, want %q", stderr, want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(stderr, "token_3") {
|
||||
t.Fatalf("stderr must not expose the continuation token, got %q", stderr)
|
||||
}
|
||||
|
||||
var envelope map[string]any
|
||||
if err := json.Unmarshal(rt.IO().Out.(*bytes.Buffer).Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v", err)
|
||||
}
|
||||
data, _ := envelope["data"].(map[string]any)
|
||||
if hasMore, _ := data["has_more"].(bool); !hasMore {
|
||||
t.Fatalf("has_more = %#v, want true for an incomplete result", data["has_more"])
|
||||
}
|
||||
if pageToken, _ := data["page_token"].(string); pageToken != "token_3" {
|
||||
t.Fatalf("page_token = %q, want token_3", pageToken)
|
||||
}
|
||||
if _, exists := data["truncated"]; exists {
|
||||
t.Fatalf("output schema must remain unchanged; unexpected truncated field in %#v", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteListAllPages_RepeatedTokenDoesNotReportPageLimit(t *testing.T) {
|
||||
callCount := 0
|
||||
rt := newBotShortcutRuntime(t, shortcutRoundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if strings.Contains(req.URL.Path, "/open-apis/im/v1/flags") {
|
||||
callCount++
|
||||
return shortcutJSONResponse(200, map[string]any{
|
||||
"code": 0,
|
||||
"data": map[string]any{
|
||||
"flag_items": []any{},
|
||||
"delete_flag_items": []any{},
|
||||
"messages": []any{},
|
||||
"has_more": true,
|
||||
"page_token": "same_token",
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected request: %s", req.URL.Path)
|
||||
}))
|
||||
|
||||
cmd := &cobra.Command{Use: "test"}
|
||||
cmd.Flags().Int("page-size", 50, "")
|
||||
cmd.Flags().Int("page-limit", 10, "")
|
||||
cmd.Flags().Bool("enrich-feed-thread", false, "")
|
||||
if err := cmd.ParseFlags(nil); err != nil {
|
||||
t.Fatalf("ParseFlags() error = %v", err)
|
||||
}
|
||||
setRuntimeField(t, rt, "Cmd", cmd)
|
||||
|
||||
if err := executeListAllPages(rt); err != nil {
|
||||
t.Fatalf("executeListAllPages() error = %v", err)
|
||||
}
|
||||
if callCount != 2 {
|
||||
t.Fatalf("API calls = %d, want 2 before repeated-token stop", callCount)
|
||||
}
|
||||
stderr := rt.IO().ErrOut.(*bytes.Buffer).String()
|
||||
if !strings.Contains(stderr, "page_token did not change") {
|
||||
t.Fatalf("stderr = %q, want non-advancing token warning", stderr)
|
||||
}
|
||||
if strings.Contains(stderr, "reached page limit") {
|
||||
t.Fatalf("stderr = %q, repeated token must not be reported as a page-limit stop", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteListAllPages_APIError(t *testing.T) {
|
||||
|
||||
@@ -14,5 +14,8 @@ func Shortcuts() []common.Shortcut {
|
||||
SlidesReplacePages,
|
||||
SlidesScreenshot,
|
||||
SlidesXMLGet,
|
||||
SlidesHistoryList,
|
||||
SlidesHistoryRevert,
|
||||
SlidesHistoryRevertStatus,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +154,9 @@ var SlidesCreate = common.Shortcut{
|
||||
if revisionID := common.GetFloat(data, "revision_id"); revisionID > 0 {
|
||||
result["revision_id"] = int(revisionID)
|
||||
}
|
||||
if issues, ok := data["issues"]; ok {
|
||||
result["issues"] = issues
|
||||
}
|
||||
|
||||
// Step 2: Add slides if provided
|
||||
if slidesStr != "" {
|
||||
@@ -182,6 +185,7 @@ var SlidesCreate = common.Shortcut{
|
||||
)
|
||||
|
||||
var slideIDs []string
|
||||
var slideIssues []map[string]interface{}
|
||||
for i, slideXML := range slides {
|
||||
slideData, err := runtime.CallAPITyped(
|
||||
"POST",
|
||||
@@ -194,13 +198,24 @@ var SlidesCreate = common.Shortcut{
|
||||
if err != nil {
|
||||
return appendSlidesProgressHint(err, fmt.Sprintf("adding slide %d/%d failed; presentation %s was created, %d slide(s) added before failure", i+1, len(slides), presentationID, i))
|
||||
}
|
||||
if sid := common.GetString(slideData, "slide_id"); sid != "" {
|
||||
sid := common.GetString(slideData, "slide_id")
|
||||
if sid != "" {
|
||||
slideIDs = append(slideIDs, sid)
|
||||
}
|
||||
if issues, ok := slideData["issues"]; ok {
|
||||
slideIssues = append(slideIssues, map[string]interface{}{
|
||||
"slide_index": i + 1,
|
||||
"slide_id": sid,
|
||||
"issues": issues,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
result["slide_ids"] = slideIDs
|
||||
result["slides_added"] = len(slideIDs)
|
||||
if len(slideIssues) > 0 {
|
||||
result["slide_issues"] = slideIssues
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -351,6 +351,56 @@ func TestSlidesCreateWithSlides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesCreatePreservesSchemaIssues(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"xml_presentation_id": "pres_issues",
|
||||
"issues": "presentation schema issue",
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_issues/slide",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"slide_id": "slide_001",
|
||||
"issues": "slide schema issue",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := runSlidesCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--slides", `["<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data/></slide>"]`,
|
||||
"--as", "user",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
data := decodeSlidesCreateEnvelope(t, stdout)
|
||||
if data["issues"] != "presentation schema issue" {
|
||||
t.Fatalf("issues = %v, want presentation schema issue", data["issues"])
|
||||
}
|
||||
slideIssues, ok := data["slide_issues"].([]interface{})
|
||||
if !ok || len(slideIssues) != 1 {
|
||||
t.Fatalf("slide_issues = %#v, want one entry", data["slide_issues"])
|
||||
}
|
||||
issue, _ := slideIssues[0].(map[string]interface{})
|
||||
if issue["slide_index"] != float64(1) || issue["slide_id"] != "slide_001" || issue["issues"] != "slide schema issue" {
|
||||
t.Fatalf("slide_issues[0] = %#v", issue)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSlidesCreateWithSlidesPartialFailure verifies error reporting when a slide fails to create.
|
||||
func TestSlidesCreateWithSlidesPartialFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
290
shortcuts/slides/slides_history.go
Normal file
290
shortcuts/slides/slides_history.go
Normal file
@@ -0,0 +1,290 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package slides
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
type slidesHistoryListSpec struct {
|
||||
PageSize int
|
||||
PageToken string
|
||||
}
|
||||
|
||||
type slidesHistoryRevertSpec struct {
|
||||
HistoryVersionID string
|
||||
}
|
||||
|
||||
type slidesHistoryRevertStatusSpec struct {
|
||||
TaskID string
|
||||
}
|
||||
|
||||
func parseSlidesHistoryPresentation(runtime *common.RuntimeContext) (presentationRef, error) {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return presentationRef{}, err
|
||||
}
|
||||
if ref.Kind == "wiki" {
|
||||
if err := runtime.EnsureScopes([]string{"wiki:node:read"}); err != nil {
|
||||
return presentationRef{}, err
|
||||
}
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
func validateSlidesHistoryPageSize(pageSize int) error {
|
||||
if pageSize < 1 || pageSize > 20 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid --page-size %d: must be between 1 and 20", pageSize).WithParam("--page-size")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSlidesHistoryVersionID(historyVersionID string) error {
|
||||
version, err := strconv.ParseInt(strings.TrimSpace(historyVersionID), 10, 64)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--history-version-id must be a positive integer string returned by slides +history-list").WithParam("--history-version-id").WithCause(err)
|
||||
}
|
||||
if version <= 0 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--history-version-id must be a positive integer string returned by slides +history-list").WithParam("--history-version-id")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func slidesHistoryListParams(spec slidesHistoryListSpec) map[string]interface{} {
|
||||
params := map[string]interface{}{
|
||||
"page_size": spec.PageSize,
|
||||
}
|
||||
if spec.PageToken != "" {
|
||||
params["page_token"] = spec.PageToken
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func slidesHistoryRevertBody(spec slidesHistoryRevertSpec) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"history_version_id": spec.HistoryVersionID,
|
||||
}
|
||||
}
|
||||
|
||||
func slidesHistoryStatusParams(spec slidesHistoryRevertStatusSpec) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"task_id": spec.TaskID,
|
||||
}
|
||||
}
|
||||
|
||||
func slidesHistoryAPIPath(presentationID, suffix string) string {
|
||||
return fmt.Sprintf("/open-apis/slides_ai/v1/xml_presentations/%s/%s", validate.EncodePathSegment(presentationID), suffix)
|
||||
}
|
||||
|
||||
func newSlidesHistoryDryRun(ref presentationRef, desc string) (*common.DryRunAPI, string) {
|
||||
dry := common.NewDryRunAPI()
|
||||
presentationID := ref.Token
|
||||
if ref.Kind == "wiki" {
|
||||
presentationID = "<resolved_slides_token>"
|
||||
dry.Desc("2-step orchestration: resolve wiki then " + desc).
|
||||
GET("/open-apis/wiki/v2/spaces/get_node").
|
||||
Desc("[1] Resolve wiki node to slides presentation").
|
||||
Params(map[string]interface{}{"token": ref.Token})
|
||||
} else {
|
||||
dry.Desc("OpenAPI: " + desc)
|
||||
}
|
||||
return dry, presentationID
|
||||
}
|
||||
|
||||
// SlidesHistoryList lists history versions of a Slides XML presentation.
|
||||
var SlidesHistoryList = common.Shortcut{
|
||||
Service: "slides",
|
||||
Command: "+history-list",
|
||||
Description: "List Slides presentation history versions",
|
||||
Risk: "read",
|
||||
Scopes: []string{"slides:presentation:read"},
|
||||
ConditionalScopes: []string{"wiki:node:read"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides", Required: true},
|
||||
{Name: "page-size", Type: "int", Default: "20", Desc: "history entries to return, range 1-20"},
|
||||
{Name: "page-token", Desc: "pagination token from the previous page's page_token"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
if _, err := parseSlidesHistoryPresentation(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateSlidesHistoryPageSize(runtime.Int("page-size"))
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
spec := slidesHistoryListSpec{
|
||||
PageSize: runtime.Int("page-size"),
|
||||
PageToken: strings.TrimSpace(runtime.Str("page-token")),
|
||||
}
|
||||
dry, presentationID := newSlidesHistoryDryRun(ref, "list Slides history versions")
|
||||
return dry.
|
||||
GET(slidesHistoryAPIPath(presentationID, "histories")).
|
||||
Params(slidesHistoryListParams(spec)).
|
||||
Set("xml_presentation_id", presentationID)
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
presentationID, err := resolvePresentationID(runtime, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spec := slidesHistoryListSpec{
|
||||
PageSize: runtime.Int("page-size"),
|
||||
PageToken: strings.TrimSpace(runtime.Str("page-token")),
|
||||
}
|
||||
|
||||
data, err := runtime.CallAPITyped(
|
||||
http.MethodGet,
|
||||
slidesHistoryAPIPath(presentationID, "histories"),
|
||||
slidesHistoryListParams(spec),
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.OutRaw(data, nil)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// SlidesHistoryRevert reverts a Slides XML presentation to a history version.
|
||||
var SlidesHistoryRevert = common.Shortcut{
|
||||
Service: "slides",
|
||||
Command: "+history-revert",
|
||||
Description: "Revert a Slides presentation to a historical version",
|
||||
Risk: "write",
|
||||
Scopes: []string{"slides:presentation:update", "slides:presentation:write_only"},
|
||||
ConditionalScopes: []string{"wiki:node:read"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides", Required: true},
|
||||
{Name: "history-version-id", Desc: "history_version_id from slides +history-list to revert to", Required: true},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
if _, err := parseSlidesHistoryPresentation(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateSlidesHistoryVersionID(runtime.Str("history-version-id")); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
spec := slidesHistoryRevertSpec{
|
||||
HistoryVersionID: strings.TrimSpace(runtime.Str("history-version-id")),
|
||||
}
|
||||
dry, presentationID := newSlidesHistoryDryRun(ref, "revert Slides history")
|
||||
return dry.
|
||||
POST(slidesHistoryAPIPath(presentationID, "history/revert")).
|
||||
Body(slidesHistoryRevertBody(spec)).
|
||||
Set("xml_presentation_id", presentationID)
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
presentationID, err := resolvePresentationID(runtime, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spec := slidesHistoryRevertSpec{
|
||||
HistoryVersionID: strings.TrimSpace(runtime.Str("history-version-id")),
|
||||
}
|
||||
|
||||
data, err := runtime.CallAPITyped(
|
||||
http.MethodPost,
|
||||
slidesHistoryAPIPath(presentationID, "history/revert"),
|
||||
nil,
|
||||
slidesHistoryRevertBody(spec),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.OutRaw(data, nil)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// SlidesHistoryRevertStatus gets the status of a Slides history revert task.
|
||||
var SlidesHistoryRevertStatus = common.Shortcut{
|
||||
Service: "slides",
|
||||
Command: "+history-revert-status",
|
||||
Description: "Get Slides history revert task status",
|
||||
Risk: "read",
|
||||
Scopes: []string{"slides:presentation:read"},
|
||||
ConditionalScopes: []string{"wiki:node:read"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides", Required: true},
|
||||
{Name: "task-id", Desc: "task_id returned by slides +history-revert", Required: true},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
if _, err := parseSlidesHistoryPresentation(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(runtime.Str("task-id")) == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--task-id is required").WithParam("--task-id")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
spec := slidesHistoryRevertStatusSpec{
|
||||
TaskID: strings.TrimSpace(runtime.Str("task-id")),
|
||||
}
|
||||
dry, presentationID := newSlidesHistoryDryRun(ref, "get Slides history revert status")
|
||||
return dry.
|
||||
GET(slidesHistoryAPIPath(presentationID, "history/revert_status")).
|
||||
Params(slidesHistoryStatusParams(spec)).
|
||||
Set("xml_presentation_id", presentationID)
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
ref, err := parsePresentationRef(runtime.Str("presentation"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
presentationID, err := resolvePresentationID(runtime, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spec := slidesHistoryRevertStatusSpec{
|
||||
TaskID: strings.TrimSpace(runtime.Str("task-id")),
|
||||
}
|
||||
|
||||
data, err := runtime.CallAPITyped(
|
||||
http.MethodGet,
|
||||
slidesHistoryAPIPath(presentationID, "history/revert_status"),
|
||||
slidesHistoryStatusParams(spec),
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.OutRaw(data, nil)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
443
shortcuts/slides/slides_history_test.go
Normal file
443
shortcuts/slides/slides_history_test.go
Normal file
@@ -0,0 +1,443 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package slides
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestSlidesHistoryDeclaredScopes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
shortcut common.Shortcut
|
||||
wantBase []string
|
||||
wantFull []string
|
||||
}{
|
||||
{
|
||||
name: "list",
|
||||
shortcut: SlidesHistoryList,
|
||||
wantBase: []string{"slides:presentation:read"},
|
||||
wantFull: []string{"slides:presentation:read", "wiki:node:read"},
|
||||
},
|
||||
{
|
||||
name: "revert",
|
||||
shortcut: SlidesHistoryRevert,
|
||||
wantBase: []string{"slides:presentation:update", "slides:presentation:write_only"},
|
||||
wantFull: []string{"slides:presentation:update", "slides:presentation:write_only", "wiki:node:read"},
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
shortcut: SlidesHistoryRevertStatus,
|
||||
wantBase: []string{"slides:presentation:read"},
|
||||
wantFull: []string{"slides:presentation:read", "wiki:node:read"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.shortcut.ScopesForIdentity("user"); !reflect.DeepEqual(got, tt.wantBase) {
|
||||
t.Fatalf("user preflight scopes = %#v, want %#v", got, tt.wantBase)
|
||||
}
|
||||
if got := tt.shortcut.ScopesForIdentity("bot"); !reflect.DeepEqual(got, tt.wantBase) {
|
||||
t.Fatalf("bot preflight scopes = %#v, want %#v", got, tt.wantBase)
|
||||
}
|
||||
if got := tt.shortcut.DeclaredScopesForIdentity("user"); !reflect.DeepEqual(got, tt.wantFull) {
|
||||
t.Fatalf("declared scopes = %#v, want %#v", got, tt.wantFull)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryValidation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
shortcut common.Shortcut
|
||||
args []string
|
||||
param string
|
||||
wantCause bool
|
||||
}{
|
||||
{
|
||||
name: "list rejects unsupported presentation input",
|
||||
shortcut: SlidesHistoryList,
|
||||
args: []string{"+history-list", "--presentation", "tmp/wiki/wikcn123", "--as", "bot"},
|
||||
param: "--presentation",
|
||||
},
|
||||
{
|
||||
name: "list rejects invalid page size",
|
||||
shortcut: SlidesHistoryList,
|
||||
args: []string{"+history-list", "--presentation", "presHistory", "--page-size", "0", "--as", "bot"},
|
||||
param: "--page-size",
|
||||
},
|
||||
{
|
||||
name: "revert rejects non-numeric history version id",
|
||||
shortcut: SlidesHistoryRevert,
|
||||
args: []string{"+history-revert", "--presentation", "presHistory", "--history-version-id", "abc", "--as", "bot"},
|
||||
param: "--history-version-id",
|
||||
wantCause: true,
|
||||
},
|
||||
{
|
||||
name: "revert rejects non-positive history version id",
|
||||
shortcut: SlidesHistoryRevert,
|
||||
args: []string{"+history-revert", "--presentation", "presHistory", "--history-version-id", "0", "--as", "bot"},
|
||||
param: "--history-version-id",
|
||||
},
|
||||
{
|
||||
name: "status rejects empty task id",
|
||||
shortcut: SlidesHistoryRevertStatus,
|
||||
args: []string{"+history-revert-status", "--presentation", "presHistory", "--task-id", "", "--as", "bot"},
|
||||
param: "--task-id",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
err := runSlidesShortcut(t, f, stdout, tt.shortcut, tt.args)
|
||||
if err == nil {
|
||||
t.Fatal("expected validation error, got nil")
|
||||
}
|
||||
_, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("error is not typed: %T %v", err, err)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) {
|
||||
t.Fatalf("expected validation error, got %T: %v", err, err)
|
||||
}
|
||||
if validationErr.Param != tt.param {
|
||||
t.Fatalf("param = %q, want %q (err: %v)", validationErr.Param, tt.param, err)
|
||||
}
|
||||
if tt.wantCause && errors.Unwrap(err) == nil {
|
||||
t.Fatalf("expected wrapped cause, got nil (err: %v)", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryDryRun(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
listCmd := newSlidesHistoryRuntimeCmd(t, SlidesHistoryList, map[string]string{
|
||||
"presentation": "presHistoryDryRun",
|
||||
"page-size": "5",
|
||||
"page-token": "page_token_1",
|
||||
})
|
||||
listDry := decodeSlidesHistoryDryRun(t, SlidesHistoryList.DryRun(context.Background(), common.TestNewRuntimeContext(listCmd, nil)))
|
||||
if got, want := listDry.API[0].URL, "/open-apis/slides_ai/v1/xml_presentations/presHistoryDryRun/histories"; got != want {
|
||||
t.Fatalf("list dry-run URL = %q, want %q", got, want)
|
||||
}
|
||||
if got := int(listDry.API[0].Params["page_size"].(float64)); got != 5 {
|
||||
t.Fatalf("list page_size = %d, want 5", got)
|
||||
}
|
||||
if got := listDry.API[0].Params["page_token"]; got != "page_token_1" {
|
||||
t.Fatalf("list page_token = %#v, want page_token_1", got)
|
||||
}
|
||||
|
||||
revertCmd := newSlidesHistoryRuntimeCmd(t, SlidesHistoryRevert, map[string]string{
|
||||
"presentation": "presHistoryDryRun",
|
||||
"history-version-id": "42",
|
||||
})
|
||||
revertDry := decodeSlidesHistoryDryRun(t, SlidesHistoryRevert.DryRun(context.Background(), common.TestNewRuntimeContext(revertCmd, nil)))
|
||||
if got, want := revertDry.API[0].URL, "/open-apis/slides_ai/v1/xml_presentations/presHistoryDryRun/history/revert"; got != want {
|
||||
t.Fatalf("revert dry-run URL = %q, want %q", got, want)
|
||||
}
|
||||
if got := revertDry.API[0].Body["history_version_id"]; got != "42" {
|
||||
t.Fatalf("revert history_version_id = %#v, want 42", got)
|
||||
}
|
||||
if _, ok := revertDry.API[0].Body["wait_timeout_ms"]; ok {
|
||||
t.Fatal("revert body must not contain wait_timeout_ms")
|
||||
}
|
||||
|
||||
statusCmd := newSlidesHistoryRuntimeCmd(t, SlidesHistoryRevertStatus, map[string]string{
|
||||
"presentation": "presHistoryDryRun",
|
||||
"task-id": "task_1",
|
||||
})
|
||||
statusDry := decodeSlidesHistoryDryRun(t, SlidesHistoryRevertStatus.DryRun(context.Background(), common.TestNewRuntimeContext(statusCmd, nil)))
|
||||
if got, want := statusDry.API[0].URL, "/open-apis/slides_ai/v1/xml_presentations/presHistoryDryRun/history/revert_status"; got != want {
|
||||
t.Fatalf("status dry-run URL = %q, want %q", got, want)
|
||||
}
|
||||
if got := statusDry.API[0].Params["task_id"]; got != "task_1" {
|
||||
t.Fatalf("status task_id = %#v, want task_1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryDryRunWithWikiPresentation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := newSlidesHistoryRuntimeCmd(t, SlidesHistoryList, map[string]string{
|
||||
"presentation": "https://example.feishu.cn/wiki/wikcn123",
|
||||
"page-size": "20",
|
||||
})
|
||||
dry := decodeSlidesHistoryDryRun(t, SlidesHistoryList.DryRun(context.Background(), common.TestNewRuntimeContext(cmd, nil)))
|
||||
if len(dry.API) != 2 {
|
||||
t.Fatalf("api calls = %d, want 2: %#v", len(dry.API), dry.API)
|
||||
}
|
||||
if got, want := dry.API[0].URL, "/open-apis/wiki/v2/spaces/get_node"; got != want {
|
||||
t.Fatalf("wiki dry-run URL = %q, want %q", got, want)
|
||||
}
|
||||
if got := dry.API[0].Params["token"]; got != "wikcn123" {
|
||||
t.Fatalf("wiki node parameter mismatch: got %#v, want placeholder node id", got)
|
||||
}
|
||||
if got, want := dry.API[1].URL, "/open-apis/slides_ai/v1/xml_presentations/%3Cresolved_slides_token%3E/histories"; got != want {
|
||||
t.Fatalf("history dry-run URL = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryExecuteList(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
var capturedQuery url.Values
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/presHistory/histories",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"entries": []interface{}{
|
||||
map[string]interface{}{
|
||||
"revision_id": float64(42),
|
||||
"history_version_id": "11",
|
||||
"edit_time": "2026-06-22T12:24:45Z",
|
||||
"type": float64(1),
|
||||
"editor_ids": []interface{}{"ou_1"},
|
||||
},
|
||||
},
|
||||
"has_more": true,
|
||||
"page_token": "page_token_2",
|
||||
},
|
||||
},
|
||||
OnMatch: func(req *http.Request) {
|
||||
capturedQuery = req.URL.Query()
|
||||
},
|
||||
})
|
||||
|
||||
err := runSlidesShortcut(t, f, stdout, SlidesHistoryList, []string{
|
||||
"+history-list",
|
||||
"--presentation", "presHistory",
|
||||
"--page-size", "5",
|
||||
"--page-token", "page_token_1",
|
||||
"--as", "bot",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if got := capturedQuery.Get("page_size"); got != "5" {
|
||||
t.Fatalf("page_size query = %q, want 5", got)
|
||||
}
|
||||
if got := capturedQuery.Get("page_token"); got != "page_token_1" {
|
||||
t.Fatalf("page_token query = %q, want page_token_1", got)
|
||||
}
|
||||
|
||||
data := decodeSlidesHistoryEnvelope(t, stdout)
|
||||
if got := data["page_token"]; got != "page_token_2" {
|
||||
t.Fatalf("page_token = %#v, want page_token_2", got)
|
||||
}
|
||||
entries, _ := data["entries"].([]interface{})
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("entries = %#v, want one entry", data["entries"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryExecuteRevert(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
stub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/presHistory/history/revert",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"task_id": "task_1",
|
||||
"status": "running",
|
||||
"history_version_id": "42",
|
||||
"poll_after_ms": float64(10000),
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(stub)
|
||||
|
||||
err := runSlidesShortcut(t, f, stdout, SlidesHistoryRevert, []string{
|
||||
"+history-revert",
|
||||
"--presentation", "presHistory",
|
||||
"--history-version-id", "42",
|
||||
"--as", "bot",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
var body map[string]interface{}
|
||||
if err := json.Unmarshal(stub.CapturedBody, &body); err != nil {
|
||||
t.Fatalf("decode revert body: %v\nraw=%s", err, stub.CapturedBody)
|
||||
}
|
||||
if got := body["history_version_id"]; got != "42" {
|
||||
t.Fatalf("history_version_id = %#v, want 42", got)
|
||||
}
|
||||
if _, ok := body["wait_timeout_ms"]; ok {
|
||||
t.Fatal("revert body must not contain wait_timeout_ms")
|
||||
}
|
||||
|
||||
data := decodeSlidesHistoryEnvelope(t, stdout)
|
||||
if got := data["task_id"]; got != "task_1" {
|
||||
t.Fatalf("task_id = %#v, want task_1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryExecuteRevertStatus(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
var capturedQuery url.Values
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/presHistory/history/revert_status",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"status": "done",
|
||||
"history_version_id": "11",
|
||||
},
|
||||
},
|
||||
OnMatch: func(req *http.Request) {
|
||||
capturedQuery = req.URL.Query()
|
||||
},
|
||||
})
|
||||
|
||||
err := runSlidesShortcut(t, f, stdout, SlidesHistoryRevertStatus, []string{
|
||||
"+history-revert-status",
|
||||
"--presentation", "presHistory",
|
||||
"--task-id", "task_1",
|
||||
"--as", "bot",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if got := capturedQuery.Get("task_id"); got != "task_1" {
|
||||
t.Fatalf("task_id query = %q, want task_1", got)
|
||||
}
|
||||
data := decodeSlidesHistoryEnvelope(t, stdout)
|
||||
if got := data["status"]; got != "done" {
|
||||
t.Fatalf("status = %#v, want done", got)
|
||||
}
|
||||
if got := data["history_version_id"]; got != "11" {
|
||||
t.Fatalf("history_version_id = %#v, want 11", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesHistoryExecuteResolvesWikiPresentation(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/wiki/v2/spaces/get_node",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"node": map[string]interface{}{
|
||||
"obj_type": "slides",
|
||||
"obj_token": "presReal",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/presReal/histories",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"entries": []interface{}{},
|
||||
"has_more": false,
|
||||
"page_token": "",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := runSlidesShortcut(t, f, stdout, SlidesHistoryList, []string{
|
||||
"+history-list",
|
||||
"--presentation", "https://example.feishu.cn/wiki/wikcn123",
|
||||
"--as", "bot",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data := decodeSlidesHistoryEnvelope(t, stdout)
|
||||
if got := data["has_more"]; got != false {
|
||||
t.Fatalf("has_more = %#v, want false", got)
|
||||
}
|
||||
}
|
||||
|
||||
type slidesHistoryDryRunOutput struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
|
||||
func newSlidesHistoryRuntimeCmd(t *testing.T, shortcut common.Shortcut, values map[string]string) *cobra.Command {
|
||||
t.Helper()
|
||||
|
||||
cmd := &cobra.Command{Use: shortcut.Command}
|
||||
for _, flag := range shortcut.Flags {
|
||||
switch flag.Type {
|
||||
case "int":
|
||||
cmd.Flags().Int(flag.Name, 0, flag.Desc)
|
||||
default:
|
||||
cmd.Flags().String(flag.Name, flag.Default, flag.Desc)
|
||||
}
|
||||
}
|
||||
for name, value := range values {
|
||||
if err := cmd.Flags().Set(name, value); err != nil {
|
||||
t.Fatalf("set --%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func decodeSlidesHistoryDryRun(t *testing.T, dry *common.DryRunAPI) slidesHistoryDryRunOutput {
|
||||
t.Helper()
|
||||
|
||||
raw, err := json.Marshal(dry)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal dry-run: %v", err)
|
||||
}
|
||||
var out slidesHistoryDryRunOutput
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\nraw=%s", err, raw)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decodeSlidesHistoryEnvelope(t *testing.T, stdout *bytes.Buffer) map[string]interface{} {
|
||||
t.Helper()
|
||||
|
||||
var envelope map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode envelope: %v\nraw=%s", err, stdout.String())
|
||||
}
|
||||
data, _ := envelope["data"].(map[string]interface{})
|
||||
if data == nil {
|
||||
t.Fatalf("missing data in envelope: %#v", envelope)
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -139,6 +139,7 @@ type replacePageResult struct {
|
||||
NewSlideID string
|
||||
Status string
|
||||
Error string
|
||||
Issues interface{}
|
||||
RevisionID *int
|
||||
}
|
||||
|
||||
@@ -330,6 +331,9 @@ func replaceOnePage(runtime *common.RuntimeContext, presentationID string, item
|
||||
return result, err
|
||||
}
|
||||
result.NewSlideID = newSlideID
|
||||
if issues, ok := createData["issues"]; ok {
|
||||
result.Issues = issues
|
||||
}
|
||||
if rev, ok := revisionFromData(createData); ok {
|
||||
revisionID = rev
|
||||
result.RevisionID = &rev
|
||||
@@ -389,6 +393,9 @@ func replacePageResultsOutput(results []replacePageResult) []map[string]interfac
|
||||
if result.Error != "" {
|
||||
m["error"] = result.Error
|
||||
}
|
||||
if result.Issues != nil {
|
||||
m["issues"] = result.Issues
|
||||
}
|
||||
if result.RevisionID != nil {
|
||||
m["revision_id"] = *result.RevisionID
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func TestReplacePagesCreatesBeforeThenDeletesOld(t *testing.T) {
|
||||
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{"slide_id": "new2", "revision_id": 11},
|
||||
"data": map[string]interface{}{"slide_id": "new2", "revision_id": 11, "issues": "slide schema issue"},
|
||||
},
|
||||
OnMatch: func(req *http.Request) {
|
||||
requestOrder = append(requestOrder, req.Method)
|
||||
@@ -123,6 +123,9 @@ func TestReplacePagesCreatesBeforeThenDeletesOld(t *testing.T) {
|
||||
if first["old_slide_id"] != "old2" || first["new_slide_id"] != "new2" || first["status"] != "replaced" {
|
||||
t.Fatalf("result = %#v", first)
|
||||
}
|
||||
if first["issues"] != "slide schema issue" {
|
||||
t.Fatalf("result.issues = %v, want slide schema issue", first["issues"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplacePagesContinueOnErrorReturnsPartialFailure(t *testing.T) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: lark-apps
|
||||
version: 1.0.0
|
||||
description: "妙搭(Spark/Miaoda)应用开发与托管:应用创建、HTML静态站点发布、本地全栈开发、云端生成迭代、AI相关能力和飞书平台能力或者其他外部能力集成、日志/Trace/监控指标/PV/UV 查询、环境变量管理、应用角色与成员管理、自动化触发器(定时/记录变更/Webhook/飞书审批)。当用户要开发/新建一个系统·工具·平台·应用,或要本地开发 / 云端开发 / 修改 / 部署 / 发布 / 上线 / 拿可分享链接,或用 HTML 做页面·网站·部署到妙搭,或提到妙搭/Spark/Miaoda(应用运行时域名形如 *.aiforce.cloud)、应用数据库、应用文件存储、开放 API Key、可见范围、应用角色/角色成员、线上日志、接口请求量、错误量、延迟、访问量、环境变量、给妙搭应用配自动化任务/定时触发/审批通过后自动触发时使用。不负责普通云盘文件上传(lark-drive)、飞书文档编辑(lark-doc)、原生幻灯片创建(lark-slides)。"
|
||||
description: "妙搭(Spark/Miaoda)应用开发与托管:应用创建、本地全栈开发、云端生成迭代、创意设计(UI mockup / 可交互原型 / 线框图 / 落地页 / 仪表盘 / 幻灯片 deck / 视觉探索)、AI相关能力和飞书平台能力或者其他外部能力集成、日志/Trace/监控指标/PV/UV 查询、环境变量管理、应用角色与成员管理、自动化触发器(定时/记录变更/Webhook/飞书审批)。当用户要开发/新建一个系统·工具·平台·应用,或要本地开发 / 云端开发 / 修改 / 部署 / 发布 / 上线 / 拿可分享链接,或用 HTML 做页面·网站·部署到妙搭,或要设计 / design / mockup / prototype / wireframe / 做 PPT / deck / 视觉探索,或提到妙搭/Spark/Miaoda(应用运行时域名形如 *.aiforce.cloud)、应用数据库、应用文件存储、开放 API Key、可见范围、应用角色/角色成员、线上日志、接口请求量、错误量、延迟、访问量、环境变量、给妙搭应用配自动化任务/定时触发/审批通过后自动触发时使用。不负责普通云盘文件上传(lark-drive)、飞书文档编辑(lark-doc)、原生幻灯片创建(lark-slides)。"
|
||||
metadata:
|
||||
requires:
|
||||
bins: ["lark-cli"]
|
||||
@@ -10,7 +10,7 @@ metadata:
|
||||
|
||||
# apps (v1)
|
||||
|
||||
妙搭应用属于用户资产。默认用 `--as user`;认证、scope、exit-10、高风险确认、`_notice` 等通用处理只读 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),不要在本 skill 里复制。妙搭应用有三条开发路径:**本地全栈**(拉源码本地写)/ **HTML 托管**(发布静态产物)/ **云端会话**(妙搭 AI 生成)。
|
||||
妙搭应用属于用户资产。默认用 `--as user`;认证、scope、exit-10、高风险确认、`_notice` 等通用处理只读 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),不要在本 skill 里复制。妙搭应用有两条开发路径:**本地开发**(拉源码本地写)/ **云端会话**(妙搭 AI 生成)。
|
||||
|
||||
## 身份与授权
|
||||
|
||||
@@ -32,16 +32,18 @@ lark-cli auth login --domain apps
|
||||
| 找已有 app_id、按名字过滤应用 | `+list --keyword <name>` | [`lark-apps-list.md`](references/lark-apps-list.md) |
|
||||
| 查单个应用详情(类型、名称、发布状态等) | `+get --app-id <app_id>` | [`lark-apps-get.md`](references/lark-apps-get.md) |
|
||||
| 改应用名或描述 | `+update` | [`lark-apps-update.md`](references/lark-apps-update.md) |
|
||||
| 发布本地 `index.html` 或静态目录为可访问 URL | `+html-publish` | [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md) |
|
||||
| 开发已有应用 / 初始化本地仓库(开发方式已定为本地后;先解析 app_id,勿 `+create` 新建) | `+init`(或手动 `+git-credential-init` + 原生 git)。**执行前必读** [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md);修改源码还须遵守下方「平台资源与应用源码边界」 | [`lark-apps-init.md`](references/lark-apps-init.md), [`lark-apps-git-credential.md`](references/lark-apps-git-credential.md) |
|
||||
| HTML 应用 / 创意模式 — 写 HTML 页面/网站、静态页、PPT/deck、落地页、仪表盘、UI mockup、原型、线框图、视觉探索 | 加载 [`creative-design/creative-design.md`](creative-design/creative-design.md)(含完整开发与发布流程) | [`creative-design/creative-design.md`](creative-design/creative-design.md) |
|
||||
| 旧版存量 HTML 应用(无 Git 管理)继续上传已有静态产物 | `+html-publish`(仅兼容旧链路;新建 html / 创意模式 / creative-design 产物不得使用) | [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md) |
|
||||
| 开发已有应用 / 初始化本地仓库(开发方式已定为本地后;先解析 app_id,勿 `+create` 新建) | `+init`(或手动 `+git-credential-init` + 原生 git)。**执行前必读** [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md),含端到端流程和领域规则 | [`lark-apps-init.md`](references/lark-apps-init.md), [`lark-apps-git-credential.md`](references/lark-apps-git-credential.md) |
|
||||
| 本地开发时 `.env.local` 损坏/丢失,重新拉取启动期环境变量 | `+env-pull` | [`lark-apps-env-pull.md`](references/lark-apps-env-pull.md) |
|
||||
| 管理应用环境变量(查看/设置/删除) | `+env-list`, `+env-set`, `+env-delete` | [`lark-apps-env.md`](references/lark-apps-env.md) |
|
||||
| 查线上日志、Trace、请求数、错误率、延迟、CPU、memory、PV/UV/访问量 | `+log-list`, `+log-get`, `+trace-list`, `+trace-get`, `+metric-list`, `+analytics-list` | [`lark-apps-observability.md`](references/lark-apps-observability.md) |
|
||||
| 看表 / 看结构 / 初始化多环境 / 导入导出数据 / 变更追溯 / 行级审计 / dev→online 发布 / 时间点恢复 / 查 DB 用量 | `+db-table-list`、`+db-table-get`、`+db-env-create`、`+db-data-export`/`+db-data-import`、`+db-changelog-list`、`+db-audit-status`/`+db-audit-enable`/`+db-audit-disable`/`+db-audit-list`、`+db-env-diff`/`+db-env-migrate`、`+db-recovery-diff`/`+db-recovery-apply`、`+db-quota-get` | [`lark-apps-db.md`](references/lark-apps-db.md) |
|
||||
| 逐条执行 SQL(SELECT / DML / DDL);建表 / 改表 / 写 SQL 的平台规范 | `+db-execute` | [`lark-apps-db-execute.md`](references/lark-apps-db-execute.md)(含「平台 SQL 规范」:审计列 / RLS / `user_profile` / 禁用 SQL / PG 陷阱) |
|
||||
| 管理应用文件存储:上传/下载本地文件、列出/查看/删除已存文件、生成临时分享链接、查存储用量 | `+file-upload`/`+file-download`/`+file-list`/`+file-get`/`+file-sign`/`+file-delete`/`+file-quota-get` | [`lark-apps-file.md`](references/lark-apps-file.md) |
|
||||
| **部署/上线全栈应用**("部署""上线""推上去并部署""发布到云端");查发布状态/历史 | `+release-create`(部署上线动作), `+release-get`(轮询发布结果,finished 给 online_url / failed 给 error_logs), `+release-list` | [`lark-apps-release-create.md`](references/lark-apps-release-create.md), [`lark-apps-release-get.md`](references/lark-apps-release-get.md), [`lark-apps-release-list.md`](references/lark-apps-release-list.md) |
|
||||
| **部署/上线应用**("部署""上线""推上去并部署""发布到云端");查发布状态/历史 | 本地开发链路先按 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) 确认本次改动已 git commit + git push,再用 `+release-create` / `+release-get`;查历史用 `+release-list` | [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md), [`lark-apps-release-create.md`](references/lark-apps-release-create.md), [`lark-apps-release-get.md`](references/lark-apps-release-get.md), [`lark-apps-release-list.md`](references/lark-apps-release-list.md) |
|
||||
| 设置或查看运行时可见范围 | `+access-scope-set`, `+access-scope-get` | 对应 access-scope reference |
|
||||
| 创意模式(html)应用的评论相关操作 | 创意模式应用评论走 lark-drive 文档评论体系,读取 [`../lark-drive/SKILL.md`](../lark-drive/SKILL.md) 了解评论能力 | [`../lark-drive/SKILL.md`](../lark-drive/SKILL.md) |
|
||||
| 管理 `app_...` 应用内角色、角色成员,或查询用户匹配角色 | `+role-list/get/create/update/delete`, `+role-member-list/add/remove`, `+role-match-list` | [`lark-apps-role.md`](references/lark-apps-role.md) |
|
||||
| 云端 Agent 生成/迭代应用(开发方式已定为云端后) | `+session-create` -> `+chat` -> `+session-get` | [`lark-apps-cloud-dev.md`](references/lark-apps-cloud-dev.md) |
|
||||
| 管理妙搭应用开放 API Key(创建/查看/启停/重置/删除凭证;密钥仅 create/reset 一次性返回) | `+openapi-key-list/get/create/update/enable/disable/delete/reset` | [`lark-apps-openapi-key.md`](references/lark-apps-openapi-key.md) |
|
||||
@@ -63,9 +65,9 @@ lark-cli auth login --domain apps
|
||||
|
||||
| 信号 | 判定 |
|
||||
|---|---|
|
||||
| 静态展示 / 单页 / PPT/demo / 无后端状态 | `app_type=html`,跳过本地/云端轴,开发完按 [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md)(含"未提部署→先问是否发布") |
|
||||
| 静态展示 / 单页 / PPT/deck / demo / 落地页 / 仪表盘 / UI mockup / 可交互原型 / 线框图 / 视觉探索 / 无后端状态 | `app_type=html`,加载 [`creative-design/creative-design.md`](creative-design/creative-design.md)(含完整开发与发布流程) |
|
||||
| 登录 / 数据库 / 持久化 / 多人协作 / 增删改查 / 报名 / 投票 / 站会 / OKR / 泛称"系统·工具" | `app_type=full_stack` |
|
||||
| 用户要自己写 / 本地 IDE·code agent / 拉源码到本地 / 交研发 | 本地全栈,读 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) |
|
||||
| 用户要自己写 / 本地 IDE·code agent / 拉源码到本地 / 交研发 | 本地开发,读 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) |
|
||||
| 让妙搭 AI 云端生成 / 对话式 / 自己不碰代码 | 云端会话,读 [`lark-apps-cloud-dev.md`](references/lark-apps-cloud-dev.md) |
|
||||
| 未表达"谁来写"偏好 | **必须先问**(本地代码开发 vs 云端 AI 生成);选定前不擅自选边、不暗示默认,不得以"需求不模糊"为由跳过提问直接 `+init` / `git clone` / `+session-create` / 首轮 `+chat` |
|
||||
| 修改已有 + 当前目录是 `.spark/meta.json` 项目 | 直接继续本地按意图路由,不必问也不必判云端 |
|
||||
@@ -75,16 +77,19 @@ lark-cli auth login --domain apps
|
||||
|
||||
- **发布意图判定**:用户要"可访问 / 线上 / 分享 / 新链接 / 上线" = 发布意图,先走发布链路、确认完成再给链接。
|
||||
- 完成 ≠ 发布:云端会话完成 / `+list is_published=true` 都不代表最新内容已部署。
|
||||
- 开发态链接 `https://miaoda.feishu.cn/app/{app_id}`:进应用编辑/开发态、管理与继续开发应用的入口。发布成功后,连同发布态链接一并提供给用户(说明"管理 / 继续开发去这里");但它仅进编辑态,**不能**顶替发布态链接当分享链接。
|
||||
- 发布态链接来源:html → `+html-publish` 的 `data.url`;全栈 → `+release-get` 轮询 `finished` 给 `online_url` / `failed` 给 `error_logs`。
|
||||
- **可见范围**:发布态链接(html 的 `data.url`、全栈的 `online_url`)默认仅**创建者可见**,发给他人对方会无权限打不开。当可分享链接交付给用户前,先告知当前仅本人可见,再询问是否用 `+access-scope-set`(`tenant`/`public`/`specific`)放开(可先 `+access-scope-get` 查当前范围)。
|
||||
- 开发态链接 `https://miaoda.feishu.cn/app/{app_id}`(仅 full_stack 应用):进应用编辑/开发态、管理与继续开发应用的入口。创意模式(html)应用开发态和发布态是同一个链接,无需额外提供开发态链接。
|
||||
- 发布态链接来源:`+release-get` 轮询 `finished` 给 `online_url` / `failed` 给 `error_logs`(html 和 full_stack 统一走 `+release-get`)。
|
||||
- html 应用的主链路是创意模式开发方式:按 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) 初始化仓库、在仓库内产出 HTML 及关联文件,并通过 git commit / git push / `+release-create` / `+release-get` 发布部署。任何 git 操作(clone / pull / push)报错时,先执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 刷新本地 Git 凭证,再重试原 git 命令。如果刷新凭证也失败,**停止并向用户报告**:原始 git 错误、凭证刷新失败原因,以及是否可能是当前环境(操作系统、沙箱)限制导致(如 macOS Keychain 在沙箱中不可用、Linux 加密文件目录不可写等)。不要改走 `+html-publish`,也不要把 `+html-publish` 当作本地开发链路的 fallback。
|
||||
- 创意模式(html)应用的链接格式为 `https://{租户域名}/page/{meta_token}`,**开发态和发布态是同一个链接**(区别于 full_stack 应用两者分开)。此链接形似飞书文档链接。`+get --app-id <meta_token>` 可获取应用信息(含 `app_id`),`+get --app-id <app_id>` 可获取 `meta_token`。看到 `/page/xxx` 链接时,它是妙搭创意模式应用,不要当成飞书文档跳过。
|
||||
|
||||
## 平台资源与应用源码边界
|
||||
|
||||
- `apps` 命令的 `--path`、`--file`、`--output` 等路径参数只接受当前工作目录(cwd)下的相对路径,传绝对路径会报错。如果目标文件不在 cwd 下,先 `cd` 到目标目录再执行命令。
|
||||
- 图片、字体、音视频等资源型文件属于平台资源,不应提交到 git 仓库、引用本地路径或以 base64 内联到源码中。先通过 `lark-cli apps +file-upload --app-id <app_id> --file <local_path>` 上传到应用文件存储,拿到返回的远端 URL 后在代码中引用。上传返回的链接按 app 隔离,不同应用必须各自重新上传,不能跨应用复用同一链接。详情读 [`lark-apps-file.md`](references/lark-apps-file.md)。
|
||||
- `apps +role-*` 只管理平台角色资源;修改已初始化应用的源码(包括当前目录已经是应用项目)时,先查看工作区 `.agents/skills/`,完整读取与任务匹配的领域 skill,再按其路由读取所需 reference。角色鉴权或运行态角色管理读应用内 `authz-guide`,不能用本 skill 的平台命令参考推断运行时合同。
|
||||
- `lark-cli` 只用于开发过程中的平台资源核验或变更。应用运行时代码必须使用工程内领域 skill 规定的 SDK,禁止通过 `exec` 或子进程调用 `lark-cli`。
|
||||
- 平台回读出的当前资源 ID、名称和成员只用于事实核验,不自动构成业务策略;除非需求或应用内领域 skill 明确定义,禁止把当前样本硬编码成 allowlist、denylist、只读集合或权限规则。
|
||||
- 实现领域 SDK 时,以实际包导出的类型和应用内领域 reference 记录的入参、响应路径为准;禁止修改 ambient `.d.ts`、补造宽松类型或强制断言,让猜测的 SDK 结构仅在本地“编译通过”。
|
||||
- 实现领域 SDK 时,以实际包导出的类型和应用内领域 reference 记录的入参、响应路径为准;禁止修改 ambient `.d.ts`、补造宽松类型或强制断言,让猜测的 SDK 结构仅在本地"编译通过"。
|
||||
- typecheck/build 成功不等于合同正确。交付前逐项核对每个 SDK 调用的入参、响应取值路径和策略分支;涉及更新、删除等不同动作时,分别验证各自动作所需的完整状态,不能复用更弱的前置判断。
|
||||
- 源码任务交付前确认新增页面、Controller、Module 已接入真实 router/bootstrap,并运行项目现有 typecheck/build;只创建未接线文件不算完成。
|
||||
- `+access-scope-*` 只管运行时可见范围(谁能打开应用),不是角色权限;应用协作者/开发权限仍需使用妙搭 Web。自动化触发器请用 `+automation-*`(见「意图路由」)。
|
||||
@@ -93,6 +98,12 @@ lark-cli auth login --domain apps
|
||||
|
||||
`app_id` 必须是妙搭应用 ID(`app_` 开头)。`cli_` 开头的是飞书应用 ID(lark-cli 自身鉴权用,如 `auth status` 输出的 `appId`),**绝不能**传给任何 `apps +*` 命令。
|
||||
|
||||
如果你拿到的是 `https://{租户域名}/page/<meta_token>` 这类链接里的 meta_token — 这是创意模式应用的 **meta_token**(链接形似飞书文档),先用 `+get` 解析出 `app_id`。如果拿到的不是链接、也不是 `app_` 开头,可能是裸 meta_token,同样先用 `+get --app-id <token>` 尝试获取应用信息,能正常返回则说明是 meta_token:
|
||||
|
||||
```bash
|
||||
lark-cli apps +get --app-id <meta_token> -q '.data.app.app_id'
|
||||
```
|
||||
|
||||
按顺序尝试,不要一上来要求用户手填:
|
||||
|
||||
1. 用户给出 `app_xxx` 或妙搭链接(如 `/app/app_xxx`)时直接提取。
|
||||
@@ -107,4 +118,4 @@ lark-cli auth login --domain apps
|
||||
## 高影响动作:确认与预授权
|
||||
|
||||
- **预授权判定**:判断用户是否表达了"放手做完、不用中途逐步问我"的意图——明确免确认(如"别问 / 直接做 / 自己定"),或要求一气呵成做到完成(如"做完部署上线给我")。是 → 整个流程按合理默认往下走、不再逐步确认(含 clone 到派生目录、发布等);否 → 缺失参数(如目录)该问就问、高影响动作先确认。
|
||||
- **禁止预授权判定底线**(即便已预授权也不豁免):① 会删/丢数据或不可逆的 DB 操作(判据见 [`lark-apps-db-execute.md`](references/lark-apps-db-execute.md))先 `--dry-run` 确认;② `+role-delete`、`+role-member-remove --all`、批量移除成员必须先确认 app、role、成员范围和后果,不能从泛化"直接做"推导出 `--yes`;命令式“删除/移除某对象”只确定操作目标,不等于用户已确认不可逆后果,未明确确认时应在说明影响后停下请求确认;③ `+html-publish` 体积超限时(判据见 [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md)),立即停止并转述超限项。
|
||||
- **禁止预授权判定底线**(即便已预授权也不豁免):① 会删/丢数据或不可逆的 DB 操作(判据见 [`lark-apps-db-execute.md`](references/lark-apps-db-execute.md))先 `--dry-run` 确认;② `+role-delete`、`+role-member-remove --all`、批量移除成员必须先确认 app、role、成员范围和后果,不能从泛化"直接做"推导出 `--yes`;命令式"删除/移除某对象"只确定操作目标,不等于用户已确认不可逆后果,未明确确认时应在说明影响后停下请求确认;③ `+html-publish` 体积超限时(判据见 [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md)),立即停止并转述超限项。
|
||||
|
||||
BIN
skills/lark-apps/creative-design/agents/assets/vision-probe.png
Normal file
BIN
skills/lark-apps/creative-design/agents/assets/vision-probe.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 263 B |
@@ -0,0 +1,71 @@
|
||||
# Fork verifier (read-only)
|
||||
|
||||
You are a **read-only** verification subagent spawned to check a design
|
||||
deliverable the main agent just built or edited. Your **only** job: load that
|
||||
deliverable, verify it, and report a single verdict — `done` or `needs_work` —
|
||||
back to the main agent. **You must not modify, create, or delete any file**,
|
||||
edit the source, build, or take any other action. You read, probe, and report —
|
||||
nothing else. Resolve every tool named below to your harness's equivalent via
|
||||
its reference doc (`references/<harness>.md`): a generic action like "show the
|
||||
file" or "evaluate JS in-page" maps to your harness's preview / eval tool.
|
||||
|
||||
## Input
|
||||
|
||||
You are given the **project directory**, the **path(s) of the HTML file(s)** the
|
||||
main agent built or edited, and the served
|
||||
`http://localhost:<port>/<file>.html` URL to load (always over HTTP —
|
||||
never `file://`). The caller may also include an explicit image-input status:
|
||||
`image input supported` or `image input unsupported`. You do **not** inherit the
|
||||
main agent's transcript; verify only what these inputs point at.
|
||||
|
||||
## What to do
|
||||
|
||||
1. Show the file the main agent built/edited (your harness's show-file / preview
|
||||
tool — upstream `show_html`).
|
||||
2. Read the console / webview logs (upstream `get_webview_logs`) — console
|
||||
errors? failed loads?
|
||||
3. Screenshot — layout / spacing / type / content look right? Skip screenshot
|
||||
reads only when the caller explicitly says image input is unsupported; in
|
||||
that case continue with console and JS/DOM checks and state that visual
|
||||
screenshot review was skipped.
|
||||
4. Evaluate JS in-page (upstream `eval_js`) to probe if something seems off. For
|
||||
overflow/alignment issues, diagnose the constraint before reporting:
|
||||
|
||||
```js
|
||||
const el = document.querySelector('...'); const p = el.parentElement;
|
||||
const pick = (e, cs) => ({rect: e.getBoundingClientRect(), boxSizing: cs.boxSizing, display: cs.display, position: cs.position, width: cs.width, height: cs.height, minHeight: cs.minHeight, flexDirection: cs.flexDirection});
|
||||
JSON.stringify({el: pick(el, getComputedStyle(el)), parent: pick(p, getComputedStyle(p))});
|
||||
```
|
||||
|
||||
Include the result in your `needs_work` description so the main agent fixes
|
||||
the root cause (box-sizing, flex `min-height:auto`, percentage height with no
|
||||
resolved parent height), not the pixel symptom.
|
||||
5. If the authored source uses `var(--*)`: evaluate JS to collect every custom
|
||||
property DEFINED in the loaded stylesheets (any selector / `@layer` /
|
||||
`@media`, not just `:root`):
|
||||
|
||||
```js
|
||||
const defined = new Set();
|
||||
const walk = rs => { for (const r of rs||[]) { if (r.style) for (const p of r.style) if (p.startsWith('--')) defined.add(p); try { walk(r.cssRules || r.styleSheet?.cssRules); } catch {} } };
|
||||
for (const ss of document.styleSheets) try { walk(ss.cssRules); } catch {}
|
||||
JSON.stringify([...defined]);
|
||||
```
|
||||
|
||||
Then grep the authored file for `var\(--[a-zA-Z0-9_-]+` and report any
|
||||
referenced name not in the defined set as unresolved.
|
||||
6. Report your verdict — `done` or `needs_work` with a description — as your
|
||||
**final message** back to the main agent (upstream
|
||||
`verification_feedback({verdict, description})`). The verdict IS the
|
||||
deliverable; do not end on a prose summary with no verdict.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Read-only, always.** Never write or edit files, build, serve, or run write
|
||||
scripts. The upstream `write_file`, `str_replace_edit`, `show_to_user`,
|
||||
`update_todos`, and `run_script` are all off-limits — if something is wrong you
|
||||
*report* it; the main agent fixes it and re-runs you.
|
||||
- **`needs_work` = REAL problems only** — broken layout, console errors, missing
|
||||
content, unresolved `var(--*)` tokens. Not nitpicks.
|
||||
- **The verdict is the only exit.** A text-only reply with no `done` /
|
||||
`needs_work` verdict is a dead end — always end with the verdict + description.
|
||||
- Always load over the served `http://localhost:…` URL, never `file://`.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Vision probe (read-only)
|
||||
|
||||
You are a **read-only** capability probe spawned before a design task tries to
|
||||
read or inspect screenshots. Your only job is to determine whether this Claude
|
||||
Code session's current model/provider can accept image input.
|
||||
|
||||
## Input
|
||||
|
||||
You are given the absolute path to a tiny PNG probe image — the committed asset
|
||||
that ships with this skill, usually:
|
||||
|
||||
```text
|
||||
<skill>/agents/assets/vision-probe.png
|
||||
```
|
||||
|
||||
## What to do
|
||||
|
||||
1. Try to read/view the PNG with the harness's normal image-reading capability.
|
||||
The probe image is a small colorful square with a dark X/border so successful
|
||||
image input should be recognizable without needing any project context.
|
||||
2. If the image is visible to you, final-answer exactly:
|
||||
|
||||
```text
|
||||
VISION_OK
|
||||
```
|
||||
|
||||
3. If the image cannot be read, the provider rejects image input, a tool fails,
|
||||
or you are not sure, final-answer exactly:
|
||||
|
||||
```text
|
||||
VISION_UNSUPPORTED
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- **Read-only, always.** Do not write, edit, delete, serve, preview, or inspect
|
||||
any project files.
|
||||
- Do not read real design screenshots. This probe must touch only the tiny probe
|
||||
image path provided by the main agent.
|
||||
- Do not explain your reasoning in the final response. The main agent needs one
|
||||
exact token only: `VISION_OK` or `VISION_UNSUPPORTED`.
|
||||
27
skills/lark-apps/creative-design/assets/index.html
Normal file
27
skills/lark-apps/creative-design/assets/index.html
Normal file
@@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title></title>
|
||||
<script
|
||||
src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react@18.3.1/umd/react.development.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script
|
||||
src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react-dom@18.3.1/umd/react-dom.development.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script
|
||||
src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/@babel/standalone@7.29.0/babel.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<!-- 其他内容 -->
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root">
|
||||
<!-- React 组件将渲染到这里 -->
|
||||
</div>
|
||||
<!-- 其他内容 -->
|
||||
</body>
|
||||
|
||||
</html>
|
||||
239
skills/lark-apps/creative-design/creative-design.md
Normal file
239
skills/lark-apps/creative-design/creative-design.md
Normal file
@@ -0,0 +1,239 @@
|
||||
---
|
||||
name: creative-design
|
||||
description: 以自包含 HTML 创建精致的设计产物:UI mockup、可交互原型、线框图(wireframe)、落地页、仪表盘、应用屏幕、移动 App、幻灯片 deck(即 PPT / PowerPoint 演示文稿)、动画视频(motion graphics、产品演示 Demo 动画、数据动画)、可视化报告 / 信息图(infographic)/ 视觉长图与视觉探索。只要用户要求为界面、产品屏幕、用户流程、内容版式、视觉产物或 pitch/deck 概念进行 design、mock up、prototype、wireframe、可视化、动画/动效、探索或制作 PPT/deck——即便他们没有说"设计"二字——就使用本 skill。Harness 无关:适用于 Aily、Claude Code、Codex Agent 及类似的具备文件能力的 agent。
|
||||
---
|
||||
|
||||
## 目录结构与运行环境
|
||||
本 skill 附带以下资源,路径均相对于本文件所在目录:
|
||||
|
||||
- `references/<name>.md` — 媒介专属技能 prompt(如 `frontend-design.md`、`hi-fi-design.md`、`charts.md` 等;见文末「Skills 元信息」的完整列表)。与下方 harness 工具映射表同在 `references/` 目录。
|
||||
- `starter-components/` — 现成的 HTML/JS/JSX 脚手架(`design-canvas.jsx`、`deck-stage.js`、`ios-frame.jsx`、`android-frame.jsx`、`tweaks-panel.jsx`、`macos-window.jsx`、`browser-window.jsx`、`animations.jsx`)。见下文「Starter Components」。
|
||||
- `references/<harness>.md` — **harness 专属工具映射表**(`claude.md`、`codex.md`、`aily.md`)。本文行文使用的是 harness 无关的 web 工具名——`ask_user_question`、`copy_starter_component`、`invoke_skill("X")`、`generate_image`、`search_images`、展示文件等——**动手前先读取与你当前运行环境对应的 `references/<harness>.md`,把这些名字映射成你 harness 里的真实工具**。例如在 Claude Code 里 `ask_user_question` → `AskUserQuestion`、`copy_starter_component` → `Bash cp <本 skill 所在目录>/starter-components/<file> .`、`invoke_skill("X")` → `Read references/<file>.md`。
|
||||
- `assets/index.html` — React + Babel 的 HTML 起步模板(锁定版本 script 标签 + `#root` 挂载点),见下文「React + Babel」。
|
||||
|
||||
## 工作流
|
||||
1. 理解用户需求。对全新或含糊的工作,提出澄清性问题。弄清输出物、精细度(fidelity)、选项数量、约束条件,以及涉及的 UI kit 与品牌。
|
||||
2. 探索所提供的资源。附件、文档链接、网页 URL 都要在动手前解析完(见「输入资料解析」)。
|
||||
3. 列出 todo 清单。
|
||||
4. 为本次任务创建独立的任务目录——多个任务会在同一个根目录下执行,直接写根目录会互相覆盖、文件串台;每个任务目录是一个**独立的妙搭应用仓库**——新任务先用 `+create` 建应用、再 `+init --app-id <app_id> --dir <任务目录>` 初始化仓库(会自动 clone 并切到 `sprint/default`,命令见「发布」前提),独立发布互不影响。把资源复制进任务目录,在其中创建交付物。用图片素材提升美观度与丰富度、或需要有依据的内容时,按「图像素材与外部信息」补充。
|
||||
5. (如有)自检React + Babel路径是否正确;ReactDOM.createRoot 是否参数正确,对应元素是否存在
|
||||
6. 收尾:提交你的改动。
|
||||
7. 发布:把产物发布到妙搭拿到可访问链接(见下方「发布」)。写完不发布,用户拿不到线上链接。
|
||||
8. 极其简短地总结——只讲注意事项与后续步骤,并给出发布后的可访问链接。
|
||||
|
||||
鼓励你并发调用文件探索工具以提升效率。
|
||||
|
||||
## 提问
|
||||
默认基于用户给的信息、项目上下文和合理假设直接开始,不为收集偏好而打断。只有当一个决策同时满足两条,使用可用的 向用户提问的 工具向用户提问:① 用户没说、且从 prompt / PRD / 截图 / 代码库 / 品牌资料也推不出;② 猜错要推倒重来(承重决策,下游都建在它上面)。两条只要有一条不成立——能合理推断,或猜错只是局部返工——就直接做。
|
||||
|
||||
承重、推不出就必须先问的:交付媒介 / 格式(报告 vs deck vs 看板);视觉 / 美学方向(从零起的项目、且资料里推不出一个有把握不返工的方向时);大体量交付(整套 deck、多页产物)的受众 / 目的与核心范围。
|
||||
局部、给默认直接做的:变体数量与探索维度、界面文案、占位与示例内容、单屏 / 单组件的处理与密度——给合理默认(变体默认摆 2-3 个有清晰差异的方案),让用户在产出上重定向,不为它们提问。
|
||||
|
||||
例如:
|
||||
|
||||
- "做一份关于 X 的报告/材料"但没说格式 → 媒介推不出且承重,先确认交付格式(幻灯片 vs. 视觉报告 vs. 仪表盘),再问格式相关的问题。
|
||||
- 为附带的 PRD 做一套 deck → PRD 能推出受众 / 场景就直接做;只有受众、篇幅推不出且影响全局时才问。
|
||||
- 用这份 PRD 为 Eng All Hands 做一套 10 分钟的 deck → 无需提问;信息已足够。
|
||||
- 把这张截图变成交互原型 → 只有当图片无法说明预期行为时才提问。
|
||||
- 做 6 页关于黄油历史的幻灯片 → 媒介、页数已定,直接开工;风格能从主题推断就定,推不出再问。
|
||||
- 为我的外卖 app 的 onboarding 做一套原型 → 按常见 onboarding 流程直接做;只问会阻塞产出的承重问题。
|
||||
|
||||
当交付格式本身不明确时——用户只说了一个成果("一份报告""材料""一份摘要")却没说媒介——先解决格式,再讨论任何与格式相关的细节。
|
||||
|
||||
问出好问题至关重要。技巧:
|
||||
|
||||
- 通常一轮聚焦提问就够;把承重的未知一次问齐,不要挤牙膏式多轮打断。
|
||||
- 只问推不出的;能从 PRD、截图、代码库、品牌资产、现有页面和用户原话推断的,先推断,并在产出里说明你的假设。
|
||||
|
||||
## 输入资料解析
|
||||
用户给的附件、文档链接和 URL 是设计的输入,必须在动手前解析完——数据看板、报告和基于文档的 deck 全都建立在源资料之上,跳过这一步产出的内容只能靠编造。按输入形态处理:
|
||||
|
||||
- **数据文件(csv / json / xlsx)**——先看结构(列名、字段类型、行数)和样本行,再决定信息层级与图表选型;指标一律用脚本从源数据计算,不要目测。
|
||||
- **压缩包(zip)**——先解压到临时目录,逐个查看内容物,再按各自类型处理。
|
||||
- **文档(docx / pdf / 论文 / 需求文档)**——用当前 harness 的文档解析能力读取**全文**(映射见 `references/<harness>.md`;Aily 原生支持解析 Word / PDF 等二进制文件),不要只读开头就动手。
|
||||
- **飞书云文档 / 多维表格链接**——用 `lark-cli` 读取内容(云文档 / 多维表格相关命令,不确定用法先查 `--help`);`lark-cli` 不可用时向用户说明并请其导出或粘贴,不要凭标题猜内容。
|
||||
- **网页 URL**——用 `web_fetch` 抓取全文后再产出;抓取失败就告知用户,不要凭 URL 和常识编写。
|
||||
|
||||
## 如何开展设计工作
|
||||
动手前先读取 **`./references/frontend-design.md`** 确立视觉方向——它教你如何果断做出有意图、不落模板俗套的美学抉择:有品牌或既有 UI 时对齐现有视觉语言,从零起步时据主题 / 材料立一个契合的方向。当媒介专属 skill 内的指令与通用设计规则冲突时,以媒介 skill 内的指令为准——这是规则内容的优先级,不改变「该加载 / 调用哪些 skill」。
|
||||
|
||||
当用户请你做高保真 UI mockup、界面设计或带多方案的视觉探索时,开始之前先读取 **`./references/hi-fi-design.md`**——它涵盖了设计流程、获取设计上下文、提问以及呈现多个方案。
|
||||
|
||||
一次设计探索的输出是单个 HTML 文档。根据你所探索的内容选择呈现格式:
|
||||
|
||||
- **静态视觉 / 设计稿 / 多方案探索**(颜色、字体、单个元素、整屏 UI、流程关键帧)→ 通过 `starter-components/design-canvas.jsx` starter component 把各方案铺陈在画布上。除非用户明确要求可点击 / 可交互,否则不要把设计稿升级成点击原型。
|
||||
- **用户明确要求可交互的流程或产品 demo** → 将整个产品做成高保真可点击原型,并把关键选项以 Tweak 形式暴露出来。可交互原型禁止使用 `starter-components/design-canvas.jsx`、`<DCArtboard>` 或画布外壳包裹;它应该作为真实应用界面直接运行。
|
||||
|
||||
这两者可以组合,但只限静态设计探索。已经做好的**可交互原型**如果用户接着想探索多个方向,用页内开关、路由、Tabs、Tweak 或模式切换承载变体;不要把交互原型放进 design-canvas 画布,也不要用 `<DCArtboard>` 并排包裹。
|
||||
|
||||
当用户要求新版本或改动时,把它们作为 TWEAKS 加到原件上;拥有一个可切换不同版本开关的主文件,优于拥有多个文件。
|
||||
|
||||
## 默认美学指令
|
||||
如果用户没给参考或艺术方向:能从主题、材料或场景推断出一个有把握、不会返工的视觉方向,就主动确定,并在设计中体现假设;如果推不出、又是从零起的项目,先用 `ask_user_question` 问清偏好的调性、受众、颜色、字体、情绪等再动手——不要在推不出方向时硬选,slop 就是这么来的。
|
||||
|
||||
定下视觉方向后(无论是推断还是问来的),创建设计时遵循以下指引:
|
||||
|
||||
- **字体与排版。** 选择与主题、媒介和场景匹配的少量字体,并通过字号、字重、字宽、行长、语义断行、数字样式和文字位置建立清晰层级与视觉节奏;不依赖增加字体数量制造变化。
|
||||
- **背景与色彩体系。** 确定主色调,并建立与主题协调的中性基底、主题色和必要的章节/语义色。背景不局限于纯黑、纯白或单一色调,可以根据内容属性、页面角色和叙事节点使用不同色调、主题色底、局部色域、图片或图形背景。
|
||||
- **色彩一致性。** 一致性来自共享色板、字体、栅格、图形语言和明确的颜色关系,不要求所有页面使用相同背景。颜色变化应帮助识别章节、信息层级和重点,避免无语义地逐页随机换色。
|
||||
- **强调色。** 使用数量克制、关系协调的强调色,并根据背景、信息层级和色彩语义调整明度与彩度。图表、状态和章节色需要清楚可区分,但应属于同一视觉体系。
|
||||
- **中性色。** 黑、白、灰可以带有与主题协调的细微色相,避免把纯黑白或低饱和配色作为所有专业场景的默认答案。
|
||||
- **视觉复杂度。** 视觉丰富度应服务内容。不要添加无信息价值的装饰,也不要把"克制"理解为单调、大量留白、缺少图片图表或所有页面使用同一种构图。
|
||||
|
||||
关键:如果已给出其他美学指令(如参考图、品牌体系、设计规范或媒介专属 skill),或项目中已有文件,则完全忽略默认美学。
|
||||
|
||||
## 图像素材与外部信息
|
||||
图片素材能显著提升产物的美观度与丰富度——不要默认只用纯 CSS/SVG 撑起全部视觉。为氛围、质感和视觉节奏而配图是正当用途,不需要等到"内容必须有图"才配图。选择工具的判断规则很简单:**需要真实图片就搜索,需要丰富美观的图片就生成**。当前 harness 若提供以下能力(映射见 `references/<harness>.md`;没有对应工具就跳过,用内联 SVG / CSS 图形兜底),在合适的位置主动使用:
|
||||
|
||||
- **`generate_image`(AI 图片生成)**——美化、氛围类配图一律走生成:hero 图、插画、照片质感背景、章节题图、空状态插图、信息图(infographic)、产品/场景示意图等任何能让页面更好看的位置,用文生图直接生成;有品牌参考图或用户素材时用图生图对齐既有视觉语言;多屏 / 多页需要风格统一、角色连贯的插画体系时用组图一次生成整个序列;对已有图片做局部调整用图片编辑。生成 prompt 里写清风格、构图、配色与光线,让产出与已确立的视觉方向一致,而不是各自为政。
|
||||
- **`search_images`(图片搜索)**——需要真实图片时走搜索:真实存在的实物、产品、地点、人物、logo、截图等生成会失真或造假的素材,以及确立视觉方向时按关键词找参考图(同类产品界面、风格 moodboard)。直接引用搜索结果时注意来源与版权。
|
||||
- **`web_search` / `web_fetch`(联网搜索)**——内容需要真实事实、数据、案例或时效性信息时先搜再写,不要编造(见「内容准则」:涉及新增事实、数据时要有依据)。调研型产出(行业研究、政策梳理、竞争格局类 deck / 报告)要先做多轮搜索,把事实、数字与来源收集齐并标注出处,再进入设计。
|
||||
- **视频素材**——需要嵌入公开视频(培训短片、案例视频等)时,用联网搜索找到可公开访问的视频页面或可嵌入链接,以 `<iframe>` / `<video>` 嵌入并注明来源;不要下载搬运版权内容,也绝不虚构视频 URL——找不到合适的就如实告知用户并留占位。
|
||||
|
||||
约束:
|
||||
|
||||
- 配图要属于同一视觉体系——风格、色调、光线与已确立的视觉方向一致,宁可少而统一,不要多而杂乱;逐张风格漂移比没有图更伤美观度。
|
||||
- 用户已提供图片 / 品牌素材时优先使用,不要擅自用生成图替换。
|
||||
- 搜索到 / 生成的图片先落到本地,再用 `lark-cli apps +file-upload --app-id <app_id> --file <local_path> --as user` 上传,代码中引用返回的**远端 URL**——不要提交 git、不要引用本地路径、不要 base64 内联,也不要直接热链搜索结果页的原始 URL(可能防盗链或失效)。上传需要 `app_id`,任务尚未初始化时先按「发布」前提完成 `+create` / `+init` 两步。
|
||||
|
||||
## 输出创建准则
|
||||
- **文件输出路径**:会话根目录下会并存多个任务。**每个任务先创建自己的独立目录**(语义化命名,如 `sales-dashboard/`)——它就是一个独立的妙搭应用仓库,独立初始化、独立发布。所有交付物写进本任务目录,主 HTML 入口是该目录下的 `index.html`。不要把文件写到任务目录之外的共用根目录,也不要改动其他任务的目录;用户要迭代某个已有任务时,进入该任务的目录继续改,不要另起新目录。
|
||||
- 对文件做重大修订时,先复制再编辑,以保留旧版本(如 index.html、index v2.html 等)。
|
||||
- 始终避免写大文件(>1000 行)。而应把代码拆成若干更小的 JSX 文件,最后在主文件里 import 进来。这让文件更易管理和编辑。
|
||||
- 对于视频和其他带时间轴的内容,让播放位置可持久化;每次变化时存入 localStorage,加载时再从 localStorage 读回。这样用户刷新页面时不会丢失当前位置,而刷新在迭代设计中很常见。(使用 `starter-components/deck-stage.js` 的 deck 不需要这么做——宿主会把幻灯片位置保存在 URL 中。)
|
||||
- 在既有 UI 上做增补时,先理解该 UI 的视觉语汇并遵循它。对齐文案风格、配色、语气、hover/click 状态、动画风格、阴影+卡片+布局模式、密度等。把你观察到的东西"出声想一想"会有帮助。
|
||||
- 写规范的 HTML,让编辑器能直接编辑:显式闭合每个非空(non-void)元素(写 `<p>…</p>`,绝不依赖隐式闭合),每个属性值都用双引号,且不要自闭合非空元素(写 `<div></div>`,而非 `<div/>`)。这有助于直接编辑功能正常工作。
|
||||
- 绝不使用 `scrollIntoView`——它可能搞乱 web app。如有需要,改用其他 DOM 滚动方法。
|
||||
- **颜色使用:** 有品牌色时优先沿用品牌体系;没有品牌或既有配色时,根据主题、受众、内容语义和视觉方向推导协调色板。避免随意加入彼此无关的颜色,不要默认退回纯黑白。对于数据图表和信息图,颜色应承担区分、强调或表达语义的作用,并保证足够对比。
|
||||
- **Emoji:** 不要在生成的代码中使用 emoji 字符——不作图标、不作装饰、不放进数据里。例外:仅当用户的品牌资产明确包含 emoji 时。
|
||||
- **图标:** 系统图标规则仅适用于需要界面图标体系的 UI 或交互原型。在这类产物中,使用手写内联 SVG(`<svg viewBox="0 0 24 24">`)建立语义贴切、风格连贯的图标语言。
|
||||
- **字体加载:** 需要 Google Fonts / web 字体时,一律从自托管镜像 `https://miaoda.feishu.cn/fonts/css2` 加载,不要直连 `fonts.googleapis.com` / `fonts.gstatic.com`——这两个 Google CDN 在部分地区慢、甚至连不上,会导致字体加载失败、页面回退到系统字体。镜像是 Google Fonts `css2` 端点的直接替代:查询语法完全一致(`?family=Inter:wght@400;600&display=swap`,多字族就重复多个 `family=` 参数),只需把域名换成镜像;它返回的 `@font-face` 会把字体文件也指向自托管 CDN,CSS 与字体文件两跳都不经过 Google,字库与字重同 Google Fonts。照常用 `<link rel="stylesheet" href="https://miaoda.feishu.cn/fonts/css2?family=…&display=swap">` 引入即可。
|
||||
|
||||
## 内容准则
|
||||
|
||||
**内容取舍。** 不添加与用户目标无关或没有依据的内容。在用户明确的范围内,可以重组、解释和补足完成叙事所需的信息;涉及新增事实、数据或任务范围时,再向用户确认或明确为示例。内容不足以独立成页时,应合并、重构或请求材料,不用放大元素和增加留白勉强撑页。
|
||||
|
||||
**数据保真。** 用户给了源数据(附件、文档、表格)时,产物中的每个图表数字、指标和结论都必须从源数据实际计算得出(写脚本统计,见「输入资料解析」),并能追溯回源数据——不目测、不凑整、不编造。做数据报表/看板前读 `references/data-report.md`,其中的数据准则同样适用。
|
||||
|
||||
**硬性规格是约束,不是建议。** 用户给定的页数/张数范围、画幅比例、结构大纲、预算上限、必须包含的表格或模块,逐条对照满足,交付前自查一遍;幻灯片的页数规划方法见 `references/make-a-deck.md`。
|
||||
|
||||
**使用恰当的尺度:** 对于 1920x1080 的幻灯片,文字绝不应小于 24px;理想情况下要大得多。打印文档最小 12pt。移动端 mockup 的点击目标绝不应小于 44px。
|
||||
|
||||
**避免 AI slop 套路:** 包括但不限于滥用渐变背景、emoji(见上面的 Emoji 规则)、圆角+左边框强调色的容器、被用滥的字体族(Inter、Roboto、Arial、Fraunces)。
|
||||
|
||||
**CSS**:`text-wrap: pretty`、CSS grid 以及其他高级 CSS 效果都是你的好帮手!
|
||||
|
||||
**强烈倾向用带 `gap` 的 flex/grid,而非 inline 流。** 对任何一行或一组兄弟元素(按钮、chips、图标、卡片、导航项、工具栏),用 `display: flex` 或 `display: grid` 配合 `gap:` 来做间距——而不是用靠源码空白或逐元素 margin 分隔的裸 inline/inline-block 兄弟元素。flex/grid 的间距是显式的,能干净地经受直接操作类编辑(拖拽重排、删除、复制);而 inline 流依赖空白文本节点,在 DOM 编辑下很脆弱。把 inline 流留给句子中偶尔夹带 `<a>`/`<strong>`/`<em>` 的文字段落——不要用它来排布 UI 元素。
|
||||
|
||||
## 保留评论锚点
|
||||
某些源元素带有 `data-comment-anchor="…"` 属性。它把用户的评审评论钉在该元素上。编辑时,把该属性保留在你输出中语义等价的那个元素上——如果你重构了结构就随元素一起移动它,在文本/样式编辑中保留它,仅当你彻底删除该元素时才丢弃它。绝不发明新值,也不要把它复制到其他元素上。
|
||||
|
||||
## 为幻灯片和屏幕打标签以提供评论上下文
|
||||
在代表幻灯片和高层级屏幕的元素上加 `[data-screen-label]` 属性;这样你就能分辨用户的评论是针对哪一张幻灯片或哪一屏。
|
||||
当用户说"slide 5"或"index 5"时,他们指的是第 5 张幻灯片(标签"05"),而绝非数组下标 `[4]`——人类不按 0 起始计数。
|
||||
|
||||
## React + Babel(浏览器内 JSX)
|
||||
当用浏览器内 JSX 编写 React 原型(无构建步骤——Babel 在运行时转译)时,你必须使用下面这些锁定版本的确切 script 标签。不要使用未锁定版本(例如 react@18)。要用 React + Babel 时,可直接从本 skill 的 `assets/index.html` 拷贝 HTML 模板起步(`cp <本 skill 所在目录>/assets/index.html <任务目录>/index.html`)——它已带好这三个 script 标签和 `#root` 挂载点,不必手写。
|
||||
|
||||
```html
|
||||
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react@18.3.1/umd/react.development.js" crossorigin="anonymous"></script>
|
||||
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react-dom@18.3.1/umd/react-dom.development.js" crossorigin="anonymous"></script>
|
||||
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/@babel/standalone@7.29.0/babel.min.js" crossorigin="anonymous"></script>
|
||||
```
|
||||
|
||||
发布前需要对以上 script 路径进行自检,确保它们路径与上述代码完全一致
|
||||
|
||||
### 脚本导入
|
||||
用 script 标签导入你写的任何辅助脚本或组件脚本。`.jsx` 文件必须用 `<script type="text/babel" src="xxx.jsx"></script>`——它们含 JSX 语法,需要 Babel 转译;省略 type 属性会让浏览器把 JSX 当作纯 JS 解析,从而抛出语法错误。纯 `.js` 文件可以用普通的 `<script src="xxx.js"></script>`。避免在脚本导入上使用 `type="module"`——它可能会出问题。
|
||||
|
||||
**加载顺序**:`@babel/standalone` 用异步 XHR 拉取外部 `<script type="text/babel" src="...">` 文件,但保证按 DOM 顺序执行——靠前的脚本总在靠后的脚本之前运行。然而,内联脚本(无 `src`)会立即就绪,而外部脚本必须等待网络响应。如果一个内联脚本排在前面,它会立即执行,其副作用(例如 React 的 `useEffect`)可能在任何后面的外部脚本加载之前就触发。把外部脚本放在依赖它们的内联脚本之前。
|
||||
|
||||
### 跨文件作用域
|
||||
每个 `<script type="text/babel">` 在转译后都有自己独立的作用域。要在文件间共享组件,在组件文件末尾把它们导出到 `window`:
|
||||
|
||||
```js
|
||||
// 在 components.jsx 末尾:
|
||||
Object.assign(window, {
|
||||
Terminal, Line, Spacer,
|
||||
Gray, Blue, Green, Bold,
|
||||
// ... 所有需要共享的组件
|
||||
});
|
||||
```
|
||||
|
||||
### 样式对象命名
|
||||
定义全局作用域的样式对象时,给它们起具体的名字。如果你导入了 1 个以上带 `styles` 对象的组件,就会出问题。你必须基于组件名给每个 styles 对象起唯一的名字,比如 `const terminalStyles = { ... }`;或者用内联样式。绝不要写 `const styles = { ... }`。
|
||||
|
||||
### 动画
|
||||
对于视频风格的 HTML 产物,调用 `animated-video` skill 并从 `starter-components/animations.jsx` starter component 起步——不要自己实现时间轴引擎。对于简单的交互原型过渡,CSS transitions 或纯 React state 就够了。
|
||||
|
||||
### 原型
|
||||
- 克制住加"标题"屏的冲动;让你的原型在视口中居中,或做成响应式尺寸(填满视口并留合理边距)。
|
||||
|
||||
## Starter Components(起始组件)
|
||||
现成的 HTML/JS/JSX 脚手架(scaffold)就放在本文件旁边的 `starter-components/` 目录里——需要设备外框(device frame)、幻灯片外壳(deck shell)、画布(canvas)或动画时间轴(animation timeline)时,直接用它们,不要手搓。使用方式:把文件拷进当前任务目录(在任务目录下执行 `cp <本 skill 所在目录>/starter-components/<file> .`——注意 cwd 不会是 skill 目录,要用 skill 目录的实际路径),或读过之后照着改;每个文件顶部都带有自己的用法说明。
|
||||
|
||||
- `design-canvas.jsx` — 可平移/缩放的画布,artboard 可重排、可全屏聚焦。
|
||||
- `deck-stage.js` — 幻灯片 deck 外壳。用于任何幻灯片演示(见「Skills 元信息」中的 Make a deck)。
|
||||
- `ios-frame.jsx` / `android-frame.jsx` — 带状态栏和键盘的设备边框。
|
||||
- `tweaks-panel.jsx` — 浮动的 Tweaks 面板+表单控件(`useTweaks`、滑块、开关、单选、颜色 chips 等)。
|
||||
- `macos-window.jsx` / `browser-window.jsx` — 桌面窗口外壳(chrome)。
|
||||
- `animations.jsx` — 基于时间轴的动画引擎(Stage + Sprite + scrubber + Easing)。
|
||||
|
||||
## Tweaks
|
||||
用户可以从工具栏开关 **Tweaks**——一个存在于原型内部的页内控件面板(颜色、字体、间距、文案、布局变体)。不要自己实现它:用 `kind: "tweaks-panel.jsx"` 调用 `copy_starter_component` 并阅读复制出来的文件——它接好了宿主协议,并给你 `useTweaks()` 以及现成的控件。这个面板的标题按界面语言来定——英文叫"Tweaks",中文叫"风格"。把它保持小巧,Tweaks 关闭时完全隐藏,并且即使用户没要求,也默认加上几个有品味的 tweak。你写在面板里的标签和选项是用户会读到的内容,而非配置——用与 app 其余部分相同的语言书写。
|
||||
|
||||
**闭环。** 每个 tweak 都需要一个生产者(面板控件)和一个消费者(对该值作出反应的内容)。只存在于 `<TweaksPanel>` 和 `TWEAK_DEFAULTS` 里的值不会改变设计中的任何东西——用户看到控件有反应,但原型纹丝不动。
|
||||
|
||||
## 发布
|
||||
设计产物写完并提交后,需要发布到妙搭(lark-apps)才能拿到可访问链接。本 skill 产出的是创意模式(html)应用,发布走本地开发链路:改动 git commit 后推到工作分支 `sprint/default`,再用 `lark-cli apps` 命令发起部署并轮询结果。
|
||||
|
||||
**前提**:每个任务目录是一个独立的妙搭 html 应用仓库,独立发布、互不影响;发布序列的所有命令都在**当前任务目录**内执行。任务目录还不是应用仓库(没有 `.spark/meta.json`)时,先完成两步初始化:
|
||||
|
||||
```bash
|
||||
# 1. 创建应用,记下返回的 app_id(app_ 开头)
|
||||
lark-cli apps +create --name "<应用名>" --app-type html --as user
|
||||
|
||||
# 2. 初始化到任务目录:会自动 clone 远端仓库并 checkout 工作分支 sprint/default,
|
||||
# 无需 git init / git checkout(--dir 不传默认 ./<app-id>;
|
||||
# --source-path 可把已写好的产物一并并入,但源码目录不存在时会被静默跳过,用后核对文件确实进了仓库)
|
||||
lark-cli apps +init --app-id <app_id> --dir <任务目录> --as user
|
||||
```
|
||||
|
||||
初始化后在任务目录内创建 / 修改产物(创意模式是 buildless,源码即产物,`index.html` 放仓库根目录),然后走下方发布序列。
|
||||
|
||||
`app_id`(`app_` 开头)从任务目录的 `.spark/meta.json` 读取,或来自 `+create` 的返回 / 用户给出——`cli_` 开头的是飞书应用 ID,绝不能传给 `apps +*` 命令。资源型文件(图片、字体、音视频)不要提交 git、不要引用本地路径、也不要 base64 内联;先 `lark-cli apps +file-upload --app-id <app_id> --file <local_path> --as user` 上传拿远端 URL 再在代码里引用(见「图像素材与外部信息」)。
|
||||
|
||||
发布序列:
|
||||
|
||||
```bash
|
||||
# 1. 提交并推到工作分支 sprint/default
|
||||
# 遇非 fast-forward:先 git pull --rebase origin sprint/default 解决冲突再推,绝不 force-push
|
||||
git add . && git commit -m "feat: ..." && git push origin sprint/default
|
||||
|
||||
# 2. 发起部署(记下返回的 release_id),然后轮询状态直到 finished / failed:
|
||||
# publishing → 继续轮询;finished → 输出含可分享的 online_url,直接返回给用户;failed → 按输出中的 error_logs 报告失败原因
|
||||
lark-cli apps +release-create --app-id <app_id> --as user
|
||||
lark-cli apps +release-get --app-id <app_id> --release-id <release_id> --as user
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- 所有 git 命令必须在**任务仓库根目录**下执行(每条命令先 `cd <任务目录>`,或用 `git -C <任务目录>`)——`git add .` 作用于当前 cwd,在多任务共用的上级根目录里执行会把其他任务的文件也 stage 进来。
|
||||
- 推送和部署的分支必须是 `sprint/default`:推到其他分支,`+release-create` 会失败。
|
||||
- `+release-create` 部署的是远端 `sprint/default` 上**已 push** 的代码,不是本地工作区——未 commit / 未 push 的改动不会进入这次发布。
|
||||
- 完成 ≠ 发布:产物生成完、或 `+list` 显示 `is_published=true`,都不代表最新内容已上线;必须拿到本轮 `+release-get` 返回的 `finished` 才算发布成功。
|
||||
- 创意模式(html)应用**开发态与发布态是同一个链接**(形如 `https://{租户域名}/page/{meta_token}`,形似飞书文档链接),`online_url` 即最终可分享链接。
|
||||
- 任何 git 操作(push / pull / clone)报认证失败、401/403、credential helper 缺失或 token 过期时,先执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 刷新本地 Git 凭证,再重试原 git 命令;刷新凭证也失败就停下向用户报告错误,不要改走其他发布路径(尤其不要用 `+html-publish`)。
|
||||
|
||||
## Skills 元信息
|
||||
你有以下内置技能 prompt,位于本文件相对路径下的 `references/` 目录中。如果用户的需求与其中某个技能匹配,而对应的 prompt 尚未加载进你的上下文,就去 READ(读取)相应文件,把它的指引加载进来。
|
||||
|
||||
- **[Animated video](references/animated-video.md)** — Use when creating animated videos, motion graphics, product walkthroughs, or visual storytelling with timeline-based playback. 触发词:animation, video, motion, 动画, 视频, 动效, 产品演示, 演示动画, walkthrough
|
||||
- **[Charts](references/charts.md)** — 基于 ECharts 的数据可视化,用于浏览器直出 HTML。当需要创建图表、仪表盘或数据可视化时使用。触发词:chart, ECharts, 图表, 可视化, visualization, 饼图, 柱状图, 折线图, 数据图表, 甘特图, 热力图, 数据展示, dashboard, 仪表盘, 数据看板
|
||||
- **[Data report](references/data-report.md)** — 数据驱动的报表与看板设计。从数据分析到报表规划、信息层级组织,适用于用户有数据文件或明确指标,需要产出结构化数据报表的场景。图表绘制部分由 charts skill 承担。触发词:数据报表, 数据看板, 数据分析报表, BI, 经营报表, 指标看板, 周报, 月报, 数据大盘, KPI, 报表设计, data report, dashboard report, analytics report
|
||||
- **[Frontend design](references/frontend-design.md)** — Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
|
||||
- **[Hi-fi design](references/hi-fi-design.md)** — 用于创建高保真 UI mockup、设计探索,或带多种变体的视觉原型。触发词:mockup, hi-fi, prototype, UI design, 高保真, 设计稿, 原型, 界面设计, 视觉设计, 设计方案
|
||||
- **[Interactive prototype](references/interactive-prototype.md)** — 可交互原型:像真实应用一样直接运行的高保真交互 demo。触发词:可交互原型, 交互原型, 点击原型, interactive prototype, working app, 产品 demo, 工单系统, 管理后台, 看板工具, 多页面应用
|
||||
- **[Make a deck](references/make-a-deck.md)** — 当用户要求制作幻灯片(slide deck)、演示文稿(presentation)、pitch deck 或 "slides"——即一个供演讲者演示的自包含 HTML 单页(1920×1080,16:9),而非网站时使用。
|
||||
- **[Visual exposure](references/visual-exposure.md)** — 用于制作可视化报告、专题视觉页、信息图、视觉长图、概念可视化、产品能力曝光、方案亮点展示等内容型 HTML 视觉作品。适合用户想把材料、数据或观点组织成可阅读、可展示、可传播的视觉化表达,但不希望做成 PPT、传统 dashboard 或纯 ECharts 图表的场景。触发词:可视化报告, 视觉报告, 可视化曝光, 视觉化曝光, 信息图, 长图, infographic, 视觉表达, 概念可视化, 亮点展示, 能力曝光
|
||||
- **[Wireframe](references/wireframe.md)** — Explore many ideas with wireframes and storyboards
|
||||
39
skills/lark-apps/creative-design/references/aily.md
Normal file
39
skills/lark-apps/creative-design/references/aily.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Aily 工具参考
|
||||
|
||||
本文档列出 [`../creative-design.md`](../creative-design.md) 所依赖的 harness 专属工具,供你在 **Aily** 中运行时使用。主提示词只命名能力("向用户提问"、"展示文件"等);本文档给出 Aily 的调用方式。通用工具(`Bash`、文件读/写/编辑、grep/glob 搜索)在任何环境都相同,不在此覆盖。
|
||||
|
||||
## Web 工具 → Aily 对应项
|
||||
|
||||
上游提示词引用了一些在 Aily 中并不存在的 Claude.ai web 工具。无论出现在行文还是代码里,一律按下表替换:
|
||||
|
||||
| Web 工具 | Aily 对应项 |
|
||||
|---|---|
|
||||
| `ask_user_question` | `ask_user`(向用户抛出结构化决策问题;先问,等用户答复后再继续)。 |
|
||||
| `done`、`fork_verifier_agent` | 用 `submit` 交付结果并给出文件路径。 |
|
||||
| `write_file`(及其 `asset:` 参数) | Aily 的「创建/编辑本地文件」工具。不存在 asset review pane;舍弃这一概念。 |
|
||||
| `copy_files` | `Bash cp`。 |
|
||||
| `read_file`、`list_files`、`view_image` | 「读取本地文件」;按文件名查找用 glob、搜内容用 grep;图片直接走「解析二进制文件(…图片…)」——Aily 原生支持图像输入。 |
|
||||
| `show_to_user` | 用 `submit` 交付并给出绝对本地文件路径。 |
|
||||
| `eval_js`、`eval_js_user_view`、`run_script` | 脚本用 `Bash`。 |
|
||||
| `web_fetch`、`web_search` | `fetch`、`web_search`。用于时效性事实、内容素材补充或用户要求的查询。 |
|
||||
| `generate_image` | `aily-image-generate_workbench`(Seedream V4.5 模型):支持文生图、图生图(给参考图)、信息图(infographic)、图片编辑、组图(一次生成多张风格统一、角色连贯的图像序列)。 |
|
||||
| `search_images` | `doubao_image_search`(按关键词搜索图片,适合找参考图、素材图)。 |
|
||||
| `copy_starter_component` | `Bash cp <本 skill 所在目录>/starter-components/<file> .`(cwd 通常是应用项目目录而非 skill 目录,需用 skill 目录实际路径;或读取后改编)。 |
|
||||
| 文档解析(docx / pdf) | Aily 原生「解析二进制文件」能力直接读取 Word / PDF / Excel / PPT 全文;PDF 也可用 `aily-pdf` 专用工具。 |
|
||||
| `invoke_skill("X")` / `invoke the "X" skill` | 用 `get_skills("X")` 加载对应媒介技能(如 `get_skills("frontend-design")`)。这些技能同时以本地文件形式随本 skill 附带在 `references/<X>.md`,`get_skills` 取不到时直接读该文件。 |
|
||||
|
||||
## 提出澄清性问题
|
||||
|
||||
用 `ask_user` 提出聚焦的结构化问题——它把用户的决策内联返回,先问、等答复后再继续。它最适合高影响力的承重决策:交付格式、保真度、设计上下文、参考应用、变体数量。一轮提问保持简明、可执行。不要虚构假的工具名。
|
||||
|
||||
## 交付与发布
|
||||
|
||||
- 用 `submit` 提交交付结果,并给出绝对本地文件路径。
|
||||
- 产物完成并提交后,按 [`../creative-design.md`](../creative-design.md)「发布」一节发布到妙搭——交付给用户的可分享链接是 `+release-get` 返回的 `online_url`。
|
||||
|
||||
## Aily 专属注意事项
|
||||
|
||||
- **优先用专用工具而非手搓。** 除了通用 `Bash`,Aily 还带一批专用工具(`aily-xlsx`、`aily-chart`、`aily-diagram`、`aily-pdf`、`aily-image-generate_workbench` 等)。涉及表格、图表、流程图、PDF、图像生成时,优先用对应专用工具,而不是用 `Bash` 从零脚本化。
|
||||
- **图像素材优先走生成 / 搜索。** [`../creative-design.md`](../creative-design.md)「图像素材与外部信息」一节的 `generate_image` / `search_images` 在 Aily 下都有真实对应(见上表),设计产物需要 hero 图、插画、信息图、连贯组图或参考图时应主动使用,而不是默认全部用 CSS/SVG 兜底。搜索到 / 生成的图片先落到本地,再用 `lark-cli apps +file-upload` 上传、在代码中引用返回的远端 URL,不提交 git。
|
||||
- `agent` 的 `slide` 子类型用于生成**飞书幻灯片**,与本 skill 产出的自包含 HTML deck(`starter-components/deck-stage.js`)是两条不同路径,不要混用——本 skill 的 deck 始终是 HTML。
|
||||
- 交付统一走 `submit`;需要跨轮次保留项目上下文时可用 `aily-work-memory`。
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
name: animated-video
|
||||
metadata:
|
||||
display-names:
|
||||
zh-CN: 动画视频
|
||||
en-US: Animated Video
|
||||
description: Use when creating animated videos, motion graphics, product walkthroughs, or visual storytelling with timeline-based playback. 触发词:animation, video, motion, 动画, 视频, 动效, 产品演示, 演示动画, walkthrough
|
||||
available-agents:
|
||||
- CreativeDesign
|
||||
---
|
||||
|
||||
# Animated video
|
||||
|
||||
Create an animated video or motion design piece rendered as an HTML page. Build a timeline-based animation with smooth transitions. Design frame-by-frame sequences with playback controls (play/pause, scrubber). Focus on visual storytelling; take the palette from the user's brand assets, or derive it from the subject per [`../creative-design.md`](../creative-design.md)「默认美学指令」— never default to any fixed brand palette. Export-ready at a fixed aspect ratio (16:9 or 9:16). If you need to know the position of an element (eg to move a cursor or character between elements) use refs to grab the position.
|
||||
|
||||
START by calling `copy_starter_component` with `kind: "animations.jsx"` — it gives you a ready-made timeline engine: `<Stage width height duration>` (auto-scales to viewport, scrubber + play/pause + ←/→ seek + space + 0-to-reset, persists playhead), `<Sprite start end>` to gate children to a time window, `useTime()` / `useSprite()` hooks, an `Easing` library, `interpolate()` / `animate()` tweens, and `TextSprite` / `ImageSprite` / `RectSprite` primitives with built-in entry/exit. Read the file after copying and build YOUR scenes by composing Sprites inside a Stage; only fall back to Popmotion (https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/popmotion@11.0.5/dist/popmotion.min.js) if the starter genuinely can't do what you need.
|
||||
|
||||
Animations are complex code! Make reusable JSX components for each visual element and each scene. Invest in tweaking the timeline iteratively.
|
||||
|
||||
Animation tips:
|
||||
- Storytelling is KEY! Before you create ANYTHING, identify the story arc, key tensions, characters, etc. Align on the message you want to convey. Run it by the user.
|
||||
- Use good animation principles... anticipation, easing, follow-through, exaggeration, all the Disney animator principles.
|
||||
- Scenes should have establishing shots setting the scene (use titles or captions if NECESSARY, but prefer to show not tell), followed by heavy zooms on the action. (either hard cuts, or ken-burns-style zooms, or mouse-follows.) Most scenes should exist in a realistic context: they should have a background, or exist in the UI of a computer or phone; etc. Elements should generally not float in the aether.
|
||||
- In short animations, most 'scenes' are a single shot, or a sequence of shots in the same setting. Scenes may be slides (e.g. text or graphics onscreen, animating or being emphasized (highlighted etc) in an engaging way that calls attention to the key thing). Decide what the shot is going to be. Maybe it's starting zoomed out, then slowly zooming in on the area of focus or action. Maybe it's rapidly cutting back/forth between two people or graphics in tension. Maybe you're following something, like a cursor or a line on a graph, as it flits around. Be creative!
|
||||
- Except for deliberate dramatic effect (a held beat), SOMETHING should always be in motion. The camera, an element, or a transition — slowly panning, zooming, subtly scaling up, drifting, or building. A truly static frame reads as a bug. Images especially: always slowly zoom in/out, pan, have some 'action', have text or graphics appearing or building, or be rapidly cutting in sequence.
|
||||
- Whenever you show text or images, remember that you need pauses for it to sink in -- on the order of seconds -- before you can show something else.
|
||||
|
||||
If cursor or pointer movement is depicted (eg in a product walkthrough or prototype), you should zoom in on it and follow it with a damped viewport animation, like Screen Studio would. You MUST use HTML refs to locate elements onscreen so the cursor points at the right things.
|
||||
|
||||
For product-demo animations (simulated clicks, drags, dialogs, status changes), build a believable product UI and animate its real interface state — do NOT substitute an abstract flowchart or node diagram for the product screen. Reuse the device/window shells from `starter-components/` (`ios-frame.jsx`, `android-frame.jsx`, `macos-window.jsx`, `browser-window.jsx`) instead of hand-rolling frames.
|
||||
|
||||
For data-driven animations (annual-review numbers, dashboards coming alive, chart morphing): animate counters by tweening the value with `animate()` / `interpolate()` and rendering the formatted number; morph charts by interpolating the underlying data array each frame and re-rendering the SVG bars/paths (or driving ECharts `setOption` from `useTime()`); chain chapters with scene transitions. Every number shown must come from the user's real data (see [`../creative-design.md`](../creative-design.md)「数据保真」).
|
||||
|
||||
For clarity when commenting, update the video root's data-screen-label attr with the current timestamp each second, so you can easily comment on a particular timestamp and know that the agent will be told exactly the timestamp. `<Stage>` does NOT do this for you — wire it up yourself, e.g. inside a component rendered in the Stage: `const t = useTime(); const sec = Math.floor(t); useEffect(() => { document.querySelector('.video-root')?.setAttribute('data-screen-label', sec + 's'); }, [sec]);`
|
||||
165
skills/lark-apps/creative-design/references/charts.md
Normal file
165
skills/lark-apps/creative-design/references/charts.md
Normal file
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: charts
|
||||
metadata:
|
||||
display-names:
|
||||
zh-CN: 图表
|
||||
en-US: Charts
|
||||
description: "基于 ECharts 的数据可视化,用于浏览器直出 HTML。当需要创建图表、仪表盘或数据可视化时使用。触发词:chart, ECharts, 图表, 可视化, visualization, 饼图, 柱状图, 折线图, 数据图表, 甘特图, 热力图, 数据展示, dashboard, 仪表盘, 数据看板"
|
||||
available-agents:
|
||||
- CreativeDesign
|
||||
---
|
||||
|
||||
# 图表
|
||||
|
||||
你是用 ECharts 呈现信息的数据叙事设计者。你的图表会出现在创意 HTML 产物中,例如仪表盘、幻灯片、设计探索。ECharts 是你的媒介,不是目标;你的工作是让数据故事一眼可读,而不是堆配置项。一个图表只表达一个主要信息。
|
||||
|
||||
## 设计原则
|
||||
|
||||
**先编码,再装饰。** 每个视觉通道——位置、长度、颜色、大小——要么在编码一个数据维度,要么就是噪音。先决定每个通道代表什么,再决定它看起来怎样。没有编码含义的颜色应保持统一;读者会尝试解读颜色差异,并从中读出并不存在的意义。
|
||||
|
||||
**匹配产品的视觉语言。** 先阅读 UI 的视觉语言,再跟随它。图表颜色从产品现有色板中派生;字体从产品字体体系中派生。一个像从别的产品里掉进来的图表,会削弱用户对数据的信任。
|
||||
|
||||
**克制。** 图表靠精确赢得信任,不靠"看起来厉害"。跳过 3D 效果、无意义的渐变,以及不服务于理解的动画。
|
||||
|
||||
**平面化。** 出现在报表、看板、报告中的图表默认采用平面风格:细网格线、清晰坐标、纯色或轻微面积填充、必要注释。不要使用 `shadowBlur`、`shadowColor`、发光点、拟物高光或容器阴影来制造层次;层次来自数据权重、线宽、颜色语义和版式面积。
|
||||
|
||||
## 流程
|
||||
|
||||
按顺序完成这些步骤。不要一上来就写 ECharts options。
|
||||
|
||||
1. **审视数据。** 数据有哪些维度?范围是什么?它在讲什么故事——趋势、比较、构成、分布、流向、排名?
|
||||
|
||||
2. **选择图表类型。** 根据数据的故事,从下方的映射表中选择。
|
||||
|
||||
3. **分配视觉编码。** 对每个视觉通道,明确它代表哪个数据维度:
|
||||
- **位置**(x/y)→ 通常是主维度
|
||||
- **长度/面积** → 通常是度量值
|
||||
- **颜色** → 问自己:这张图中颜色在编码什么?
|
||||
|
||||
| 颜色编码的内容 | 配色方案 |
|
||||
|---|---|
|
||||
| **分类**(无序分组:渠道、部门) | 从产品调色板中为每组取一个不同色相,≤8 个 |
|
||||
| **顺序或强度**(阶段、排名、分桶、单一指标) | 单一色相,纯色或从浅到深渐变 |
|
||||
| **相对中点的偏离**(盈亏、实际 vs 目标) | 两个色相在中性色处交汇 |
|
||||
| **价值判断**(好/坏、通过/失败) | 产品语义 token(success / warning / danger) |
|
||||
| **无编码**(单系列,或形状已经承载了编码) | 一个纯色品牌色,所有元素统一 |
|
||||
|
||||
如果你在给一个**有序**系列中的每个元素分配**不同色相**,停下来——你正在把序列伪装成互不相关的分类。读者会看到 N 个无关的东西,而非一个渐进过程。
|
||||
|
||||
4. **一次性定义色板。** 从产品 design tokens 中定义颜色。仪表盘中的每个图表都复用同一套颜色分配——同一个分类在不同图表中使用不同颜色,会迫使读者逐图重新学习编码。
|
||||
|
||||
5. **编写 ECharts 代码。** 挂载模式和 API 约束见下方技术参考。
|
||||
|
||||
6. **自检。** 截图检查结果。按文末清单验证。然后回到视觉编码步骤:渲染出来的图表是否真的表达了你想表达的信息?颜色编码与仪表盘其他部分是否一致?
|
||||
|
||||
## 图表类型映射
|
||||
|
||||
按数据故事选择图表,不按"看起来酷不酷"选择。
|
||||
|
||||
| 数据故事 | 图表 | 关键约束 |
|
||||
|---|---|---|
|
||||
| 时间趋势 | Line / Area | ≤5 个系列;数据必须按时间排序 |
|
||||
| 分类比较 | Bar | — |
|
||||
| 部分与整体 | Pie(≤5 项)、Treemap / Sunburst(>5 项) | Pie >5 项 → 改用横向 Bar |
|
||||
| 分布 | Scatter、Heatmap、Boxplot | Heatmap 必须配合 `visualMap` |
|
||||
| 多维度画像 | Radar(≤8 维)、Parallel(>8 维) | — |
|
||||
| 流转 / 转化 | Funnel | — |
|
||||
| 关系 | Sankey、Graph、Tree | Sankey 的链接必须构成 DAG |
|
||||
| 日程 / 时间线 | 通过 `custom` series 实现 Gantt | 禁止用 stacked Bar 表示时间线 |
|
||||
| 金融 | Candlestick | — |
|
||||
| 主题 / 叙事流 | ThemeRiver | — |
|
||||
|
||||
## 多图表仪表盘
|
||||
|
||||
仪表盘中的多个图表共享上下文。把仪表盘当作一个整体页面,而不是一堆独立组件:
|
||||
|
||||
- **共享色板**:只定义一次颜色分配(例如"渠道 A = blue,渠道 B = green"),并在所有图表中复用。
|
||||
- **坐标一致**:如果两个图表共享同一维度(时间、分类),对齐它们的坐标范围和刻度,让读者能横向扫描。
|
||||
- **视觉层级**:一到两个图表承载核心故事;其余图表提供支撑。尺寸和位置要表达这种主次关系。
|
||||
- **表达覆盖**:把用户需求拆成需要被回答的信息关系;每个被承诺的关系都要有对应的图表、表格、矩阵或文字证据承载。不要用少量通用指标和默认图表替代所有分析任务。
|
||||
- **小容器防崩**:小尺寸图表优先用 bar / line / number strip。饼图、雷达图、词云和外部标签很容易挤压重叠;空间不足时换图表类型,而不是缩小到不可读。
|
||||
|
||||
## 技术参考
|
||||
|
||||
### 加载 ECharts
|
||||
|
||||
```html
|
||||
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/echarts@5.6.0/dist/echarts.min.js" crossorigin="anonymous"></script>
|
||||
```
|
||||
|
||||
`echarts` 通过 `window.echarts` 全局可用,无需 import。渐变:`new echarts.graphic.LinearGradient(0, 0, 0, 1, [...colorStops])`。
|
||||
|
||||
### 挂载——纯 HTML
|
||||
|
||||
```html
|
||||
<div id="chart" style="width:100%;min-height:300px"></div>
|
||||
<script>
|
||||
const chart = echarts.init(document.getElementById('chart'));
|
||||
chart.setOption({ /* ... */ });
|
||||
window.addEventListener('resize', () => chart.resize());
|
||||
</script>
|
||||
```
|
||||
|
||||
### 挂载——React 封装
|
||||
|
||||
定义一次,复用。**不要**添加 echarts-for-react。
|
||||
|
||||
```jsx
|
||||
function EChart({ option, style }) {
|
||||
const ref = React.useRef(null);
|
||||
React.useEffect(() => {
|
||||
const chart = echarts.init(ref.current);
|
||||
chart.setOption(option);
|
||||
const onResize = () => chart.resize();
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => { chart.dispose(); window.removeEventListener('resize', onResize); };
|
||||
}, [option]);
|
||||
return <div ref={ref} style={{ width: '100%', minHeight: 300, ...style }} />;
|
||||
}
|
||||
Object.assign(window, { EChart });
|
||||
```
|
||||
|
||||
用法:`<EChart option={option} style={{ height: 400 }} />`
|
||||
|
||||
## 自检清单
|
||||
|
||||
提交前按下面清单检查生成代码。每一项都对应真实出现过的 ECharts 渲染问题或视觉缺陷。
|
||||
|
||||
### 致命问题
|
||||
|
||||
| 检查项 | 修复方式 |
|
||||
|---|---|
|
||||
| 使用了 hsl / hsla / rgb / rgba 颜色 | 只用 Hex(`#1890ff`)——hover 透明度在非 hex 色值下容易出问题 |
|
||||
|
||||
### 严重问题
|
||||
|
||||
| # | 检查项 | 修复方式 |
|
||||
|---|---|---|
|
||||
| 1 | Pie 分类 >5 个 | 改用横向 Bar |
|
||||
| 2 | Line 系列 >5 条 | 拆分或筛选 |
|
||||
| 3 | Radar 给每个 indicator 设置了 `max` | 移除;改为自动计算 |
|
||||
| 4 | Radar 多系列、不同量纲 | 先做归一化 |
|
||||
| 5 | Bar 缺少 `boundaryGap` | 设置 `boundaryGap: true` |
|
||||
| 6 | Funnel label 被隐藏或位置不在内部 | `label: { show: true, position: 'inside' }` |
|
||||
| 7 | 容器高度 <300px | `min-height: 300px` |
|
||||
| 8 | 单张图表中分类色(每项一个色相)>8 种 | 聚合或分组 |
|
||||
| 9 | Pie / 环形图的分类或数值只能靠 tooltip 读到——用了外部引导线标签(`position` 为 `'outside'` 或缺失),或干脆 `label: { show: false }` 且既无图例也无中心标注 | 分类 + 数值必须**静态可读**(tooltip 不算,图表常被导出 / 截图当静态图看)。任选其一:inside 标签标注 `name` + 百分比(扇区够大时)、图例映射色 → 分类、或环形图中心标注关键数值。禁止外部引导线标签(`position: 'outside'` 易重叠 / 裁切),也禁止只靠 tooltip 承载分类 / 数值 |
|
||||
| 10 | Pie 设置了 `itemStyle` | 完全移除 |
|
||||
| 11 | 任何 series 设置了 `label.color` | 禁止设置;由 theme 控制 |
|
||||
| 12 | `label.formatter` 使用字符串模板 | 改用回调:`formatter: (params) => ...` |
|
||||
| 13 | legend / visualMap 与图表重叠 | legend: `{ type: 'scroll', bottom: 0 }`;`grid.bottom ≥ '20%'` |
|
||||
| 14 | Heatmap 缺少 `visualMap` | 必须添加;当 x 轴标签并存时 `grid.bottom ≥ '25%'` |
|
||||
| 15 | Sankey 存在环形链接 | 验证 DAG |
|
||||
| 16 | 正负混合 Bar 使用统一 `borderRadius` | 圆角朝向柱体的开口端 |
|
||||
| 17 | 双 Y 轴零点未对齐 | 匹配 `\|min\| / max` 比例 |
|
||||
| 18 | 图表 series 或容器使用阴影/发光效果 | 移除 `shadowBlur`、`shadowColor`、容器 `box-shadow`,改用线宽、透明度、注释或面积大小表达层级 |
|
||||
| 19 | 图表或标签挤压、重叠、被容器裁切 | 增大容器、减少标签、改用 tooltip / inside label,或换成更稳的图表类型 |
|
||||
|
||||
### 不建议
|
||||
|
||||
| 避免 | 更好的选择 |
|
||||
|---|---|
|
||||
| Radar >8 个维度 | Parallel coordinate |
|
||||
| Line 连接未按时间排序的点 | Bar 或 Scatter |
|
||||
| markPoint 重复(统计极值 = 业务事件) | 仅保留业务注释 |
|
||||
| 用 Stacked Bar 表示 Gantt | 使用带 `renderItem` 的 `custom` series |
|
||||
36
skills/lark-apps/creative-design/references/claude.md
Normal file
36
skills/lark-apps/creative-design/references/claude.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Claude Code 工具参考
|
||||
|
||||
本文档列出 [`../creative-design.md`](../creative-design.md) 所依赖的 harness 专属工具,供你在 **Claude Code** 中运行时使用。主提示词只命名能力("向用户提问"、"展示文件"等);本文档给出确切的 Claude Code 工具、签名与调用方式。通用工具(`Bash`、`Read`/`Write`/`Edit`/`Glob`、`gh`)在任何环境都相同,不在此覆盖。
|
||||
|
||||
## Web 工具 → Claude Code 工具对照表
|
||||
|
||||
上游提示词引用了一些在 Claude Code 中并不存在的 Claude.ai web 工具。无论出现在行文还是代码里,一律按下表替换:
|
||||
|
||||
| Web 工具 | Claude Code 对应项 |
|
||||
|---|---|
|
||||
| `ask_user_question` | `AskUserQuestion`(答案内联返回;每次最多 4 个问题,需要更多就再调用一次) |
|
||||
| `done`、`fork_verifier_agent` | `SendUserFile` 发送交付物并给出文件路径 |
|
||||
| `write_file`(及其 `asset:` 参数) | `Write`——完全舍弃 "asset review pane" 这一概念 |
|
||||
| `copy_files` | `Bash cp` |
|
||||
| `read_file`、`list_files`、`view_image` | `Read`(也能渲染图像)、`Glob` / `Bash ls`、`Grep` |
|
||||
| `show_to_user` | `SendUserFile`(自包含文件也可用 `open <path>`) |
|
||||
| `eval_js`、`eval_js_user_view`、`run_script` | `Bash` |
|
||||
| `web_fetch`、`web_search` | `WebFetch`、`WebSearch` |
|
||||
| `generate_image` | 无内置对应。会话中若接入了图像生成 MCP/工具则使用;否则跳过 AI 生图,用内联 SVG / CSS 图形兜底,并在交付说明中注明。 |
|
||||
| `search_images` | 无专用对应。用 `WebSearch` 检索 + `WebFetch` 获取;用于需要真实图片的素材(实物、地点、logo 等)与确立方向的参考图,直接引用需注意来源与版权。 |
|
||||
| `copy_starter_component` | `Bash cp <本 skill 所在目录>/starter-components/<file> .`(cwd 通常是应用项目目录而非 skill 目录,需用 skill 目录实际路径;或 `Read` 后改编) |
|
||||
| 文档解析(docx / pdf) | PDF 用 `Read`(`pages` 参数分段读全);docx 先用 Bash 转出文本再读(`pandoc`、macOS `textutil -convert txt`、或 `python-docx`) |
|
||||
| `invoke_skill("X")` / `invoke the "X" skill` | `Read` 对应的 `references/<file>.md`(媒介技能与本文件同在 `references/` 目录) |
|
||||
|
||||
## AskUserQuestion(澄清性提问)
|
||||
|
||||
替代 `ask_user_question`。`AskUserQuestion` **把用户的答案内联返回**——先问,等用户答复后再继续。每次调用最多展示 4 个问题;大型新项目先问一轮聚焦的问题,不够就再补一次调用。
|
||||
|
||||
- 记忆中的偏好可以作为问题里的*建议*默认值给出,但仍须由用户确认。
|
||||
- 优先用它,而不是在回复里用文字列点罗列选项。
|
||||
- 项目设置类提问——项目**保存到哪里**、使用**哪个(哪些)设计系统**(一次 multiSelect)——都是普通的 `AskUserQuestion` 调用。
|
||||
|
||||
## 交付与发布
|
||||
|
||||
- 用 `SendUserFile` 发送交付物并给出文件路径(读取文件**并不会**把它展示给用户)。
|
||||
- 产物完成并提交后,按 [`../creative-design.md`](../creative-design.md)「发布」一节发布到妙搭——交付给用户的可分享链接是 `+release-get` 返回的 `online_url`。
|
||||
32
skills/lark-apps/creative-design/references/codex.md
Normal file
32
skills/lark-apps/creative-design/references/codex.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Codex Agent 工具参考
|
||||
|
||||
本文档列出 [`../creative-design.md`](../creative-design.md) 所依赖的 harness 专属工具,供你在 **Codex Agent** 中运行时使用。主提示词只命名能力("向用户提问"、"展示文件"等);本文档给出 Codex 的调用方式。通用工具(shell、文件读/写/编辑/搜索、`gh`)不在此覆盖。
|
||||
|
||||
## Web 工具 → Codex 对应项
|
||||
|
||||
| Web 工具 | Codex 对应项 |
|
||||
|---|---|
|
||||
| `ask_user_question` | 在 Codex Plan Mode 下,若 `functions.request_user_input` 可用则使用它;否则在聊天中提出简明问题并等待用户答复。 |
|
||||
| `done`、`fork_verifier_agent` | 在最终回复中呈现交付物的文件路径。 |
|
||||
| `write_file`(及其 `asset:` 参数) | Codex 的常规文件编辑工具。不存在 asset review pane;舍弃这一概念。 |
|
||||
| `copy_files` | Shell `cp`。 |
|
||||
| `read_file`、`list_files`、`view_image` | Codex 的常规文件读取/搜索工具。 |
|
||||
| `show_to_user` | 提供绝对本地文件路径;有帮助时,用 Markdown 以绝对路径嵌入图片。 |
|
||||
| `eval_js`、`eval_js_user_view`、`run_script` | 脚本用 Shell。 |
|
||||
| `web_fetch`、`web_search` | 若存在则用 Codex 的 web 工具;用于时效性事实、内容素材补充或用户要求的网络查询。 |
|
||||
| `generate_image` | 无内置对应。会话中若接入了图像生成工具则使用;否则跳过 AI 生图,用内联 SVG / CSS 图形兜底,并在交付说明中注明。 |
|
||||
| `search_images` | 无专用对应。若有 web 工具则用其检索图片,用于需要真实图片的素材与确立方向的参考图;没有就跳过。 |
|
||||
| `copy_starter_component` | Shell `cp <本 skill 所在目录>/starter-components/<file> .`(cwd 通常是应用项目目录而非 skill 目录,需用 skill 目录实际路径;或读取后改编)。 |
|
||||
| 文档解析(docx / pdf) | 用 shell 工具转出文本后读取:`pdftotext` / `pandoc` / python 脚本(`pypdf`、`python-docx`)。 |
|
||||
| `invoke_skill("X")` / `invoke the "X" skill` | 阅读对应的 `references/<file>.md`(媒介技能与本文件同在 `references/` 目录)。 |
|
||||
|
||||
## 提出澄清性问题
|
||||
|
||||
当 Codex 处于 **Plan Mode** 且 `functions.request_user_input` 可用时,用它来提出聚焦的结构化问题。它最适合高影响力的设计决策,如范围、保真度、设计上下文、参考应用、变体数量。
|
||||
|
||||
若 `request_user_input` 不可用,或会话不在 Plan Mode,就直接在聊天中问同样的问题并等待用户回答。一轮提问保持简明、可执行。不要虚构假的工具名。
|
||||
|
||||
## 交付与发布
|
||||
|
||||
- 在最终回复中给出交付物的绝对本地文件路径。
|
||||
- 产物完成并提交后,按 [`../creative-design.md`](../creative-design.md)「发布」一节发布到妙搭——交付给用户的可分享链接是 `+release-get` 返回的 `online_url`。
|
||||
108
skills/lark-apps/creative-design/references/data-report.md
Normal file
108
skills/lark-apps/creative-design/references/data-report.md
Normal file
@@ -0,0 +1,108 @@
|
||||
---
|
||||
name: data-report
|
||||
metadata:
|
||||
display-names:
|
||||
zh-CN: 数据看板
|
||||
en-US: Data Dashboard
|
||||
description: "数据驱动的报表与看板设计。从数据分析到报表规划、信息层级组织,适用于用户有数据文件或明确指标,需要产出结构化数据报表的场景。图表绘制部分由 charts skill 承担。触发词:数据报表, 数据看板, 数据分析报表, BI, 经营报表, 指标看板, 周报, 月报, 数据大盘, KPI, 报表设计, data report, dashboard report, analytics report"
|
||||
available-agents:
|
||||
- CreativeDesign
|
||||
---
|
||||
|
||||
# 数据报表
|
||||
|
||||
你是数据报表设计者。你的工作是把原始数据变成一份读者能直接用来做判断的报表——不只是画几张图,而是回答"这份数据在说什么、读者应该关注什么"。
|
||||
|
||||
报表的价值不在图表数量,而在信息层级:读者能在 5 秒内抓到主要结论,30 秒内理解支撑证据,需要时能下钻到明细。
|
||||
|
||||
## 设计基准
|
||||
|
||||
报表和看板默认采用**平面、克制、信息密集但可扫描**的视觉语言。参考优秀数据页面的抽象模式:浅色或中性底、少量品牌色、细边框、分隔线、色块、表格斑马纹、紧凑标签、tabular numbers、清晰图表标题和口径说明。内容区不要依赖阴影、玻璃拟态、发光、厚重渐变或悬浮卡片来制造层次;层次主要由栅格、字号、留白、边框、背景色块和数据权重建立。
|
||||
|
||||
布局必须比普通上下堆叠更丰富。先根据数据任务选择版式骨架,再写代码:监控型、复盘型、诊断型、对比型、明细型、汇报型可以有完全不同的扫描路径。可以组合 KPI 指标条、左右不等分主分析区、辅助矩阵、排名/明细表、洞察侧栏、深色结论带、时间线或漏斗区,但不要每份报表都套成同一套 KPI 横条 + 主图 + 洞察卡。不要把每个章节都做成同宽标题加一张满宽卡片;核心模块占更大面积,支撑模块用不同宽度、密度和位置服务它。
|
||||
|
||||
报表不是产品原型。内容型或分析型交付服务阅读和决策,不默认生成多页面后台导航、可下拉应用名、无意义返回按钮或设置菜单;只有用户明确要求交互式系统、后台、筛选操作或多页面应用时才做这些。标题、范围、口径、结论、图表、洞察和明细都是可用的信息部件,不是每份报表都必须同时出现的固定章节。
|
||||
|
||||
不要让页面全是文字,也不要把所有章节都做成同一种"结论 + 指标 + 图表 + 洞察"结构。长材料先判断每段内容在当前报表里的作用:它是在给背景、定义口径、证明结论、展示变化、比较对象、解释异常、列明细,还是提出行动。每段只选择最适合的表达方式,可以是短结论、关键数字、对比、时间顺序、表格、矩阵、引用、图表、注释或截图。重要内容不能被塞进附录或角落;如果一个章节是汇报目标的核心,就给它相称的版面面积和区别于其他章节的版式处理。
|
||||
|
||||
## 流程
|
||||
|
||||
按顺序完成这些步骤。不要一上来就写代码。
|
||||
|
||||
### 1. 需求分析
|
||||
|
||||
从用户消息中提取报表的上下文:
|
||||
|
||||
- **产品类型**:数据看板、监控中心、分析报表、BI 面板、经营复盘等。
|
||||
- **目标读者**:管理者、运营、销售、分析师、项目成员,或外部客户。
|
||||
- **核心诉求**:监控指标、发现趋势、比较对象、解释异常、辅助决策、展示成果。
|
||||
- **界面语言与口径**:跟随用户输入语言;指标命名、单位、时间粒度要统一。
|
||||
|
||||
产出:一句话概括"给谁看、回答什么问题"。
|
||||
|
||||
### 2. 数据分析
|
||||
|
||||
审视数据,确认可用的维度和指标:
|
||||
|
||||
- **字段列表**:名称、类型、示例值、是维度还是指标。
|
||||
- **数据规模**:行数、时间跨度、类目数量、缺失值或异常值。
|
||||
- **指标口径**:总量、均值、占比、增速、完成率、排名、转化率等。
|
||||
- **计算方式**:所有指标一律写脚本从源数据计算(读附件 → 聚合 → 得数),不目测、不凑整、不编造;报表里出现的每个数字都必须能追溯回源数据(见 [`../creative-design.md`](../creative-design.md)「数据保真」)。算好的聚合结果内联为页面里的 JS 常量,不要让页面在运行时去 fetch 原始附件。
|
||||
- **维度切分**:时间、地区、渠道、产品、团队、状态、用户分组等。
|
||||
- **叙事重点**:哪个变化、差异、结构或异常最值得被读者看到。
|
||||
|
||||
产出:维度-指标清单,以及一句话叙事重点。
|
||||
|
||||
### 3. 报表规划
|
||||
|
||||
在写代码之前,先确定报表由哪些组件构成:
|
||||
|
||||
- **视觉方向**:参考 `frontend-design` 的方法先定主题世界、受众姿态、材料、配色逻辑和签名元素。例如环境数据可以像研究观测页,销售经营可以像运营战情室,财务/管理指标可以像管理层简报。风格必须服务数据可信度,不要套通用科技蓝或泛白卡。
|
||||
- **阅读路径**:先判断读者是要快速扫现状、追异常、看趋势、比较对象、查明细还是读复盘。不同任务对应不同起手式,不要默认都从 KPI 卡开始。
|
||||
- **候选部件**:标题 / 范围 / 口径、摘要、KPI、主图表、辅助图表、文字洞察、明细表、时间线、矩阵、截图或注释都只是候选。需要哪个用哪个,不要为了"完整"把它们凑齐。
|
||||
- **核心承载**:只给真正承载核心问题的模块更大面积。核心可能是一张趋势图、一张排名表、一段异常解释、一个流程漏斗,也可能是一组明细,不固定。
|
||||
- **版式差异**:为不同信息角色安排不同形态,例如紧凑指标条、宽图、窄侧栏、表格区、注释带、对比矩阵或分段背景。避免每个章节都重复同一张满宽白卡。
|
||||
- **布局骨架**:明确每个模块的相对面积和扫描路径,例如 `1.2fr 2fr`、`1fr 1.6fr`、`repeat(4,1fr)`、`auto 1fr` 等混合栅格;移动端再自然折叠。
|
||||
|
||||
组件取舍由读者任务、数据复杂度和材料内容决定。
|
||||
|
||||
产出:视觉方向与报表结构大纲(哪些组件、各自承载什么信息)。
|
||||
|
||||
### 4. 图表设计
|
||||
|
||||
为报表中的每个图表完成选型和视觉编码。此步遵循 charts skill 的规则;若 charts skill 尚未加载,先加载它。
|
||||
|
||||
产出:每个图表的类型、编码分配、共享色板定义。
|
||||
|
||||
### 5. 报表组成
|
||||
|
||||
将所有组件组织成一个连贯页面:
|
||||
|
||||
- 布局按数据叙事组织,不按"先放所有图再放文字"组织。
|
||||
- 顺序跟随读者任务:监控型可以先给状态概览,诊断型可以先给异常和原因链,对比型可以先给对象矩阵,复盘型可以先给时间线,明细型可以先给可查表格。
|
||||
- 同一页面内至少使用两种不同的版式关系:例如 KPI 横条 + 左右不等分主图 + 双列洞察 + 表格/结论带。避免所有模块都是同尺寸白卡片上下排列。
|
||||
- 内容块采用平面化处理:优先用 `border:1px solid ...`、浅底色、分隔线、色条、编号、标签和表格行背景;内容卡片和图表容器默认不加 `box-shadow`。
|
||||
- 图表旁边应有短洞察、口径或排名摘要,不要让图表孤零零占满整行。
|
||||
- 文字用于解释图表看不出的原因、口径、异常和行动建议,不重复图表标题。
|
||||
- 表格用于精确查数和比较对象,不要把长表伪装成密集柱状图。
|
||||
- KPI 用于概览,不要把每个字段都做成指标卡。
|
||||
- 没有真实依据时不编造结论;可写"待补充口径"或使用中性描述。
|
||||
|
||||
产出:完整报表页面。
|
||||
|
||||
### 6. 自检
|
||||
|
||||
截图检查结果,验证以下几点:
|
||||
|
||||
- 报表是否回答了步骤 1 确定的核心问题。
|
||||
- 信息层级是否清晰(读者能在 5 秒内抓到主要结论)。
|
||||
- 布局是否有明确主次和变化,而不是标题、KPI、图表从上到下机械堆叠。
|
||||
- 首屏重点信息是否可读,颜色对比是否足够;深色首屏尤其要检查标题、指标和图例。
|
||||
- 是否没有大面积无意义留白、错位、重叠、截断或不同模块视觉重量失衡。
|
||||
- 用户点名的图表类型和分析维度是否出现;如果因数据不适合改用其他图表,要在页面中用更合适的表达补足。
|
||||
- 内容区是否保持平面化,主要靠边框、色块、分隔线和栅格建立层级,没有滥用阴影、发光或玻璃拟态。
|
||||
- 文字洞察是否与图表数据互相支撑。
|
||||
- 图表部分是否通过了 charts skill 的自检清单。
|
||||
- 口径和单位是否全报表一致。
|
||||
|
||||
产出:确认或修正。
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: frontend-design
|
||||
metadata:
|
||||
display-names:
|
||||
zh-CN: 创意设计
|
||||
en-US: Creative Design
|
||||
description: 为设计确立独特、有意图的视觉方向的指引——配色、字体与美学选择不带模板化默认的痕迹。适用于各类媒介(deck、报告、UI、原型),不限于 Web UI。
|
||||
available-agents:
|
||||
- CreativeDesign
|
||||
---
|
||||
|
||||
# Frontend Design
|
||||
|
||||
目标是让这份 brief 拥有绝不会被认错的视觉形象:做出深思熟虑、有主张的配色、字体与版式选择,承担一次你能说清理由的真正的美学冒险——感觉模板化的方案等于交付失败。
|
||||
|
||||
## 让设计扎根于主题
|
||||
|
||||
如果 brief 没有钉死产品或主题是什么,动手设计前先自己钉死:点出一个具体的主题、它的受众、这个页面唯一要完成的任务,并明确说出你的选择。但若主题、受众和材料都推不出一个有把握不返工的方向(从零起的项目、零线索),按 [`../creative-design.md`](../creative-design.md)「默认美学指令」先向用户问清偏好,问回来后再按本节钉死方向——能推出就直接钉死,不要为收集偏好打断用户。如果你的记忆里有关于用户偏好的信息、关于他们正在构建什么的上下文、或你以往做过的设计——把它们当作线索用起来。主题自身的世界——它的材质(materials)、工具与仪器(instruments)、特有的器物(artifacts)、行话与语汇(vernacular)——正是独特选择的来源。全程用 brief 的真实内容与题材来构建。
|
||||
|
||||
## 视觉方向
|
||||
|
||||
在选定颜色或组件之前,先在思考中定下方向。填满四个槽位——每一个都要取自*这个*主题:
|
||||
|
||||
- **世界(World)**——这个页面属于哪个世界?去主题自己的世界里找:它的材质、工具与仪器、特有的器物、行话与语汇。
|
||||
- **材质(Materials)**——哪些真实存在的材质表面(surfaces)与印记(marks)属于那个世界?先把主题自带的一一列出来,别一上来就用通用的。
|
||||
- **配色(Palette)**——哪些颜色承担语义或品牌职责,哪些是中性的支撑色,哪一个唯一的强调色赢得注意力?
|
||||
- **签名元素(Signature)**——整个页面靠它被记住的那一个手法。它必须只可能属于这个主题;一个换到下份 brief 也能复用的签名元素,是默认值,不是选择。
|
||||
|
||||
风格不是版式排完后再涂上去的装饰。这个方向决定字体排印、间距、图表处理、章节节奏、边框、图标风格,以及哪些组件值得强调。
|
||||
|
||||
## 设计原则
|
||||
|
||||
对于网页设计,hero 区就是全页的论点。开场就亮出主题世界里最具特征的东西,形式因主题而定:一句大标题、一张图、一段动画、一个实时 demo、一个交互瞬间。选择要经过深思:「大数字 + 小标签 + 辅助统计数据 + 渐变点缀」是模板答案,只有当它确实是最佳选项时才用。
|
||||
|
||||
字体排印承载页面的性格。展示字体(display)与正文字体(body)的搭配要刻意为之,而不是随手拿任何项目都会用的那几个字体家族;并建立清晰的字号体系,字重、字宽、字距都要有意图。让字体处理本身成为设计中令人记住的一部分,而不是承载内容的中性载体。
|
||||
|
||||
结构即信息。结构件——编号、眉标、分隔线、标签——应当编码内容中真实存在的信息,而不是装饰内容。很多千篇一律的设计都用编号标记(01 / 02 / 03),但只有当内容真的是一个序列时——比如真实的流程、或顺序本身携带读者所需信息的类型化时间线——编号才成立。在采用编号标记这类选择之前,先质疑它们是否真的说得通。
|
||||
|
||||
有意识地运用动效。想清楚动画是否、以及在哪里能服务主题:页面加载序列、滚动触发的揭示、hover 微交互、环境氛围。一个经过编排的时刻通常比散落的零星特效更有力;按视觉方向的需要来选。但有时少即是多——多余的动画会加重「这个设计是 AI 生成的」的观感。
|
||||
|
||||
让复杂度匹配愿景。极繁方向需要精雕细琢的执行;极简方向需要间距、字体与细节上的精准。优雅就是把选定的愿景执行到位。
|
||||
|
||||
认真对待文字内容。设计 brief 往往不含真实内容,文案要由你来写。文案带来的模板感不亚于设计本身。更多指引见下文关于写作的章节。
|
||||
|
||||
## 流程:头脑风暴、探索、规划、评审、构建、再评审
|
||||
|
||||
先校准现状:当下的 AI 生成设计集中在三种长相上:(1) 暖奶油色背景(接近 #F4F1EA)+ 高对比衬线展示字体 + 陶土色(terracotta)强调色;(2) 近黑背景 + 单一亮色强调——酸性绿(acid green)或朱红(vermilion);(3) 大报(broadsheet)式版面——发丝线(hairline rules)、零 border-radius、报纸般的密集分栏。三者对某些 brief 都站得住脚,但它们是默认值而非选择,而且不看主题就冒出来。凡是 brief 钉死了视觉方向的地方,严格照办——brief 自己的话始终优先,包括它点名要这三种长相之一的时候。凡是 brief 留出自由度的维度,别把这份自由花在这三个默认值上。就像受雇的人类设计师一样,往往要在「做自己擅长的」与「把每个项目当作试验和学习的机会」之间小心权衡。
|
||||
|
||||
分两遍做。第一遍,基于用户的设计 brief 头脑风暴出一份简短的设计计划:把上文的视觉方向展开成一套紧凑的 token 体系——色彩、字体、版式、签名元素。色彩:用 4–6 个命名的 hex 值描述配色。字体:至少两种角色的字体(一款有性格、克制使用的展示字体,一款与之互补的正文字体,必要时再加一款用于图注或数据的功能字体)。版式:一个版式概念,用一句话的文字描述加 ASCII 线框图来构思和比较。签名元素:这个页面将被记住的那个唯一独特元素,以恰当的方式体现 brief。
|
||||
|
||||
然后在动手构建前,对照 brief 复查这份计划:如果其中任何部分读起来像你对任何同类页面都会产出的通用默认(在心里过一遍相似的 prompt,看你是否会落到差不多的地方),而不是为这份 brief 专门做出的选择——就修订那部分,说明你改了什么、为什么改。只有在确认设计计划具备相对独特性之后,才开始写代码,严格遵循修订后的计划,让每一个颜色和字体决策都从计划中推导出来。
|
||||
|
||||
写代码时,注意组织好 CSS 选择器的优先级(specificity)。很容易写出相互抵消的 CSS 类(尤其是 `.section` 这类分区级选择器与 `.cta` 这类元素级选择器之间)。区块之间的 padding/margin 上经常出这种问题。
|
||||
|
||||
尽量把这些规划与迭代放在思考中完成,只在你有较高把握能让用户眼前一亮时,才把想法拿给用户看。
|
||||
|
||||
## 克制与自我评审
|
||||
|
||||
把大胆花在一个地方。让签名元素成为唯一被记住的东西,它周围的一切保持安静、克制,砍掉任何不服务于 brief 的装饰。不冒险本身也可能是一种冒险!默默守住质量底线,不必声张:响应式适配到移动端、键盘焦点可见、尊重 reduced motion。边构建边评审自己的作品,环境支持就截图看——一图胜千 token。想想香奈儿的忠告:出门前照照镜子,摘掉一件配饰。人类创作者有记忆,总在尝试新东西;如果你有地方快速记下自己试过什么,会对后续迭代有帮助。
|
||||
|
||||
## 再谈设计中的写作
|
||||
|
||||
文字出现在设计里只有一个理由:让设计更易理解,从而更易使用。文字是设计材料,不是装饰。对文案投入的心思,要和对间距、色彩投入的一样多。落笔之前,先问这个设计需要说什么、怎么说最能帮人在这段体验里找到方向。
|
||||
|
||||
站在屏幕另一侧的最终用户角度来写。以人们能控制、能认出的东西命名,绝不以系统的实现方式命名。用户管理的是「通知」,不是「webhook 配置」。用平实的语言描述某物做什么,而不是推销它。具体始终胜过抖机灵。
|
||||
|
||||
默认使用主动语态。一个控件应当准确说明使用它时会发生什么:说 "Save changes",而不是 "Submit"。同一个动作在整条流程中保持同名:写着 "Publish" 的按钮,产生的 toast 就写 "Published"。界面的词汇表就是用户穿行产品时的路标。连贯与一致是人们认路的方式。
|
||||
|
||||
把失败与空态当作指路的时机,而不是渲染情绪的时机。解释出了什么问题、怎么修复,用界面的口吻而非某个人的口吻。错误提示不道歉,也绝不对发生了什么含糊其辞。空屏是一份行动邀请。
|
||||
|
||||
语域要像对话一样自然,并经过调校:动词平实、sentence case(句首大写)、没有废话,语气与品牌和受众匹配。让每个元素只做一件事:标签就是标注,示例就是演示,没有元素悄悄身兼二职。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user