mirror of
https://github.com/larksuite/cli.git
synced 2026-08-03 08:32:46 +08:00
Compare commits
2 Commits
v1.0.70
...
sun/lark-d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a24e93c44 | ||
|
|
ec15ca58f6 |
16
.github/workflows/ci.yml
vendored
16
.github/workflows/ci.yml
vendored
@@ -64,6 +64,22 @@ jobs:
|
||||
- name: Run tests
|
||||
run: go test -v -race -count=1 -timeout=5m ./cmd/... ./internal/... ./shortcuts/... ./extension/...
|
||||
|
||||
windows-compat:
|
||||
needs: fast-gate
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
|
||||
- uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
with:
|
||||
python-version: '3.x'
|
||||
- name: Fetch meta data
|
||||
run: python scripts/fetch_meta.py
|
||||
- name: Run Windows compatibility tests
|
||||
run: go test -count=1 -timeout=5m . ./shortcuts/doc/...
|
||||
|
||||
lint:
|
||||
needs: fast-gate
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
15
AGENTS.md
15
AGENTS.md
@@ -105,20 +105,6 @@ Signatures that are easy to guess wrong:
|
||||
|
||||
Program output (JSON envelopes) goes to stdout. Progress, warnings, hints go to stderr. Mixing them corrupts pipe chains.
|
||||
|
||||
### Typed data over loose maps
|
||||
|
||||
Parse `map[string]interface{}` into a typed struct at the boundary — one projection function per shape — and let everything downstream consume struct fields, not string keys. A typo'd map key compiles fine and fails at runtime, which an agent then debugs blind.
|
||||
|
||||
Use distinct types when two values could be swapped silently: see `internal/meta.Token` — a bare string compiles on either side of a string/string signature, a distinct type does not.
|
||||
|
||||
Legacy loose-map code exists in older paths. Match its call sites when touching it, but do not copy the pattern into new code.
|
||||
|
||||
### Transcribe faithfully — no silent fallbacks
|
||||
|
||||
When code echoes input onward (request previews, transformations, proxies), transcribe verbatim. A `default:` branch that coerces unrecognized input into a plausible value ("unknown HTTP verb → GET") makes the output lie, and an agent reasons from the lie.
|
||||
|
||||
The same rule applies to flag combinations and internal wiring: if a requested option cannot be honored, return a typed validation error — never silently substitute another behavior and exit 0. Silent guesses (defaulting a missing identity, discarding writes on a nil writer) are bugs even when every current caller happens to avoid them.
|
||||
|
||||
### Use `vfs.*` instead of `os.*`
|
||||
|
||||
All filesystem access goes through `internal/vfs`. This enables test mocking.
|
||||
@@ -130,7 +116,6 @@ CLI arguments are untrusted (they come from AI agents). Call `validate.SafeInput
|
||||
### Tests
|
||||
|
||||
- Every behavior change needs a test alongside the change.
|
||||
- A contract test must fail if the implementation is reverted. If you can undo the code change and the suite stays green, the contract is not pinned — assert the new field/behavior directly, not a happy-path substring.
|
||||
- `cmdutil.TestFactory(t, config)` for test factories.
|
||||
- `t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())` to isolate config state.
|
||||
|
||||
|
||||
70
CHANGELOG.md
70
CHANGELOG.md
@@ -2,74 +2,6 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [v1.0.70] - 2026-07-15
|
||||
|
||||
### Features
|
||||
|
||||
- add minutes permission application shortcut (#1876)
|
||||
- **drive**: support apps in list comments (#1877)
|
||||
- slide style
|
||||
- edit ppt template
|
||||
- **slides**: add sxsd validation to slides lint
|
||||
- **slides**: validate iconpark icon types in slides lint
|
||||
- **slides**: lint before create
|
||||
- **apps**: add automation trigger commands for Miaoda (#1886)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- unify dry-run output contract (#1870)
|
||||
- **skills**: align skill guidance with the typed error contract (#1786)
|
||||
- **slides**: limit slides screenshot page requests
|
||||
- **slides**: detect lark slides text overflow overlap
|
||||
- **vc**: align meeting query scopes by identity (#1850)
|
||||
|
||||
### Documentation
|
||||
|
||||
- clarify task search relevance filters (#1884)
|
||||
- surface minutes permission application in skill description (#1890)
|
||||
- clarify okr progress children (#1861)
|
||||
- **slides**: prefer slides xml-get shortcut
|
||||
- **calendar**: document setting meeting owner via full API (#1903)
|
||||
|
||||
### Refactoring
|
||||
|
||||
- **slides**: streamline create workflow and validate SML namespaces
|
||||
|
||||
### Misc
|
||||
|
||||
- **slides**: address PR review feedback
|
||||
|
||||
## [v1.0.69] - 2026-07-13
|
||||
|
||||
### Features
|
||||
|
||||
- support docs fetch selection anchors (#1815)
|
||||
- **apps**: support modern_html app type with TOS publish path and app type querying
|
||||
- **im**: show bot sender display names when reading messages (#1829)
|
||||
- add drive list comments shortcut (#1845)
|
||||
- support wiki sources in drive export (#1802)
|
||||
- add application domain with slash command management shortcuts (#1806)
|
||||
- validate IM idempotency key length (#1797)
|
||||
- surface reply context and mentions in im.message.receive_v1 (#1798)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- route brand-sensitive endpoints through the resolver (#1836)
|
||||
|
||||
### Documentation
|
||||
|
||||
- document OKR block XML guidance (#1648)
|
||||
- refine doubao whiteboard workflow routing (#1841)
|
||||
- clarify Mindnote token handling (#1827)
|
||||
|
||||
### Tests
|
||||
|
||||
- isolate semantic waiver fixtures from wall clock
|
||||
|
||||
### Misc
|
||||
|
||||
- Merge lark sheets development branch (#1833)
|
||||
|
||||
## [v1.0.68] - 2026-07-09
|
||||
|
||||
### Features
|
||||
@@ -1506,8 +1438,6 @@ Bundled AI agent skills for intelligent assistance:
|
||||
- Bilingual documentation (English & Chinese).
|
||||
- CI/CD pipelines: linting, testing, coverage reporting, and automated releases.
|
||||
|
||||
[v1.0.70]: https://github.com/larksuite/cli/releases/tag/v1.0.70
|
||||
[v1.0.69]: https://github.com/larksuite/cli/releases/tag/v1.0.69
|
||||
[v1.0.68]: https://github.com/larksuite/cli/releases/tag/v1.0.68
|
||||
[v1.0.67]: https://github.com/larksuite/cli/releases/tag/v1.0.67
|
||||
[v1.0.66]: https://github.com/larksuite/cli/releases/tag/v1.0.66
|
||||
|
||||
@@ -130,13 +130,6 @@ func buildAPIRequest(opts *APIOptions) (client.RawApiRequest, *cmdutil.FileUploa
|
||||
stdin := opts.Factory.IOStreams.In
|
||||
fileIO := opts.Factory.ResolveFileIO(opts.Ctx)
|
||||
|
||||
if opts.Method == "" {
|
||||
return client.RawApiRequest{}, nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"HTTP method must not be empty").
|
||||
WithHint("pass the verb as the first argument, e.g. lark-cli api GET /open-apis/...").
|
||||
WithParam("<method>")
|
||||
}
|
||||
|
||||
// Validate --file mutual exclusions first.
|
||||
if err := cmdutil.ValidateFileFlag(opts.File, opts.Params, opts.Data, opts.Output, opts.PageAll, opts.Method); err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
@@ -250,9 +243,9 @@ func apiRun(opts *APIOptions) error {
|
||||
|
||||
if opts.DryRun {
|
||||
if fileMeta != nil {
|
||||
return cmdutil.PrintDryRunWithFile(request, config, dryRunOutputOptions(f, opts), *fileMeta)
|
||||
return cmdutil.PrintDryRunWithFile(f.IOStreams.Out, request, config, opts.Format, fileMeta.FieldName, fileMeta.FilePath, fileMeta.FormFields)
|
||||
}
|
||||
return apiDryRun(f, request, config, opts)
|
||||
return apiDryRun(f, request, config, opts.Format)
|
||||
}
|
||||
// Identity info is now included in the JSON envelope; skip stderr printing.
|
||||
// cmdutil.PrintIdentity(f.IOStreams.ErrOut, opts.As, config, f.IdentityAutoDetected)
|
||||
@@ -304,19 +297,8 @@ func apiRun(opts *APIOptions) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func apiDryRun(f *cmdutil.Factory, request client.RawApiRequest, config *core.CliConfig, opts *APIOptions) error {
|
||||
return cmdutil.PrintDryRun(request, config, dryRunOutputOptions(f, opts))
|
||||
}
|
||||
|
||||
func dryRunOutputOptions(f *cmdutil.Factory, opts *APIOptions) cmdutil.DryRunOutputOptions {
|
||||
return cmdutil.DryRunOutputOptions{
|
||||
Format: opts.Format,
|
||||
JqExpr: opts.JqExpr,
|
||||
CommandPath: opts.Cmd.CommandPath(),
|
||||
Identity: opts.As,
|
||||
Out: f.IOStreams.Out,
|
||||
ErrOut: f.IOStreams.ErrOut,
|
||||
}
|
||||
func apiDryRun(f *cmdutil.Factory, request client.RawApiRequest, config *core.CliConfig, format string) error {
|
||||
return cmdutil.PrintDryRun(f.IOStreams.Out, request, config, format)
|
||||
}
|
||||
|
||||
func apiPaginate(ctx context.Context, ac *client.APIClient, request client.RawApiRequest, format output.Format, jqExpr string, out, errOut io.Writer, commandPath string, pagOpts client.PaginationOptions) error {
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestApiCmd_FlagParsing(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApiCmd_DryRun(t *testing.T) {
|
||||
f, stdout, stderr, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
|
||||
@@ -79,42 +79,12 @@ func TestApiCmd_DryRun(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
output := stdout.String()
|
||||
if !strings.Contains(output, "Dry Run") {
|
||||
t.Error("expected dry run output")
|
||||
}
|
||||
if got["ok"] != true || got["identity"] != "bot" || got["dry_run"] != true {
|
||||
t.Fatalf("unexpected dry-run envelope: %#v", got)
|
||||
}
|
||||
data, ok := got["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("data = %#v, want object", got["data"])
|
||||
}
|
||||
api, ok := data["api"].([]interface{})
|
||||
if !ok || len(api) != 1 {
|
||||
t.Fatalf("api = %#v, want one call", data["api"])
|
||||
}
|
||||
call, ok := api[0].(map[string]interface{})
|
||||
if !ok || call["url"] != "/open-apis/test" {
|
||||
t.Fatalf("api[0] = %#v", api[0])
|
||||
}
|
||||
if strings.Contains(stdout.String(), "=== Dry Run ===") {
|
||||
t.Fatalf("stdout should not contain dry-run banner: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_DryRunWithJq(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
|
||||
cmd := newTestApiCmd(f, nil)
|
||||
cmd.SetArgs([]string{"GET", "/open-apis/test", "--as", "bot", "--dry-run", "--jq", ".data.api[0].url"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(stdout.String()); got != "/open-apis/test" {
|
||||
t.Fatalf("jq output = %q, want /open-apis/test", got)
|
||||
if !strings.Contains(output, "/open-apis/test") {
|
||||
t.Error("expected path in dry run output")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,22 +152,6 @@ func TestApiCmd_MissingArgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_EmptyMethodRejected(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
|
||||
cmd := newTestApiCmd(f, nil)
|
||||
cmd.SetArgs([]string{"", "/open-apis/test", "--as", "bot", "--dry-run"})
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected validation error for empty HTTP method")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "method") {
|
||||
t.Fatalf("error should name the method argument, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_InvalidParamsJSON(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
@@ -1046,23 +1000,11 @@ func TestApiCmd_DryRunWithFile(t *testing.T) {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, out)
|
||||
if !strings.Contains(out, "image") {
|
||||
t.Errorf("expected dry-run output to mention file field, got: %s", out)
|
||||
}
|
||||
if env["dry_run"] != true {
|
||||
t.Fatalf("dry_run = %#v, want true", env["dry_run"])
|
||||
}
|
||||
data := env["data"].(map[string]interface{})
|
||||
api := data["api"].([]interface{})
|
||||
call := api[0].(map[string]interface{})
|
||||
body := call["body"].(map[string]interface{})
|
||||
file := body["file"].(map[string]interface{})
|
||||
if file["field"] != "image" || file["path"] != tmpFile {
|
||||
t.Fatalf("unexpected file dry-run body: %#v", body)
|
||||
}
|
||||
if strings.Contains(out, "=== Dry Run ===") {
|
||||
t.Fatalf("stdout should not contain dry-run banner: %s", out)
|
||||
if !strings.Contains(out, "Dry Run") {
|
||||
t.Errorf("expected dry-run header, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -128,5 +128,5 @@ func getLoginMsg(lang i18n.Lang) *loginMsg {
|
||||
// (not backed by from_meta service specs). Descriptions are now centralized in
|
||||
// service_descriptions.json.
|
||||
func getShortcutOnlyDomainNames() []string {
|
||||
return []string{"application", "base", "contact", "docs", "markdown", "apps", "note"}
|
||||
return []string{"base", "contact", "docs", "markdown", "apps", "note"}
|
||||
}
|
||||
|
||||
@@ -96,40 +96,6 @@ func TestRunSchema_JSONOutput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunSchema_ReceiveMessageAgentFieldsJSON(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "test"})
|
||||
|
||||
if err := runSchema(f, "im.message.receive_v1", true); err != nil {
|
||||
t.Fatalf("runSchema json: %v", err)
|
||||
}
|
||||
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("output is not valid JSON: %v\n%s", err, stdout.String())
|
||||
}
|
||||
resolved := payload["resolved_output_schema"].(map[string]interface{})
|
||||
props := resolved["properties"].(map[string]interface{})
|
||||
for _, field := range []string{
|
||||
"root_id",
|
||||
"thread_id",
|
||||
"reply_to",
|
||||
"sender_type",
|
||||
"mentions",
|
||||
} {
|
||||
if _, ok := props[field]; !ok {
|
||||
t.Errorf("receive schema missing field %q", field)
|
||||
}
|
||||
}
|
||||
msgDesc := props["message_id"].(map[string]interface{})["description"].(string)
|
||||
if !strings.Contains(msgDesc, "Recommended idempotency key") {
|
||||
t.Errorf("message_id description should guide deduplication, got %q", msgDesc)
|
||||
}
|
||||
eventDesc := props["event_id"].(map[string]interface{})["description"].(string)
|
||||
if strings.Contains(eventDesc, "safe for deduplication") {
|
||||
t.Errorf("event_id description should not recommend deduplication, got %q", eventDesc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunSchema_TaskUpdateUserAccessJSON(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "test"})
|
||||
|
||||
|
||||
@@ -403,9 +403,9 @@ func serviceMethodRun(opts *ServiceMethodOptions) error {
|
||||
|
||||
if opts.DryRun {
|
||||
if fileMeta != nil {
|
||||
return cmdutil.PrintDryRunWithFile(request, config, serviceDryRunOutputOptions(f, opts), *fileMeta)
|
||||
return cmdutil.PrintDryRunWithFile(f.IOStreams.Out, request, config, opts.Format, fileMeta.FieldName, fileMeta.FilePath, fileMeta.FormFields)
|
||||
}
|
||||
return serviceDryRun(f, request, config, opts)
|
||||
return serviceDryRun(f, request, config, opts.Format)
|
||||
}
|
||||
|
||||
if opts.Method.Risk == cmdutil.RiskHighRiskWrite {
|
||||
@@ -667,19 +667,8 @@ func buildServiceRequest(opts *ServiceMethodOptions) (client.RawApiRequest, *cmd
|
||||
return request, nil, nil
|
||||
}
|
||||
|
||||
func serviceDryRun(f *cmdutil.Factory, request client.RawApiRequest, config *core.CliConfig, opts *ServiceMethodOptions) error {
|
||||
return cmdutil.PrintDryRun(request, config, serviceDryRunOutputOptions(f, opts))
|
||||
}
|
||||
|
||||
func serviceDryRunOutputOptions(f *cmdutil.Factory, opts *ServiceMethodOptions) cmdutil.DryRunOutputOptions {
|
||||
return cmdutil.DryRunOutputOptions{
|
||||
Format: opts.Format,
|
||||
JqExpr: opts.JqExpr,
|
||||
CommandPath: opts.Cmd.CommandPath(),
|
||||
Identity: opts.As,
|
||||
Out: f.IOStreams.Out,
|
||||
ErrOut: f.IOStreams.ErrOut,
|
||||
}
|
||||
func serviceDryRun(f *cmdutil.Factory, request client.RawApiRequest, config *core.CliConfig, format string) error {
|
||||
return cmdutil.PrintDryRun(f.IOStreams.Out, request, config, format)
|
||||
}
|
||||
|
||||
func servicePaginate(ctx context.Context, ac *client.APIClient, request client.RawApiRequest, format output.Format, jqExpr string, out, errOut io.Writer, commandPath string, pagOpts client.PaginationOptions, checkErr func(interface{}, core.Identity) error) error {
|
||||
|
||||
@@ -224,39 +224,13 @@ func TestServiceMethod_DryRun_PathParam(t *testing.T) {
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if got["ok"] != true || got["dry_run"] != true {
|
||||
t.Fatalf("unexpected dry-run envelope: %#v", got)
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
api := data["api"].([]interface{})
|
||||
call := api[0].(map[string]interface{})
|
||||
if call["url"] != tt.wantInURL {
|
||||
t.Errorf("url = %q, want %q\nstdout:\n%s", call["url"], tt.wantInURL, stdout.String())
|
||||
if !strings.Contains(stdout.String(), tt.wantInURL) {
|
||||
t.Errorf("expected URL containing %q, got:\n%s", tt.wantInURL, stdout.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_DryRunWithJq(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
cmd := NewCmdServiceMethod(f, driveSpec(), driveMethod("GET", nil), "get", "files", nil)
|
||||
cmd.SetArgs([]string{
|
||||
"--params", `{"file_token":"boxcn123abc"}`,
|
||||
"--dry-run",
|
||||
"--jq", ".data.api[0].url",
|
||||
})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got, want := strings.TrimSpace(stdout.String()), "/open-apis/drive/v1/files/boxcn123abc/copy"; got != want {
|
||||
t.Fatalf("jq output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_PathParamRejectsTraversal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -344,12 +318,8 @@ func TestServiceMethod_PaginationParamSkippedWithPageAll(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error with --page-all skipping page_size, got: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if got["dry_run"] != true {
|
||||
t.Fatalf("dry_run = %#v, want true", got["dry_run"])
|
||||
if !strings.Contains(stdout.String(), "Dry Run") {
|
||||
t.Error("expected dry-run output")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1111,23 +1081,11 @@ func TestServiceMethod_FileUpload_DryRun(t *testing.T) {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, out)
|
||||
if !strings.Contains(out, "image") {
|
||||
t.Errorf("expected dry-run output to mention file field, got: %s", out)
|
||||
}
|
||||
if env["dry_run"] != true {
|
||||
t.Fatalf("dry_run = %#v, want true", env["dry_run"])
|
||||
}
|
||||
data := env["data"].(map[string]interface{})
|
||||
api := data["api"].([]interface{})
|
||||
call := api[0].(map[string]interface{})
|
||||
body := call["body"].(map[string]interface{})
|
||||
file := body["file"].(map[string]interface{})
|
||||
if file["field"] != "image" || file["path"] != tmpFile {
|
||||
t.Fatalf("unexpected file dry-run body: %#v", body)
|
||||
}
|
||||
if strings.Contains(out, "=== Dry Run ===") {
|
||||
t.Fatalf("stdout should not contain dry-run banner: %s", out)
|
||||
if !strings.Contains(out, "Dry Run") {
|
||||
t.Errorf("expected dry-run header, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,29 +13,17 @@ import (
|
||||
|
||||
// ImMessageReceiveOutput is the flattened shape for im.message.receive_v1; `desc` tags drive the reflected schema.
|
||||
type ImMessageReceiveOutput struct {
|
||||
Type string `json:"type" desc:"Event type; always im.message.receive_v1"`
|
||||
EventID string `json:"event_id,omitempty" desc:"Event delivery ID. Do not use as the message deduplication key; use message_id instead."`
|
||||
Timestamp string `json:"timestamp,omitempty" desc:"Event delivery time (ms timestamp string); prefers header.create_time" kind:"timestamp_ms"`
|
||||
ID string `json:"id,omitempty" desc:"Message ID (legacy alias of message_id, kept for compatibility)" kind:"message_id"`
|
||||
MessageID string `json:"message_id,omitempty" desc:"Message ID; prefixed with om_. Recommended idempotency key for im.message.receive_v1 consumers." kind:"message_id"`
|
||||
CreateTime string `json:"create_time,omitempty" desc:"Message creation time (ms timestamp string)" kind:"timestamp_ms"`
|
||||
UpdateTime string `json:"update_time,omitempty" desc:"Message update time (ms timestamp string); emitted only when different from create_time" kind:"timestamp_ms"`
|
||||
ChatID string `json:"chat_id,omitempty" desc:"Chat/conversation ID; prefixed with oc_" kind:"chat_id"`
|
||||
ChatType string `json:"chat_type,omitempty" desc:"Conversation type" enum:"p2p,group"`
|
||||
MessageType string `json:"message_type,omitempty" desc:"Message type"`
|
||||
SenderID string `json:"sender_id,omitempty" desc:"Sender open_id; prefixed with ou_" kind:"open_id"`
|
||||
SenderType string `json:"sender_type,omitempty" desc:"Sender type" enum:"user,bot"`
|
||||
RootID string `json:"root_id,omitempty" desc:"Root message ID of the reply/thread context, when present" kind:"message_id"`
|
||||
ThreadID string `json:"thread_id,omitempty" desc:"Thread ID, when present"`
|
||||
ReplyTo string `json:"reply_to,omitempty" desc:"Parent message ID of the direct reply context, when present" kind:"message_id"`
|
||||
Content string `json:"content,omitempty" desc:"Message content. For most types (text/post/image/file/audio, etc.) this is pre-rendered human-readable text."`
|
||||
Mentions []MentionOutput `json:"mentions,omitempty" desc:"Compact mentions aligned with im +messages-mget"`
|
||||
}
|
||||
|
||||
type MentionOutput struct {
|
||||
Key string `json:"key,omitempty" desc:"Mention placeholder key, for example @_user_1"`
|
||||
ID string `json:"id,omitempty" desc:"Mentioned user open_id; prefixed with ou_" kind:"open_id"`
|
||||
Name string `json:"name,omitempty" desc:"Mentioned display name"`
|
||||
Type string `json:"type" desc:"Event type; always im.message.receive_v1"`
|
||||
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"`
|
||||
ID string `json:"id,omitempty" desc:"Message ID (legacy alias of message_id, kept for compatibility)" kind:"message_id"`
|
||||
MessageID string `json:"message_id,omitempty" desc:"Message ID; prefixed with om_" kind:"message_id"`
|
||||
CreateTime string `json:"create_time,omitempty" desc:"Message creation time (ms timestamp string)" kind:"timestamp_ms"`
|
||||
ChatID string `json:"chat_id,omitempty" desc:"Chat/conversation ID; prefixed with oc_" kind:"chat_id"`
|
||||
ChatType string `json:"chat_type,omitempty" desc:"Conversation type" enum:"p2p,group"`
|
||||
MessageType string `json:"message_type,omitempty" desc:"Message type"`
|
||||
SenderID string `json:"sender_id,omitempty" desc:"Sender open_id; prefixed with ou_" kind:"open_id"`
|
||||
Content string `json:"content,omitempty" desc:"Message content. For most types (text/post/image/file/audio, etc.) this is pre-rendered human-readable text."`
|
||||
}
|
||||
|
||||
func processImMessageReceive(_ context.Context, _ event.APIClient, raw *event.RawEvent, _ map[string]string) (json.RawMessage, error) {
|
||||
@@ -48,20 +36,15 @@ func processImMessageReceive(_ context.Context, _ event.APIClient, raw *event.Ra
|
||||
Event struct {
|
||||
Message struct {
|
||||
MessageID string `json:"message_id"`
|
||||
RootID string `json:"root_id"`
|
||||
ParentID string `json:"parent_id"`
|
||||
ThreadID string `json:"thread_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
ChatType string `json:"chat_type"`
|
||||
MessageType string `json:"message_type"`
|
||||
Content string `json:"content"`
|
||||
CreateTime string `json:"create_time"`
|
||||
UpdateTime string `json:"update_time"`
|
||||
Mentions []interface{} `json:"mentions"`
|
||||
} `json:"message"`
|
||||
Sender struct {
|
||||
SenderType string `json:"sender_type"`
|
||||
SenderID struct {
|
||||
SenderID struct {
|
||||
OpenID string `json:"open_id"`
|
||||
} `json:"sender_id"`
|
||||
} `json:"sender"`
|
||||
@@ -98,54 +81,7 @@ func processImMessageReceive(_ context.Context, _ event.APIClient, raw *event.Ra
|
||||
ChatType: msg.ChatType,
|
||||
MessageType: msg.MessageType,
|
||||
SenderID: envelope.Event.Sender.SenderID.OpenID,
|
||||
SenderType: envelope.Event.Sender.SenderType,
|
||||
RootID: msg.RootID,
|
||||
ThreadID: msg.ThreadID,
|
||||
ReplyTo: msg.ParentID,
|
||||
Content: content,
|
||||
Mentions: compactMentions(msg.Mentions),
|
||||
}
|
||||
if msg.UpdateTime != "" && msg.UpdateTime != msg.CreateTime {
|
||||
out.UpdateTime = msg.UpdateTime
|
||||
}
|
||||
return json.Marshal(out)
|
||||
}
|
||||
|
||||
func compactMentions(mentions []interface{}) []MentionOutput {
|
||||
if len(mentions) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]MentionOutput, 0, len(mentions))
|
||||
for _, raw := range mentions {
|
||||
item, _ := raw.(map[string]interface{})
|
||||
mention := MentionOutput{
|
||||
Key: stringField(item, "key"),
|
||||
ID: mentionOpenID(item["id"]),
|
||||
Name: stringField(item, "name"),
|
||||
}
|
||||
if mention.Key != "" || mention.ID != "" || mention.Name != "" {
|
||||
out = append(out, mention)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func stringField(m map[string]interface{}, key string) string {
|
||||
v, _ := m[key].(string)
|
||||
return v
|
||||
}
|
||||
|
||||
func mentionOpenID(raw interface{}) string {
|
||||
switch v := raw.(type) {
|
||||
case map[string]interface{}:
|
||||
openID, _ := v["open_id"].(string)
|
||||
return openID
|
||||
case string:
|
||||
return v
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,32 +84,19 @@ func TestProcessImMessageReceive_Text(t *testing.T) {
|
||||
},
|
||||
"event": {
|
||||
"sender": {
|
||||
"sender_type": "user",
|
||||
"sender_id": {"open_id": "ou_sender"}
|
||||
},
|
||||
"message": {
|
||||
"message_id": "om_text_001",
|
||||
"root_id": "om_root_001",
|
||||
"parent_id": "om_parent_001",
|
||||
"thread_id": "omt_thread_001",
|
||||
"chat_id": "oc_chat",
|
||||
"chat_type": "p2p",
|
||||
"message_type": "text",
|
||||
"create_time": "1776409468987",
|
||||
"update_time": "1776409469999",
|
||||
"content": "{\"text\":\"hello @_user_1\"}",
|
||||
"mentions": [
|
||||
{
|
||||
"key": "@_user_1",
|
||||
"id": {"open_id": "ou_mentioned"},
|
||||
"name": "Alice"
|
||||
}
|
||||
]
|
||||
"content": "{\"text\":\"hello there\"}"
|
||||
}
|
||||
}
|
||||
}`
|
||||
out := runReceive(t, payload)
|
||||
outMap := runReceiveMap(t, payload)
|
||||
|
||||
if out.Type != "im.message.receive_v1" {
|
||||
t.Errorf("Type = %q", out.Type)
|
||||
@@ -123,69 +110,12 @@ func TestProcessImMessageReceive_Text(t *testing.T) {
|
||||
if out.SenderID != "ou_sender" {
|
||||
t.Errorf("SenderID = %q", out.SenderID)
|
||||
}
|
||||
if out.Content != "hello @Alice" {
|
||||
t.Errorf("Content = %q, want \"hello @Alice\"", out.Content)
|
||||
if out.Content != "hello there" {
|
||||
t.Errorf("Content = %q, want \"hello there\"", out.Content)
|
||||
}
|
||||
if out.Timestamp != "1776409469273" {
|
||||
t.Errorf("Timestamp = %q", out.Timestamp)
|
||||
}
|
||||
for field, want := range map[string]string{
|
||||
"sender_type": "user",
|
||||
"root_id": "om_root_001",
|
||||
"thread_id": "omt_thread_001",
|
||||
"reply_to": "om_parent_001",
|
||||
"update_time": "1776409469999",
|
||||
} {
|
||||
if got, _ := outMap[field].(string); got != want {
|
||||
t.Errorf("%s = %q, want %q", field, got, want)
|
||||
}
|
||||
}
|
||||
mentions, _ := outMap["mentions"].([]interface{})
|
||||
if len(mentions) != 1 {
|
||||
t.Fatalf("mentions length = %d, want 1: %#v", len(mentions), outMap["mentions"])
|
||||
}
|
||||
mention, _ := mentions[0].(map[string]interface{})
|
||||
for field, want := range map[string]string{
|
||||
"key": "@_user_1",
|
||||
"id": "ou_mentioned",
|
||||
"name": "Alice",
|
||||
} {
|
||||
if got, _ := mention[field].(string); got != want {
|
||||
t.Errorf("mentions[0].%s = %q, want %q", field, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessImMessageReceive_OmitsUnchangedUpdateTime(t *testing.T) {
|
||||
payload := `{
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
"event_id": "ev_test_text",
|
||||
"event_type": "im.message.receive_v1",
|
||||
"create_time": "1776409469273",
|
||||
"app_id": "cli_test"
|
||||
},
|
||||
"event": {
|
||||
"sender": {
|
||||
"sender_type": "user",
|
||||
"sender_id": {"open_id": "ou_sender"}
|
||||
},
|
||||
"message": {
|
||||
"message_id": "om_text_001",
|
||||
"chat_id": "oc_chat",
|
||||
"chat_type": "p2p",
|
||||
"message_type": "text",
|
||||
"create_time": "1776409468987",
|
||||
"update_time": "1776409468987",
|
||||
"content": "{\"text\":\"hello there\"}"
|
||||
}
|
||||
}
|
||||
}`
|
||||
outMap := runReceiveMap(t, payload)
|
||||
|
||||
if _, ok := outMap["update_time"]; ok {
|
||||
t.Errorf("update_time should be omitted when it equals create_time: %#v", outMap)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessImMessageReceive_Interactive(t *testing.T) {
|
||||
@@ -258,22 +188,3 @@ func runReceive(t *testing.T, payload string) ImMessageReceiveOutput {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func runReceiveMap(t *testing.T, payload string) map[string]interface{} {
|
||||
t.Helper()
|
||||
raw := &event.RawEvent{
|
||||
EventID: "ev_test",
|
||||
EventType: "im.message.receive_v1",
|
||||
Payload: json.RawMessage(payload),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
got, err := processImMessageReceive(context.Background(), nil, raw, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Process error: %v", err)
|
||||
}
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal(got, &out); err != nil {
|
||||
t.Fatalf("Process output is not valid JSON: %v\nraw=%s", err, string(got))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
1
go.mod
1
go.mod
@@ -18,6 +18,7 @@ require (
|
||||
github.com/spf13/pflag v1.0.9
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
github.com/yuin/goldmark v1.7.16
|
||||
github.com/zalando/go-keyring v0.2.8
|
||||
golang.org/x/net v0.33.0
|
||||
golang.org/x/sync v0.15.0
|
||||
|
||||
2
go.sum
2
go.sum
@@ -131,6 +131,8 @@ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavM
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.7.16 h1:n+CJdUxaFMiDUNnWC3dMWCIQJSkxH4uz3ZwQBkAlVNE=
|
||||
github.com/yuin/goldmark v1.7.16/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
|
||||
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
|
||||
@@ -8,29 +8,15 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/util"
|
||||
)
|
||||
|
||||
var dryRunURLPlaceholderRE = regexp.MustCompile(`:([A-Za-z_][A-Za-z0-9_]*)`)
|
||||
|
||||
// DryRunOutputOptions controls dry-run stdout/stderr rendering.
|
||||
type DryRunOutputOptions struct {
|
||||
Format string
|
||||
JqExpr string
|
||||
CommandPath string
|
||||
Identity core.Identity
|
||||
Out io.Writer
|
||||
ErrOut io.Writer
|
||||
}
|
||||
|
||||
// DryRunAPICall describes a single API call in dry-run output.
|
||||
type DryRunAPICall struct {
|
||||
Desc string `json:"desc,omitempty"`
|
||||
@@ -40,21 +26,12 @@ type DryRunAPICall struct {
|
||||
Body interface{} `json:"body,omitempty"`
|
||||
}
|
||||
|
||||
// DryRunContext is the execution context shared by every dry-run preview:
|
||||
// which app would make the call and, when known, as which user. The identity
|
||||
// itself lives at the envelope top level, not here.
|
||||
type DryRunContext struct {
|
||||
AppID string `json:"app_id,omitempty"`
|
||||
UserOpenID string `json:"user_open_id,omitempty"`
|
||||
}
|
||||
|
||||
// DryRunAPI is the builder and result type for dry-run output.
|
||||
// URL templates use :param placeholders; Set stores actual values; MarshalJSON and Format resolve them.
|
||||
type DryRunAPI struct {
|
||||
desc string
|
||||
calls []DryRunAPICall
|
||||
context *DryRunContext
|
||||
extra map[string]interface{}
|
||||
desc string
|
||||
calls []DryRunAPICall
|
||||
extra map[string]interface{}
|
||||
}
|
||||
|
||||
func NewDryRunAPI() *DryRunAPI {
|
||||
@@ -63,22 +40,30 @@ func NewDryRunAPI() *DryRunAPI {
|
||||
|
||||
// --- HTTP method builders (add a call, return self for chaining) ---
|
||||
|
||||
// call appends a request with the method transcribed verbatim, so previews
|
||||
// never misreport what the real client would send.
|
||||
func (d *DryRunAPI) call(method, url string) *DryRunAPI {
|
||||
d.calls = append(d.calls, DryRunAPICall{Method: method, URL: url})
|
||||
func (d *DryRunAPI) GET(url string) *DryRunAPI {
|
||||
d.calls = append(d.calls, DryRunAPICall{Method: "GET", URL: url})
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *DryRunAPI) GET(url string) *DryRunAPI { return d.call("GET", url) }
|
||||
func (d *DryRunAPI) POST(url string) *DryRunAPI {
|
||||
d.calls = append(d.calls, DryRunAPICall{Method: "POST", URL: url})
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *DryRunAPI) POST(url string) *DryRunAPI { return d.call("POST", url) }
|
||||
func (d *DryRunAPI) PUT(url string) *DryRunAPI {
|
||||
d.calls = append(d.calls, DryRunAPICall{Method: "PUT", URL: url})
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *DryRunAPI) PUT(url string) *DryRunAPI { return d.call("PUT", url) }
|
||||
func (d *DryRunAPI) DELETE(url string) *DryRunAPI {
|
||||
d.calls = append(d.calls, DryRunAPICall{Method: "DELETE", URL: url})
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *DryRunAPI) DELETE(url string) *DryRunAPI { return d.call("DELETE", url) }
|
||||
|
||||
func (d *DryRunAPI) PATCH(url string) *DryRunAPI { return d.call("PATCH", url) }
|
||||
func (d *DryRunAPI) PATCH(url string) *DryRunAPI {
|
||||
d.calls = append(d.calls, DryRunAPICall{Method: "PATCH", URL: url})
|
||||
return d
|
||||
}
|
||||
|
||||
// Body sets the request body on the last added call.
|
||||
func (d *DryRunAPI) Body(body interface{}) *DryRunAPI {
|
||||
@@ -113,26 +98,12 @@ func (d *DryRunAPI) Set(key string, value interface{}) *DryRunAPI {
|
||||
return d
|
||||
}
|
||||
|
||||
// Context records the calling app/user under data.context; empty values are
|
||||
// omitted, and a fully empty context is not emitted at all.
|
||||
func (d *DryRunAPI) Context(appID, userOpenID string) *DryRunAPI {
|
||||
if appID == "" && userOpenID == "" {
|
||||
return d
|
||||
}
|
||||
d.context = &DryRunContext{AppID: appID, UserOpenID: userOpenID}
|
||||
return d
|
||||
}
|
||||
|
||||
// resolveURL replaces :key placeholders in url with path-escaped values from extra.
|
||||
func (d *DryRunAPI) resolveURL(rawURL string) string {
|
||||
return dryRunURLPlaceholderRE.ReplaceAllStringFunc(rawURL, func(token string) string {
|
||||
name := token[1:]
|
||||
value, ok := d.extra[name]
|
||||
if !ok {
|
||||
return token
|
||||
}
|
||||
return url.PathEscape(fmt.Sprintf("%v", value))
|
||||
})
|
||||
for k, v := range d.extra {
|
||||
rawURL = strings.ReplaceAll(rawURL, ":"+k, url.PathEscape(fmt.Sprintf("%v", v)))
|
||||
}
|
||||
return rawURL
|
||||
}
|
||||
|
||||
// MarshalJSON serializes as {"description": "...", "api": [...calls with resolved URLs], ...extra}.
|
||||
@@ -147,17 +118,13 @@ func (d *DryRunAPI) MarshalJSON() ([]byte, error) {
|
||||
Body: c.Body,
|
||||
}
|
||||
}
|
||||
m := make(map[string]interface{}, len(d.extra)+3)
|
||||
for k, v := range d.extra {
|
||||
m[k] = v
|
||||
}
|
||||
// Typed fields win over same-named extra keys.
|
||||
m := make(map[string]interface{}, len(d.extra)+2)
|
||||
if d.desc != "" {
|
||||
m["description"] = d.desc
|
||||
}
|
||||
m["api"] = resolved
|
||||
if d.context != nil {
|
||||
m["context"] = d.context
|
||||
for k, v := range d.extra {
|
||||
m[k] = v
|
||||
}
|
||||
return json.Marshal(m)
|
||||
}
|
||||
@@ -187,7 +154,11 @@ func (d *DryRunAPI) Format() string {
|
||||
u += "?" + encodeParams(c.Params)
|
||||
}
|
||||
|
||||
b.WriteString(c.Method)
|
||||
method := c.Method
|
||||
if method == "" {
|
||||
method = "GET"
|
||||
}
|
||||
b.WriteString(method)
|
||||
b.WriteByte(' ')
|
||||
b.WriteString(u)
|
||||
b.WriteByte('\n')
|
||||
@@ -244,74 +215,83 @@ func encodeParams(params map[string]interface{}) string {
|
||||
return vals.Encode()
|
||||
}
|
||||
|
||||
// buildDryRunPreview assembles the shared preview skeleton: HTTP method, URL,
|
||||
// query params, and the app/user context common to every dry-run.
|
||||
func buildDryRunPreview(request client.RawApiRequest, config *core.CliConfig) *DryRunAPI {
|
||||
dr := NewDryRunAPI().call(request.Method, request.URL)
|
||||
// PrintDryRunWithFile outputs a dry-run summary for file upload requests.
|
||||
// Instead of serializing the Formdata body, it shows file metadata.
|
||||
func PrintDryRunWithFile(w io.Writer, request client.RawApiRequest, config *core.CliConfig, format, fileField, filePath string, formFields any) error {
|
||||
dr := NewDryRunAPI()
|
||||
switch request.Method {
|
||||
case "POST":
|
||||
dr.POST(request.URL)
|
||||
case "PUT":
|
||||
dr.PUT(request.URL)
|
||||
case "PATCH":
|
||||
dr.PATCH(request.URL)
|
||||
case "DELETE":
|
||||
dr.DELETE(request.URL)
|
||||
default:
|
||||
dr.GET(request.URL)
|
||||
}
|
||||
if len(request.Params) > 0 {
|
||||
dr.Params(request.Params)
|
||||
}
|
||||
// Identity is reported at the envelope top level, not duplicated here.
|
||||
dr.Context(config.AppID, config.UserOpenId)
|
||||
return dr
|
||||
}
|
||||
|
||||
// PrintDryRunWithFile outputs a dry-run summary for file upload requests.
|
||||
// Instead of serializing the Formdata body, it shows file metadata.
|
||||
func PrintDryRunWithFile(request client.RawApiRequest, config *core.CliConfig, opts DryRunOutputOptions, file FileUploadMeta) error {
|
||||
dr := buildDryRunPreview(request, config)
|
||||
filePathDisplay := file.FilePath
|
||||
filePathDisplay := filePath
|
||||
if filePathDisplay == "" {
|
||||
filePathDisplay = "<stdin>"
|
||||
}
|
||||
fileInfo := map[string]any{
|
||||
"file": map[string]string{"field": file.FieldName, "path": filePathDisplay},
|
||||
"file": map[string]string{"field": fileField, "path": filePathDisplay},
|
||||
}
|
||||
if file.FormFields != nil {
|
||||
fileInfo["form_fields"] = file.FormFields
|
||||
if formFields != nil {
|
||||
fileInfo["form_fields"] = formFields
|
||||
}
|
||||
fileInfo["options"] = []string{"WithFileUpload"}
|
||||
dr.Body(fileInfo)
|
||||
return WriteDryRun(dr, opts)
|
||||
dr.Set("as", string(request.As))
|
||||
dr.Set("appId", config.AppID)
|
||||
if config.UserOpenId != "" {
|
||||
dr.Set("userOpenId", config.UserOpenId)
|
||||
}
|
||||
fmt.Fprintln(w, "=== Dry Run ===")
|
||||
if format == "pretty" {
|
||||
fmt.Fprint(w, dr.Format())
|
||||
} else {
|
||||
output.PrintJson(w, dr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrintDryRun outputs a standardised dry-run summary using DryRunAPI.
|
||||
// When format is "pretty", outputs human-readable text; otherwise JSON.
|
||||
func PrintDryRun(request client.RawApiRequest, config *core.CliConfig, opts DryRunOutputOptions) error {
|
||||
dr := buildDryRunPreview(request, config)
|
||||
func PrintDryRun(w io.Writer, request client.RawApiRequest, config *core.CliConfig, format string) error {
|
||||
dr := NewDryRunAPI()
|
||||
switch request.Method {
|
||||
case "POST":
|
||||
dr.POST(request.URL)
|
||||
case "PUT":
|
||||
dr.PUT(request.URL)
|
||||
case "PATCH":
|
||||
dr.PATCH(request.URL)
|
||||
case "DELETE":
|
||||
dr.DELETE(request.URL)
|
||||
default:
|
||||
dr.GET(request.URL)
|
||||
}
|
||||
if len(request.Params) > 0 {
|
||||
dr.Params(request.Params)
|
||||
}
|
||||
if !util.IsNil(request.Data) {
|
||||
dr.Body(request.Data)
|
||||
}
|
||||
return WriteDryRun(dr, opts)
|
||||
}
|
||||
|
||||
// WriteDryRun emits a DryRunAPI using the shared dry-run output contract.
|
||||
// Identity may be empty; the envelope omits it rather than guessing.
|
||||
func WriteDryRun(dr *DryRunAPI, opts DryRunOutputOptions) error {
|
||||
if dr == nil {
|
||||
return errs.NewInternalError(errs.SubtypeUnknown, "dry-run produced no request preview")
|
||||
dr.Set("as", string(request.As))
|
||||
dr.Set("appId", config.AppID)
|
||||
if config.UserOpenId != "" {
|
||||
dr.Set("userOpenId", config.UserOpenId)
|
||||
}
|
||||
// The JqExpr guard is defensive: every entry point already rejects --jq
|
||||
// combined with --format pretty via output.ValidateJqFlags.
|
||||
if opts.Format == "pretty" && opts.JqExpr == "" {
|
||||
// A nil ErrOut only skips the banner decoration (mirroring
|
||||
// WriteSuccessEnvelope's warning path); the payload write to Out
|
||||
// must fail loudly rather than be silently discarded.
|
||||
if opts.ErrOut != nil {
|
||||
fmt.Fprintln(opts.ErrOut, "=== Dry Run ===")
|
||||
}
|
||||
// stdout carries its own marker so logs that drop stderr still show
|
||||
// this was a preview, not an executed request.
|
||||
fmt.Fprintln(opts.Out, "# dry-run: request not sent")
|
||||
fmt.Fprint(opts.Out, dr.Format())
|
||||
return nil
|
||||
fmt.Fprintln(w, "=== Dry Run ===")
|
||||
if format == "pretty" {
|
||||
fmt.Fprint(w, dr.Format())
|
||||
} else {
|
||||
output.PrintJson(w, dr)
|
||||
}
|
||||
return output.WriteSuccessEnvelope(dr, output.SuccessEnvelopeOptions{
|
||||
CommandPath: opts.CommandPath,
|
||||
Identity: string(opts.Identity),
|
||||
DryRun: true,
|
||||
JqExpr: opts.JqExpr,
|
||||
Out: opts.Out,
|
||||
ErrOut: opts.ErrOut,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -6,12 +6,9 @@ package cmdutil
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/client"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
)
|
||||
@@ -69,31 +66,11 @@ func TestDryRunAPI_ResolveURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunAPI_ResolveURLMatchesFullPlaceholderOnly(t *testing.T) {
|
||||
dr := NewDryRunAPI().
|
||||
GET("/open-apis/task/v2/tasks/:assignee_id").
|
||||
Set("assignee", "ou_bot")
|
||||
|
||||
text := dr.Format()
|
||||
if strings.Contains(text, "ou_bot_id") {
|
||||
t.Fatalf("prefix placeholder key corrupted longer token: %s", text)
|
||||
}
|
||||
if !strings.Contains(text, ":assignee_id") {
|
||||
t.Fatalf("missing unresolved placeholder, got: %s", text)
|
||||
}
|
||||
|
||||
dr.Set("assignee_id", "ou_abc/123")
|
||||
text = dr.Format()
|
||||
if !strings.Contains(text, "/open-apis/task/v2/tasks/ou_abc%2F123") {
|
||||
t.Fatalf("expected full placeholder replacement with path escaping, got: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunAPI_MarshalJSON(t *testing.T) {
|
||||
dr := NewDryRunAPI().
|
||||
Desc("test api").
|
||||
GET("/open-apis/test").
|
||||
Set("note", "audit")
|
||||
Set("as", "user")
|
||||
|
||||
data, err := json.Marshal(dr)
|
||||
if err != nil {
|
||||
@@ -106,8 +83,8 @@ func TestDryRunAPI_MarshalJSON(t *testing.T) {
|
||||
if m["description"] != "test api" {
|
||||
t.Errorf("expected description, got: %v", m["description"])
|
||||
}
|
||||
if m["note"] != "audit" {
|
||||
t.Errorf("expected note=audit, got: %v", m["note"])
|
||||
if m["as"] != "user" {
|
||||
t.Errorf("expected as=user, got: %v", m["as"])
|
||||
}
|
||||
api, ok := m["api"].([]interface{})
|
||||
if !ok || len(api) != 1 {
|
||||
@@ -146,67 +123,31 @@ func TestDryRunAPI_ExtraFieldsOnly(t *testing.T) {
|
||||
|
||||
func TestPrintDryRun_JSON(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
var errBuf bytes.Buffer
|
||||
err := PrintDryRun(client.RawApiRequest{
|
||||
err := PrintDryRun(&buf, client.RawApiRequest{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/test",
|
||||
As: "user",
|
||||
}, &core.CliConfig{AppID: "app123"}, DryRunOutputOptions{
|
||||
Format: "json",
|
||||
CommandPath: "lark-cli api",
|
||||
Identity: core.AsUser,
|
||||
Out: &buf,
|
||||
ErrOut: &errBuf,
|
||||
})
|
||||
}, &core.CliConfig{AppID: "app123"}, "json")
|
||||
if err != nil {
|
||||
t.Fatalf("PrintDryRun failed: %v", err)
|
||||
}
|
||||
out := buf.String()
|
||||
if strings.Contains(out, "=== Dry Run ===") {
|
||||
t.Fatalf("JSON stdout must not contain banner, got: %s", out)
|
||||
if !strings.Contains(out, "=== Dry Run ===") {
|
||||
t.Errorf("expected header, got: %s", out)
|
||||
}
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, out)
|
||||
}
|
||||
if env["ok"] != true || env["identity"] != "user" || env["dry_run"] != true {
|
||||
t.Fatalf("unexpected envelope: %#v", env)
|
||||
}
|
||||
data, ok := env["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("unexpected data: %#v", env["data"])
|
||||
}
|
||||
dctx, ok := data["context"].(map[string]interface{})
|
||||
if !ok || dctx["app_id"] != "app123" {
|
||||
t.Fatalf("unexpected data.context: %#v", data["context"])
|
||||
}
|
||||
if _, exists := data["as"]; exists {
|
||||
t.Fatalf("data.as must not appear; identity lives at the envelope top level: %#v", data)
|
||||
}
|
||||
api, ok := data["api"].([]interface{})
|
||||
if !ok || len(api) != 1 {
|
||||
t.Fatalf("api = %#v, want one call", data["api"])
|
||||
}
|
||||
call, ok := api[0].(map[string]interface{})
|
||||
if !ok || call["url"] != "/open-apis/test" {
|
||||
t.Fatalf("api[0] = %#v", api[0])
|
||||
if !strings.Contains(out, "app123") {
|
||||
t.Errorf("expected appId in output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintDryRun_Pretty(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
var errBuf bytes.Buffer
|
||||
err := PrintDryRun(client.RawApiRequest{
|
||||
err := PrintDryRun(&buf, client.RawApiRequest{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/test",
|
||||
Data: map[string]interface{}{"key": "val"},
|
||||
As: "bot",
|
||||
}, &core.CliConfig{AppID: "app456"}, DryRunOutputOptions{
|
||||
Format: "pretty",
|
||||
Identity: core.AsBot,
|
||||
Out: &buf,
|
||||
ErrOut: &errBuf,
|
||||
})
|
||||
}, &core.CliConfig{AppID: "app456"}, "pretty")
|
||||
if err != nil {
|
||||
t.Fatalf("PrintDryRun failed: %v", err)
|
||||
}
|
||||
@@ -214,136 +155,6 @@ func TestPrintDryRun_Pretty(t *testing.T) {
|
||||
if !strings.Contains(out, "POST /open-apis/test") {
|
||||
t.Errorf("expected POST line in pretty output, got: %s", out)
|
||||
}
|
||||
if !strings.HasPrefix(out, "# dry-run: request not sent\n") {
|
||||
t.Fatalf("pretty stdout should start with the dry-run marker, got: %s", out)
|
||||
}
|
||||
if strings.Contains(out, "=== Dry Run ===") {
|
||||
t.Fatalf("pretty stdout must not contain banner, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(errBuf.String(), "=== Dry Run ===") {
|
||||
t.Fatalf("pretty stderr should contain banner, got: %s", errBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintDryRun_WithJqUsesEnvelope(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
err := PrintDryRun(client.RawApiRequest{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/test",
|
||||
As: "bot",
|
||||
}, &core.CliConfig{AppID: "app123"}, DryRunOutputOptions{
|
||||
Format: "json",
|
||||
JqExpr: ".data.api[0].url",
|
||||
Identity: core.AsBot,
|
||||
Out: &buf,
|
||||
ErrOut: io.Discard,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PrintDryRun failed: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(buf.String()); got != "/open-apis/test" {
|
||||
t.Fatalf("jq output = %q, want /open-apis/test", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintDryRunWithFile_JSONEnvelope(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
err := PrintDryRunWithFile(client.RawApiRequest{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/drive/v1/files/upload_all",
|
||||
As: "bot",
|
||||
}, &core.CliConfig{AppID: "app123", UserOpenId: "ou_tester"}, DryRunOutputOptions{
|
||||
Format: "json",
|
||||
Identity: core.AsBot,
|
||||
Out: &buf,
|
||||
ErrOut: io.Discard,
|
||||
}, FileUploadMeta{FieldName: "file", FilePath: "report.txt", FormFields: map[string]any{"parent": "fld"}})
|
||||
if err != nil {
|
||||
t.Fatalf("PrintDryRunWithFile failed: %v", err)
|
||||
}
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
if env["dry_run"] != true {
|
||||
t.Fatalf("dry_run = %#v, want true", env["dry_run"])
|
||||
}
|
||||
data := env["data"].(map[string]interface{})
|
||||
api := data["api"].([]interface{})
|
||||
call := api[0].(map[string]interface{})
|
||||
body := call["body"].(map[string]interface{})
|
||||
file := body["file"].(map[string]interface{})
|
||||
if file["path"] != "report.txt" {
|
||||
t.Fatalf("file body = %#v", body)
|
||||
}
|
||||
dctx, ok := data["context"].(map[string]interface{})
|
||||
if !ok || dctx["app_id"] != "app123" || dctx["user_open_id"] != "ou_tester" {
|
||||
t.Fatalf("unexpected data.context: %#v", data["context"])
|
||||
}
|
||||
for _, legacy := range []string{"as", "appId", "userOpenId"} {
|
||||
if _, exists := data[legacy]; exists {
|
||||
t.Fatalf("legacy key %q must not appear in data: %#v", legacy, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintDryRun_MethodTranscribedVerbatim(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
err := PrintDryRun(client.RawApiRequest{
|
||||
Method: "OPTIONS",
|
||||
URL: "/open-apis/test",
|
||||
As: "bot",
|
||||
}, &core.CliConfig{AppID: "app123"}, DryRunOutputOptions{
|
||||
Format: "json",
|
||||
Identity: core.AsBot,
|
||||
Out: &buf,
|
||||
ErrOut: io.Discard,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PrintDryRun failed: %v", err)
|
||||
}
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
call := env["data"].(map[string]interface{})["api"].([]interface{})[0].(map[string]interface{})
|
||||
if call["method"] != "OPTIONS" {
|
||||
t.Fatalf("method = %#v, want OPTIONS transcribed verbatim (not coerced to GET)", call["method"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintDryRun_EmptyConfigOmitsContext(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
err := PrintDryRun(client.RawApiRequest{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/test",
|
||||
}, &core.CliConfig{}, DryRunOutputOptions{
|
||||
Format: "json",
|
||||
Out: &buf,
|
||||
ErrOut: io.Discard,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PrintDryRun failed: %v", err)
|
||||
}
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
data := env["data"].(map[string]interface{})
|
||||
if _, exists := data["context"]; exists {
|
||||
t.Fatalf("empty app/user context must be omitted entirely, got: %#v", data["context"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteDryRun_NilPreviewIsInternalError(t *testing.T) {
|
||||
err := WriteDryRun(nil, DryRunOutputOptions{Format: "json", Out: io.Discard})
|
||||
if err == nil {
|
||||
t.Fatal("WriteDryRun(nil) should fail instead of emitting an empty preview")
|
||||
}
|
||||
var internal *errs.InternalError
|
||||
if !errors.As(err, &internal) {
|
||||
t.Fatalf("expected *errs.InternalError, got %T: %v", err, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunFormatValue(t *testing.T) {
|
||||
|
||||
@@ -7,7 +7,6 @@ package output
|
||||
type Envelope struct {
|
||||
OK bool `json:"ok"`
|
||||
Identity string `json:"identity,omitempty"`
|
||||
DryRun bool `json:"dry_run,omitempty"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Meta *Meta `json:"meta,omitempty"`
|
||||
ContentSafetyAlert interface{} `json:"_content_safety_alert,omitempty"`
|
||||
|
||||
@@ -9,7 +9,6 @@ import "io"
|
||||
type SuccessEnvelopeOptions struct {
|
||||
CommandPath string
|
||||
Identity string
|
||||
DryRun bool
|
||||
JqExpr string
|
||||
Out io.Writer
|
||||
ErrOut io.Writer
|
||||
@@ -42,7 +41,6 @@ func WriteSuccessEnvelope(data interface{}, opts SuccessEnvelopeOptions) error {
|
||||
env := Envelope{
|
||||
OK: true,
|
||||
Identity: opts.Identity,
|
||||
DryRun: opts.DryRun,
|
||||
Data: data,
|
||||
Notice: GetNotice(),
|
||||
}
|
||||
|
||||
@@ -104,47 +104,6 @@ func TestWriteSuccessEnvelope_JqUsesEnvelope(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteSuccessEnvelope_DryRunMarker(t *testing.T) {
|
||||
var out strings.Builder
|
||||
|
||||
err := WriteSuccessEnvelope(map[string]interface{}{"api": []interface{}{}}, SuccessEnvelopeOptions{
|
||||
Identity: "bot",
|
||||
DryRun: true,
|
||||
Out: &out,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("WriteSuccessEnvelope() error = %v", err)
|
||||
}
|
||||
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(out.String()), &env); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\n%s", err, out.String())
|
||||
}
|
||||
if env["ok"] != true || env["identity"] != "bot" || env["dry_run"] != true {
|
||||
t.Fatalf("unexpected dry-run envelope: %#v", env)
|
||||
}
|
||||
if _, ok := env["data"].(map[string]interface{}); !ok {
|
||||
t.Fatalf("data = %#v, want object", env["data"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteSuccessEnvelope_DryRunJqUsesEnvelope(t *testing.T) {
|
||||
var out strings.Builder
|
||||
|
||||
err := WriteSuccessEnvelope(map[string]interface{}{"api": []interface{}{}}, SuccessEnvelopeOptions{
|
||||
Identity: "bot",
|
||||
DryRun: true,
|
||||
JqExpr: ".dry_run",
|
||||
Out: &out,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("WriteSuccessEnvelope() error = %v", err)
|
||||
}
|
||||
if strings.TrimSpace(out.String()) != "true" {
|
||||
t.Fatalf("jq output = %q, want true", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteSuccessEnvelope_JqWarnsWhenSafetyAlertFiltered(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONTENT_SAFETY_MODE", "warn")
|
||||
extcs.Register(&mockProvider{
|
||||
|
||||
@@ -878,23 +878,16 @@ func extractDryRunJSON(raw []byte) (facts.DryRunRequest, int, error) {
|
||||
var firstErr error
|
||||
for start >= 0 {
|
||||
var preview struct {
|
||||
API []facts.DryRunRequest `json:"api"`
|
||||
Data struct {
|
||||
API []facts.DryRunRequest `json:"api"`
|
||||
} `json:"data"`
|
||||
API []facts.DryRunRequest `json:"api"`
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw[start:]))
|
||||
if err := dec.Decode(&preview); err == nil {
|
||||
api := preview.API
|
||||
if len(api) == 0 {
|
||||
api = preview.Data.API
|
||||
}
|
||||
if len(api) == 0 {
|
||||
if len(preview.API) == 0 {
|
||||
if firstErr == nil {
|
||||
firstErr = errNoDryRunAPI
|
||||
}
|
||||
} else {
|
||||
return api[0], len(api), nil
|
||||
return preview.API[0], len(preview.API), nil
|
||||
}
|
||||
} else if firstErr == nil {
|
||||
firstErr = err
|
||||
|
||||
@@ -33,17 +33,6 @@ func TestExtractDryRunJSONSkipsBanner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDryRunJSONReadsSuccessEnvelope(t *testing.T) {
|
||||
raw := `{"ok":true,"dry_run":true,"data":{"api":[{"method":"GET","url":"/open-apis/test"}]}}`
|
||||
got, apiCallCount, err := extractDryRunJSON([]byte(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("extractDryRunJSON() error = %v", err)
|
||||
}
|
||||
if got.Method != "GET" || got.URL != "/open-apis/test" || apiCallCount != 1 {
|
||||
t.Fatalf("got request=%#v apiCallCount=%d, want enveloped GET and count 1", got, apiCallCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDryRunJSONSkipsBannerWithBraces(t *testing.T) {
|
||||
raw := "banner {not json}\n{\"api\":[{\"method\":\"GET\",\"url\":\"/open-apis/test\"}]}\n"
|
||||
got, apiCallCount, err := extractDryRunJSON([]byte(raw))
|
||||
|
||||
@@ -248,18 +248,10 @@ func TestLoadPlatformAutoApproveSet(t *testing.T) {
|
||||
|
||||
func TestLoadOverrideAutoApproveAllow(t *testing.T) {
|
||||
allowSet := LoadOverrideAutoApproveAllow()
|
||||
// recommend.allow special-cases scopes absent from scope_priorities.json
|
||||
// (application v7 is not in the platform catalog yet) so interactive
|
||||
// login's "common scopes" tier still offers them. Only the read scope is
|
||||
// admitted: write stays out of the recommended tier by design.
|
||||
if !allowSet["application:app_slash_command:read"] {
|
||||
t.Error("expected application:app_slash_command:read in override allow set")
|
||||
}
|
||||
if allowSet["application:app_slash_command:write"] {
|
||||
t.Error("write scope must NOT be in the recommended tier")
|
||||
}
|
||||
if len(allowSet) != 1 {
|
||||
t.Errorf("expected exactly 1 override allow entry, got %d", len(allowSet))
|
||||
// recommend.allow in scope_overrides.json is intentionally empty:
|
||||
// no scopes are special-cased into the auto-approve set anymore.
|
||||
if len(allowSet) != 0 {
|
||||
t.Errorf("expected empty override allow set, got %d entries", len(allowSet))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,7 @@
|
||||
"vc:meeting.meetingevent:read": 75
|
||||
},
|
||||
"recommend": {
|
||||
"allow": [
|
||||
"application:app_slash_command:read"
|
||||
],
|
||||
"allow": [],
|
||||
"deny": [
|
||||
"im:chat",
|
||||
"im:message.send_as_user"
|
||||
|
||||
@@ -3,10 +3,6 @@
|
||||
"en": { "title": "Approval", "description": "Approval instance, and task management" },
|
||||
"zh": { "title": "审批", "description": "审批实例、审批任务管理" }
|
||||
},
|
||||
"application": {
|
||||
"en": { "title": "Application", "description": "Open Platform app self-management: slash commands for the currently bound app" },
|
||||
"zh": { "title": "应用管理", "description": "开放平台应用自管理:当前绑定应用的斜杠指令管理" }
|
||||
},
|
||||
"apps": {
|
||||
"en": { "title": "Apps", "description": "Develop, deploy HTML, web pages and applications" },
|
||||
"zh": { "title": "应用", "description": "开发、部署 HTML、Web 页面和应用" }
|
||||
|
||||
@@ -65,7 +65,7 @@ func safePath(raw, flagName string) (string, error) {
|
||||
}
|
||||
|
||||
if isAbsolutePath(raw) {
|
||||
return "", fmt.Errorf("%s must be a relative path within the current directory, got %q (hint: use a relative path like ./filename; flags that support stdin can read an out-of-tree file via '-' instead)", flagName, raw)
|
||||
return "", fmt.Errorf("%s must be a relative path within the current directory, got %q (hint: cd to the target directory first, or use a relative path like ./filename)", flagName, raw)
|
||||
}
|
||||
|
||||
path := filepath.Clean(raw)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@larksuite/cli",
|
||||
"version": "1.0.70",
|
||||
"version": "1.0.68",
|
||||
"description": "The official CLI for Lark/Feishu open platform",
|
||||
"bin": {
|
||||
"lark-cli": "scripts/run.js"
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package application provides shortcuts for Open Platform app
|
||||
// self-management (slash commands of the current bound app).
|
||||
package application
|
||||
|
||||
import "github.com/larksuite/cli/shortcuts/common"
|
||||
|
||||
// Shortcuts returns all shortcuts of the application domain.
|
||||
func Shortcuts() []common.Shortcut {
|
||||
return []common.Shortcut{
|
||||
SlashCommandList,
|
||||
SlashCommandCreate,
|
||||
SlashCommandUpdate,
|
||||
SlashCommandDelete,
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
)
|
||||
|
||||
// slashCommandBasePath is the raw v7 endpoint (not in meta_data.json / SDK).
|
||||
const slashCommandBasePath = "/open-apis/application/v7/app_slash_commands"
|
||||
|
||||
// clientCacheHint is printed to stderr after every successful write.
|
||||
const clientCacheHint = "note: changes take ~5 minutes to appear in Feishu clients (client-side cache); the server state is already updated - list reflects it immediately."
|
||||
|
||||
// parseDescriptionI18n parses repeated --description-i18n values ("<lang>=<text>",
|
||||
// split on the FIRST '='). Returns nil for empty input. Duplicate langs rejected.
|
||||
func parseDescriptionI18n(values []string) (map[string]string, error) {
|
||||
if len(values) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
m := make(map[string]string, len(values))
|
||||
for _, v := range values {
|
||||
idx := strings.Index(v, "=")
|
||||
if idx <= 0 || idx == len(v)-1 {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"invalid --description-i18n value %q: expected <lang>=<text> (e.g. zh_cn=你好)", v).
|
||||
WithParam("--description-i18n")
|
||||
}
|
||||
lang := strings.TrimSpace(v[:idx])
|
||||
text := v[idx+1:]
|
||||
if lang == "" || strings.TrimSpace(text) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"invalid --description-i18n value %q: language and text must be non-empty", v).
|
||||
WithParam("--description-i18n")
|
||||
}
|
||||
if _, dup := m[lang]; dup {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"duplicate language %q in --description-i18n", lang).
|
||||
WithParam("--description-i18n")
|
||||
}
|
||||
m[lang] = text
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// validateCommandName rejects empty and slash-prefixed command names.
|
||||
func validateCommandName(name, flagName string) error {
|
||||
trimmed := strings.TrimSpace(name)
|
||||
if trimmed == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"%s must not be empty", flagName).WithParam(flagName)
|
||||
}
|
||||
if strings.HasPrefix(trimmed, "/") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"%s must not start with \"/\" - the slash is implied (use %q)",
|
||||
flagName, strings.TrimPrefix(trimmed, "/")).WithParam(flagName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// encodeCommandIDPathSegment applies the same normalization and escaping to
|
||||
// command IDs in dry-run output and real requests.
|
||||
func encodeCommandIDPathSegment(id string) string {
|
||||
return validate.EncodePathSegment(strings.TrimSpace(id))
|
||||
}
|
||||
|
||||
// buildSlashCommandBody assembles a create/update request body. Only provided
|
||||
// fields are included: PATCH is field-level partial (absent top-level fields
|
||||
// are preserved server-side; a provided i18n map REPLACES the whole map).
|
||||
// icon sits at the top level, sibling of description (verified live; the
|
||||
// official create sample nesting icon inside description is a doc bug).
|
||||
func buildSlashCommandBody(command, description string, i18n map[string]string, iconKey string) map[string]interface{} {
|
||||
body := map[string]interface{}{}
|
||||
if command != "" {
|
||||
body["command"] = command
|
||||
}
|
||||
if description != "" || len(i18n) > 0 {
|
||||
desc := map[string]interface{}{}
|
||||
if description != "" {
|
||||
desc["default_value"] = description
|
||||
}
|
||||
if len(i18n) > 0 {
|
||||
desc["i18n"] = i18n
|
||||
}
|
||||
body["description"] = desc
|
||||
}
|
||||
if iconKey != "" {
|
||||
body["icon"] = map[string]interface{}{"icon_key": iconKey}
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// isCommandExists reports whether err is the server-side name-collision error
|
||||
// (code=40000000, message contains "command already exists"; verified live).
|
||||
func isCommandExists(err error) bool {
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return p.Code == 40000000 && strings.Contains(p.Message, "command already exists")
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
func TestParseDescriptionI18n_OK(t *testing.T) {
|
||||
m, err := parseDescriptionI18n([]string{"zh_cn=你好", "en_us=Hello=World"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if m["zh_cn"] != "你好" {
|
||||
t.Errorf("zh_cn = %q", m["zh_cn"])
|
||||
}
|
||||
// 只按首个 = 分割:值内可含 =
|
||||
if m["en_us"] != "Hello=World" {
|
||||
t.Errorf("en_us = %q", m["en_us"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDescriptionI18n_Empty(t *testing.T) {
|
||||
m, err := parseDescriptionI18n(nil)
|
||||
if err != nil || m != nil {
|
||||
t.Fatalf("nil input: m=%v err=%v", m, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDescriptionI18n_BadFormat(t *testing.T) {
|
||||
for _, bad := range []string{"zh_cn", "=text", "zh_cn=", " =x"} {
|
||||
_, err := parseDescriptionI18n([]string{bad})
|
||||
if err == nil {
|
||||
t.Errorf("%q: expected error", bad)
|
||||
continue
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Errorf("%q: expected validation problem, got %v", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDescriptionI18n_DuplicateLang(t *testing.T) {
|
||||
_, err := parseDescriptionI18n([]string{"zh_cn=a", "zh_cn=b"})
|
||||
if err == nil {
|
||||
t.Fatal("expected duplicate language error")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected validation/invalid_argument, got %v", err)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--description-i18n" {
|
||||
t.Fatalf("expected param --description-i18n, got %#v", validationErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCommandName(t *testing.T) {
|
||||
if err := validateCommandName("greet", "--command"); err != nil {
|
||||
t.Fatalf("greet: %v", err)
|
||||
}
|
||||
for _, bad := range []string{"", " ", "/greet"} {
|
||||
if err := validateCommandName(bad, "--command"); err == nil {
|
||||
t.Errorf("%q: expected error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSlashCommandBody(t *testing.T) {
|
||||
body := buildSlashCommandBody("greet", "hi", map[string]string{"zh_cn": "你好"}, "skill_outlined")
|
||||
if body["command"] != "greet" {
|
||||
t.Errorf("command = %v", body["command"])
|
||||
}
|
||||
desc := body["description"].(map[string]interface{})
|
||||
if desc["default_value"] != "hi" {
|
||||
t.Errorf("default_value = %v", desc["default_value"])
|
||||
}
|
||||
if desc["i18n"].(map[string]string)["zh_cn"] != "你好" {
|
||||
t.Errorf("i18n = %v", desc["i18n"])
|
||||
}
|
||||
// icon 与 description 顶层平级(实测钉死,文档 create 示例是笔误)
|
||||
if body["icon"].(map[string]interface{})["icon_key"] != "skill_outlined" {
|
||||
t.Errorf("icon = %v", body["icon"])
|
||||
}
|
||||
// partial:不提供的字段不出现(PATCH 语义依赖)
|
||||
partial := buildSlashCommandBody("", "", nil, "skill_outlined")
|
||||
if _, has := partial["command"]; has {
|
||||
t.Error("empty command must be omitted")
|
||||
}
|
||||
if _, has := partial["description"]; has {
|
||||
t.Error("empty description must be omitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsCommandExists(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "matching code and message",
|
||||
err: errs.NewAPIError(errs.SubtypeUnknown,
|
||||
"Invalid Param 'command'. command already exists.").WithCode(40000000),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "same message with different code",
|
||||
err: errs.NewAPIError(errs.SubtypeUnknown,
|
||||
"Invalid Param 'command'. command already exists.").WithCode(40000031),
|
||||
},
|
||||
{
|
||||
name: "same code with different message",
|
||||
err: errs.NewAPIError(errs.SubtypeUnknown,
|
||||
"Invalid Param 'icon_key'. icon_key is invalid.").WithCode(40000000),
|
||||
},
|
||||
{name: "nil error"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isCommandExists(tt.err); got != tt.want {
|
||||
t.Fatalf("isCommandExists() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSlashCommandShortcuts_SharedScopesAcrossIdentities locks in the
|
||||
// reversal of the OAuth-isolation design: all four slash-command shortcuts
|
||||
// declare identical scopes for the bot and user identities (plain Scopes /
|
||||
// ConditionalScopes, no per-identity overrides), so a user-identity
|
||||
// pre-flight sees the same scope set a bot identity would.
|
||||
func TestSlashCommandShortcuts_SharedScopesAcrossIdentities(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
shortcut common.Shortcut
|
||||
wantScope string
|
||||
wantConditional string
|
||||
hasConditional bool
|
||||
}{
|
||||
{
|
||||
name: "list",
|
||||
shortcut: SlashCommandList,
|
||||
wantScope: "application:app_slash_command:read",
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
shortcut: SlashCommandCreate,
|
||||
wantScope: "application:app_slash_command:write",
|
||||
wantConditional: "application:app_slash_command:read",
|
||||
hasConditional: true,
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
shortcut: SlashCommandUpdate,
|
||||
wantScope: "application:app_slash_command:write",
|
||||
wantConditional: "application:app_slash_command:read",
|
||||
hasConditional: true,
|
||||
},
|
||||
{
|
||||
name: "delete",
|
||||
shortcut: SlashCommandDelete,
|
||||
wantScope: "application:app_slash_command:write",
|
||||
wantConditional: "application:app_slash_command:read",
|
||||
hasConditional: true,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
for _, identity := range []string{"user", "bot"} {
|
||||
declared := tc.shortcut.DeclaredScopesForIdentity(identity)
|
||||
if !containsStr(declared, tc.wantScope) {
|
||||
t.Errorf("%s: DeclaredScopesForIdentity(%q) = %v, want to contain %q", tc.name, identity, declared, tc.wantScope)
|
||||
}
|
||||
if tc.hasConditional && !containsStr(declared, tc.wantConditional) {
|
||||
t.Errorf("%s: DeclaredScopesForIdentity(%q) = %v, want to contain conditional %q", tc.name, identity, declared, tc.wantConditional)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func containsStr(list []string, want string) bool {
|
||||
for _, v := range list {
|
||||
if v == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// SlashCommandCreate registers a new slash command on the current bound app.
|
||||
var SlashCommandCreate = common.Shortcut{
|
||||
Service: "application",
|
||||
Command: "+slash-command-create",
|
||||
Description: "Register a slash command (/ command) on the current bound Open Platform app; --force converts a name collision into an update (idempotent re-run)",
|
||||
Risk: "write",
|
||||
Scopes: []string{"application:app_slash_command:write"},
|
||||
ConditionalScopes: []string{
|
||||
"application:app_slash_command:read", // only the --force collision path lists to resolve the id
|
||||
},
|
||||
AuthTypes: []string{"bot", "user"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "command", Desc: "command name WITHOUT the leading slash (server enforces uniqueness per app; max 100 commands)", Required: true},
|
||||
{Name: "description", Desc: "default description shown in the client command panel (description.default_value)", Required: true},
|
||||
{Name: "description-i18n", Type: "string_array", Desc: "localized description, repeatable, format <lang>=<text> (e.g. zh_cn=发送问候); language codes are passed through to the server"},
|
||||
{Name: "icon-key", Desc: "icon key (server default: skill_outlined; invalid keys are rejected server-side with code 40000031)"},
|
||||
{Name: "force", Type: "bool", Desc: "on name collision, resolve the existing command by name and update it in place"},
|
||||
},
|
||||
Tips: []string{
|
||||
`lark-cli application +slash-command-create --command greet --description "say hi" --description-i18n zh_cn=问候 --as bot`,
|
||||
"changes take ~5 minutes to appear in clients (client-side cache); the server updates immediately",
|
||||
"user identity needs explicit authorization first: lark-cli auth login --scope application:app_slash_command:write",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
if err := validateCommandName(runtime.Str("command"), "--command"); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(strings.TrimSpace(runtime.Str("description"))) == 0 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--description must not be blank").WithParam("--description")
|
||||
}
|
||||
if _, err := parseDescriptionI18n(runtime.StrArray("description-i18n")); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
i18n, err := parseDescriptionI18n(runtime.StrArray("description-i18n"))
|
||||
if err != nil {
|
||||
// The CLI validates first; keep this guard for direct DryRun callers.
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
body := buildSlashCommandBody(name, runtime.Str("description"), i18n, runtime.Str("icon-key"))
|
||||
d := common.NewDryRunAPI().
|
||||
Desc("Create a slash command on the current bound app").
|
||||
POST(slashCommandBasePath).
|
||||
Body(body)
|
||||
if runtime.Bool("force") {
|
||||
d.Desc("--force: on 'command already exists' (code 40000000), GET list to resolve command_id then PATCH the same body")
|
||||
}
|
||||
return d
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
i18n, err := parseDescriptionI18n(runtime.StrArray("description-i18n"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body := buildSlashCommandBody(name, runtime.Str("description"), i18n, runtime.Str("icon-key"))
|
||||
|
||||
data, err := runtime.CallAPITyped("POST", slashCommandBasePath, nil, body)
|
||||
action := "created"
|
||||
if err != nil {
|
||||
if !isCommandExists(err) {
|
||||
return err
|
||||
}
|
||||
if !runtime.Bool("force") {
|
||||
p, _ := errs.ProblemOf(err)
|
||||
rewrapped := errs.NewAPIError(errs.SubtypeAlreadyExists, "slash command %q already exists", name).
|
||||
WithHint("rerun with --force to update it, or use `lark-cli application +slash-command-update --command %q`", name).
|
||||
WithCause(err)
|
||||
if p.Code != 0 {
|
||||
rewrapped = rewrapped.WithCode(p.Code)
|
||||
}
|
||||
if p.LogID != "" {
|
||||
rewrapped = rewrapped.WithLogID(p.LogID)
|
||||
}
|
||||
return rewrapped
|
||||
}
|
||||
// --force: name collision -> resolve id -> PATCH (idempotent re-run).
|
||||
id, rerr := resolveCommandID(runtime, name)
|
||||
if rerr != nil {
|
||||
return rerr
|
||||
}
|
||||
patchBody := buildSlashCommandBody("", runtime.Str("description"), i18n, runtime.Str("icon-key"))
|
||||
data, err = runtime.CallAPITyped("PATCH", slashCommandBasePath+"/"+encodeCommandIDPathSegment(id), nil, patchBody)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
action = "updated"
|
||||
}
|
||||
if data == nil {
|
||||
data = map[string]interface{}{}
|
||||
}
|
||||
data["action"] = action
|
||||
fmt.Fprintln(runtime.IO().ErrOut, clientCacheHint)
|
||||
runtime.OutFormat(data, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s /%v (command_id: %v)\n", action, data["command"], data["command_id"])
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func createOKStub() *httpmock.Stub {
|
||||
return &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/application/v7/app_slash_commands",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": sampleItem("greet", "id-new"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func createConflictStub() *httpmock.Stub {
|
||||
return &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/application/v7/app_slash_commands",
|
||||
Body: map[string]interface{}{
|
||||
"code": 40000000, "msg": "Invalid Param 'command'. command already exists.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func patchOKStub(id string) *httpmock.Stub {
|
||||
return &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/application/v7/app_slash_commands/" + id,
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": sampleItem("greet", id),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_OK(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(createOKStub())
|
||||
|
||||
err := mountAndRun(t, SlashCommandCreate, []string{"+slash-command-create",
|
||||
"--command", "greet", "--description", "hi",
|
||||
"--description-i18n", "zh_cn=你好", "--description-i18n", "en_us=Hello",
|
||||
"--icon-key", "skill_outlined", "--format", "json", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v\n%s", err, stdout.String())
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
if data["action"] != "created" {
|
||||
t.Fatalf("action = %v", data["action"])
|
||||
}
|
||||
if data["command_id"] != "id-new" {
|
||||
t.Fatalf("command_id = %v", data["command_id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_ValidateRejects(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
cases := [][]string{
|
||||
{"+slash-command-create", "--command", "/greet", "--description", "hi", "--as", "bot"},
|
||||
{"+slash-command-create", "--command", "greet", "--description", "hi", "--description-i18n", "bad", "--as", "bot"},
|
||||
{"+slash-command-create", "--command", "greet", "--description", "hi", "--description-i18n", "zh_cn=a", "--description-i18n", "zh_cn=b", "--as", "bot"},
|
||||
{"+slash-command-create", "--command", "greet", "--description", " ", "--as", "bot"},
|
||||
}
|
||||
for i, args := range cases {
|
||||
err := mountAndRun(t, SlashCommandCreate, args, f, stdout)
|
||||
if err == nil {
|
||||
t.Errorf("case %d: expected validation error", i)
|
||||
continue
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryValidation {
|
||||
t.Errorf("case %d: expected validation problem, got %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_ConflictNoForce(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(createConflictStub())
|
||||
|
||||
err := mountAndRun(t, SlashCommandCreate, []string{"+slash-command-create",
|
||||
"--command", "greet", "--description", "hi", "--as", "bot"}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected conflict error")
|
||||
}
|
||||
p, _ := errs.ProblemOf(err)
|
||||
if p == nil || p.Category != errs.CategoryAPI || p.Subtype != errs.SubtypeAlreadyExists || p.Code != 40000000 {
|
||||
t.Fatalf("expected api/already_exists code 40000000, got %#v", p)
|
||||
}
|
||||
if !strings.Contains(p.Hint, "--force") || !strings.Contains(p.Hint, "+slash-command-update") {
|
||||
t.Fatalf("hint must offer --force and update, got %q", p.Hint)
|
||||
}
|
||||
var apiErr *errs.APIError
|
||||
if !errors.As(err, &apiErr) {
|
||||
t.Fatalf("rewrapped error must be *errs.APIError, got %T", err)
|
||||
}
|
||||
if errors.Unwrap(apiErr) == nil {
|
||||
t.Fatal("rewrapped conflict error must preserve the original cause via WithCause")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_ForceConvertsToUpdate(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(createConflictStub())
|
||||
reg.Register(listStub([]interface{}{sampleItem("greet", "id-exist")}))
|
||||
reg.Register(patchOKStub("id-exist"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandCreate, []string{"+slash-command-create",
|
||||
"--command", "greet", "--description", "hi2", "--force", "--format", "json", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
if data["action"] != "updated" {
|
||||
t.Fatalf("action = %v (force must convert to update)", data["action"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_TrimsCommandBeforeCreateAndForceResolution(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
conflict := createConflictStub()
|
||||
reg.Register(conflict)
|
||||
reg.Register(listStub([]interface{}{sampleItem("greet", "id-exist")}))
|
||||
reg.Register(patchOKStub("id-exist"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandCreate, []string{"+slash-command-create",
|
||||
"--command", " greet ", "--description", "hi", "--force", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var body map[string]interface{}
|
||||
if err := json.Unmarshal(conflict.CapturedBody, &body); err != nil {
|
||||
t.Fatalf("decode captured create body: %v", err)
|
||||
}
|
||||
if body["command"] != "greet" {
|
||||
t.Fatalf("command = %q, want trimmed value %q", body["command"], "greet")
|
||||
}
|
||||
}
|
||||
|
||||
func createIconInvalidStub() *httpmock.Stub {
|
||||
return &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/application/v7/app_slash_commands",
|
||||
Body: map[string]interface{}{
|
||||
"code": 40000031, "msg": "Invalid Param 'icon_key'. icon_key is invalid.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestSlashCommandCreate_ForceDoesNotConvertNonConflict guards against --force
|
||||
// blindly treating ANY POST failure as a name collision: only the
|
||||
// "command already exists" (40000000) shape may fall through to the
|
||||
// GET+PATCH idempotent-update path. No PATCH stub is registered here, so if
|
||||
// the code mistakenly attempted a PATCH, the httpmock registry would fail
|
||||
// the unexpected request and surface a different (registry) error instead
|
||||
// of the original icon_key failure asserted below.
|
||||
func TestSlashCommandCreate_ForceDoesNotConvertNonConflict(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(createIconInvalidStub())
|
||||
|
||||
err := mountAndRun(t, SlashCommandCreate, []string{"+slash-command-create",
|
||||
"--command", "greet", "--description", "hi", "--icon-key", "bogus", "--force", "--as", "bot"}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected the original icon_key error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryAPI || p.Subtype == errs.SubtypeAlreadyExists || p.Code != 40000031 {
|
||||
t.Fatalf("expected original API error code 40000031 without collision reclassification, got %#v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_DryRun(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
if err := mountAndRun(t, SlashCommandCreate, []string{"+slash-command-create",
|
||||
"--command", "greet", "--description", "hi", "--icon-key", "skill_outlined", "--dry-run", "--as", "bot"}, f, stdout); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "POST") || !strings.Contains(out, slashCommandBasePath) {
|
||||
t.Fatalf("dry-run must show POST path: %s", out)
|
||||
}
|
||||
// icon 顶层:dry-run body 里 icon 不嵌套在 description 内
|
||||
if !strings.Contains(out, "icon_key") {
|
||||
t.Fatalf("dry-run must include body: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandCreate_ForceHelpHasNoMetavar(t *testing.T) {
|
||||
parent := &cobra.Command{Use: "application"}
|
||||
SlashCommandCreate.Mount(parent, &cmdutil.Factory{})
|
||||
cmd := parent.Commands()[0]
|
||||
forceFlag := cmd.Flags().Lookup("force")
|
||||
if forceFlag == nil {
|
||||
t.Fatal("missing --force flag")
|
||||
}
|
||||
placeholder, usage := pflag.UnquoteUsage(forceFlag)
|
||||
if placeholder != "" {
|
||||
t.Fatalf("boolean --force must not render a value placeholder, got %q", placeholder)
|
||||
}
|
||||
if !strings.Contains(usage, "update it in place") || strings.Contains(usage, "gh ") {
|
||||
t.Fatalf("unexpected --force help: %q", usage)
|
||||
}
|
||||
if help := cmd.Flags().FlagUsages(); !strings.Contains(help, "--force") || !strings.Contains(help, "update it in place") {
|
||||
t.Fatalf("rendered help missing --force description:\n%s", help)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// SlashCommandDelete removes a slash command (irreversible; command_id is not
|
||||
// reused - recreating the same name yields a NEW id).
|
||||
var SlashCommandDelete = common.Shortcut{
|
||||
Service: "application",
|
||||
Command: "+slash-command-delete",
|
||||
Description: "Delete a slash command from the current bound app (high-risk: irreversible; recreating the same name yields a new command_id)",
|
||||
Risk: "high-risk-write",
|
||||
Scopes: []string{"application:app_slash_command:write"},
|
||||
ConditionalScopes: []string{
|
||||
"application:app_slash_command:read", // only the --command by-name path
|
||||
},
|
||||
AuthTypes: []string{"bot", "user"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "command-id", Desc: "target command_id; mutually exclusive with --command"},
|
||||
{Name: "command", Desc: "target command name WITHOUT leading slash (resolved via live list, needs read scope); mutually exclusive with --command-id"},
|
||||
},
|
||||
Tips: []string{
|
||||
"lark-cli application +slash-command-delete --command greet --yes --as bot",
|
||||
"deleted commands may linger in clients for ~5 minutes (client cache)",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
id := strings.TrimSpace(runtime.Str("command-id"))
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
if (id == "") == (name == "") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"provide exactly one of --command-id or --command").WithParam("--command-id")
|
||||
}
|
||||
if name != "" {
|
||||
return validateCommandName(name, "--command")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
d := common.NewDryRunAPI().Desc("HIGH-RISK: delete a slash command (irreversible; same-name recreate gets a NEW command_id)")
|
||||
target := strings.TrimSpace(runtime.Str("command-id"))
|
||||
if target == "" {
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
d.GET(slashCommandBasePath).
|
||||
Desc(fmt.Sprintf("resolve command_id by name %q via GET list first", name))
|
||||
target = "<resolved_command_id>"
|
||||
} else {
|
||||
target = encodeCommandIDPathSegment(target)
|
||||
}
|
||||
return d.DELETE(slashCommandBasePath + "/" + target)
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
id := strings.TrimSpace(runtime.Str("command-id"))
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
if id == "" {
|
||||
resolved, err := resolveCommandID(runtime, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id = resolved
|
||||
}
|
||||
if _, err := runtime.CallAPITyped("DELETE", slashCommandBasePath+"/"+encodeCommandIDPathSegment(id), nil, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
out := map[string]interface{}{"action": "deleted", "command_id": id}
|
||||
if name != "" {
|
||||
out["command"] = name
|
||||
}
|
||||
fmt.Fprintln(runtime.IO().ErrOut, clientCacheHint)
|
||||
fmt.Fprintln(runtime.IO().ErrOut, "note: recreating the same command name will yield a NEW command_id.")
|
||||
runtime.OutFormat(out, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "deleted command_id %s\n", id)
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
func deleteOKStub(id string) *httpmock.Stub {
|
||||
return &httpmock.Stub{
|
||||
Method: "DELETE",
|
||||
URL: slashCommandBasePath + "/" + id,
|
||||
Body: map[string]interface{}{"code": 0, "msg": "success", "data": map[string]interface{}{}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandDelete_RequiresYes(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
err := mountAndRun(t, SlashCommandDelete, []string{"+slash-command-delete",
|
||||
"--command-id", "id1", "--as", "bot"}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected confirmation_required without --yes")
|
||||
}
|
||||
if errs.CategoryOf(err) != errs.CategoryConfirmation {
|
||||
t.Fatalf("expected confirmation category, got %v (%v)", errs.CategoryOf(err), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandDelete_ByIDWithYes(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(deleteOKStub("id1"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandDelete, []string{"+slash-command-delete",
|
||||
"--command-id", "id1", "--yes", "--format", "json", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
// 上游 DELETE 返回空对象;CLI 必须补 action/command_id(写操作返回资源 ID)
|
||||
if data["action"] != "deleted" || data["command_id"] != "id1" {
|
||||
t.Fatalf("data = %v", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandDelete_ByNameWithYes(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(listStub([]interface{}{sampleItem("greet", "id7")}))
|
||||
reg.Register(deleteOKStub("id7"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandDelete, []string{"+slash-command-delete",
|
||||
"--command", "greet", "--yes", "--format", "json", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
if data["command"] != "greet" || data["command_id"] != "id7" {
|
||||
t.Fatalf("data = %v", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandDelete_ByNameDryRun(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
|
||||
err := mountAndRun(t, SlashCommandDelete, []string{"+slash-command-delete",
|
||||
"--command", "greet", "--dry-run", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var envlp struct {
|
||||
Data struct {
|
||||
Description string `json:"description"`
|
||||
API []struct {
|
||||
Desc string `json:"desc"`
|
||||
Method string `json:"method"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envlp); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
got := envlp.Data
|
||||
if !strings.Contains(got.Description, "HIGH-RISK") || strings.Contains(got.Description, "resolve command_id") {
|
||||
t.Fatalf("top-level description must contain only the risk context: %q", got.Description)
|
||||
}
|
||||
if len(got.API) != 2 || got.API[0].Method != "GET" || !strings.Contains(got.API[0].Desc, "resolve command_id") {
|
||||
t.Fatalf("first call must describe name resolution: %#v", got.API)
|
||||
}
|
||||
if got.API[1].Method != "DELETE" || strings.Contains(got.API[1].Desc, "resolve command_id") {
|
||||
t.Fatalf("second call must be the delete without the resolve description: %#v", got.API)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandDelete_Validate(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
for _, args := range [][]string{
|
||||
{"+slash-command-delete", "--yes", "--as", "bot"},
|
||||
{"+slash-command-delete", "--command-id", "id1", "--command", "greet", "--yes", "--as", "bot"},
|
||||
} {
|
||||
err := mountAndRun(t, SlashCommandDelete, args, f, stdout)
|
||||
if err == nil {
|
||||
t.Errorf("%v: expected validation error", args)
|
||||
continue
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Errorf("%v: expected validation problem, got %v", args, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandDelete_ByIDEncodesTrimmedPathSegment(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(deleteOKStub("id%2Fwith%20space%3Fx"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandDelete, []string{"+slash-command-delete",
|
||||
"--command-id", " id/with space?x ", "--yes", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// SlashCommandList lists all slash commands of the current bound app.
|
||||
var SlashCommandList = common.Shortcut{
|
||||
Service: "application",
|
||||
Command: "+slash-command-list",
|
||||
Description: "List all slash commands (/ commands) registered on the currently bound Open Platform app; source of command_id for update/delete",
|
||||
Risk: "read",
|
||||
Scopes: []string{"application:app_slash_command:read"},
|
||||
AuthTypes: []string{"bot", "user"},
|
||||
Tips: []string{
|
||||
"lark-cli application +slash-command-list --as bot",
|
||||
"user identity needs explicit authorization first: lark-cli auth login --scope application:app_slash_command:read",
|
||||
"the upstream API returns all commands at once (max 100 per app, no pagination)",
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return common.NewDryRunAPI().
|
||||
Desc("List all slash commands of the current bound app (read-only)").
|
||||
GET(slashCommandBasePath)
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
data, err := runtime.CallAPITyped("GET", slashCommandBasePath, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, _ := data["items"].([]interface{})
|
||||
if items == nil {
|
||||
items = []interface{}{}
|
||||
}
|
||||
out := map[string]interface{}{"items": items, "count": len(items)}
|
||||
runtime.OutFormat(out, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%d slash command(s)\n", len(items))
|
||||
for _, it := range items {
|
||||
m, ok := it.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
desc := ""
|
||||
if d, ok := m["description"].(map[string]interface{}); ok {
|
||||
desc, _ = d["default_value"].(string)
|
||||
}
|
||||
fmt.Fprintf(w, " /%v\t%v\t%s\n", m["command"], m["command_id"], desc)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func appTestConfig() *core.CliConfig {
|
||||
return &core.CliConfig{AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu}
|
||||
}
|
||||
|
||||
// mountAndRun mounts the shortcut under a parent cobra command and runs it.
|
||||
// Mirrors shortcuts/contact tests.
|
||||
func mountAndRun(t *testing.T, s common.Shortcut, args []string, f *cmdutil.Factory, stdout *bytes.Buffer) error {
|
||||
t.Helper()
|
||||
parent := &cobra.Command{Use: "application"}
|
||||
s.Mount(parent, f)
|
||||
parent.SetArgs(args)
|
||||
parent.SilenceErrors = true
|
||||
parent.SilenceUsage = true
|
||||
if stdout != nil {
|
||||
stdout.Reset()
|
||||
}
|
||||
return parent.Execute()
|
||||
}
|
||||
|
||||
func listStub(items []interface{}) *httpmock.Stub {
|
||||
return &httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/application/v7/app_slash_commands",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": map[string]interface{}{"items": items},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func sampleItem(name, id string) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"command": name, "command_id": id,
|
||||
"create_time": "1783318553", "update_time": "1783318553",
|
||||
"description": map[string]interface{}{"default_value": "desc of " + name},
|
||||
"icon": map[string]interface{}{"icon_key": "skill_outlined"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandList_JSON(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(listStub([]interface{}{sampleItem("greet", "id1"), sampleItem("weather", "id2")}))
|
||||
|
||||
if err := mountAndRun(t, SlashCommandList, []string{"+slash-command-list", "--format", "json", "--as", "bot"}, f, stdout); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v\n%s", err, stdout.String())
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
items := data["items"].([]interface{})
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("items = %d", len(items))
|
||||
}
|
||||
if data["count"] != float64(2) {
|
||||
t.Fatalf("count = %v", data["count"])
|
||||
}
|
||||
first := items[0].(map[string]interface{})
|
||||
for _, k := range []string{"command", "command_id", "description", "icon", "create_time", "update_time"} {
|
||||
if _, ok := first[k]; !ok {
|
||||
t.Errorf("missing item key %q", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandList_Empty(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(listStub(nil))
|
||||
|
||||
if err := mountAndRun(t, SlashCommandList, []string{"+slash-command-list", "--format", "json", "--as", "bot"}, f, stdout); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
items, ok := data["items"].([]interface{})
|
||||
if !ok || len(items) != 0 {
|
||||
t.Fatalf("empty list must be [] not %v", data["items"])
|
||||
}
|
||||
if data["count"] != float64(0) {
|
||||
t.Fatalf("count = %v", data["count"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandList_DryRun(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
if err := mountAndRun(t, SlashCommandList, []string{"+slash-command-list", "--dry-run", "--as", "bot"}, f, stdout); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "/open-apis/application/v7/app_slash_commands") || !strings.Contains(out, "GET") {
|
||||
t.Fatalf("dry-run must show GET path, got %s", out)
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// matchCommandID finds the command_id of the item whose "command" equals
|
||||
// name (exact match - the server enforces name uniqueness, so first hit is the
|
||||
// only hit).
|
||||
func matchCommandID(items []interface{}, name string) string {
|
||||
for _, it := range items {
|
||||
m, ok := it.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if m["command"] == name {
|
||||
id, _ := m["command_id"].(string)
|
||||
if id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// commandNotFoundError reports a resolution miss against the live list as an
|
||||
// API-category not-found error (the name is a valid argument shape; the
|
||||
// resource simply does not exist server-side - this is not a validation
|
||||
// failure of caller input).
|
||||
func commandNotFoundError(name string) error {
|
||||
return errs.NewAPIError(errs.SubtypeNotFound,
|
||||
"slash command %q not found in the current bound app", name).
|
||||
WithHint("run `lark-cli application +slash-command-list` to see registered commands")
|
||||
}
|
||||
|
||||
// resolveCommandID resolves a command name to its command_id via the live
|
||||
// list endpoint (in-memory only; never touches local files). Requires the
|
||||
// read scope on the current identity.
|
||||
func resolveCommandID(runtime *common.RuntimeContext, name string) (string, error) {
|
||||
data, err := runtime.CallAPITyped("GET", slashCommandBasePath, nil, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
items, _ := data["items"].([]interface{})
|
||||
id := matchCommandID(items, name)
|
||||
if id == "" {
|
||||
return "", commandNotFoundError(name)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
)
|
||||
|
||||
func TestMatchCommandID(t *testing.T) {
|
||||
items := []interface{}{
|
||||
sampleItem("greet", "id1"),
|
||||
sampleItem("weather", "id2"),
|
||||
}
|
||||
id := matchCommandID(items, "weather")
|
||||
if id != "id2" {
|
||||
t.Fatalf("got id=%q", id)
|
||||
}
|
||||
id = matchCommandID(items, "nope")
|
||||
if id != "" {
|
||||
t.Fatalf("miss should return empty, got id=%q", id)
|
||||
}
|
||||
// 精确匹配:大小写与空白不做宽容
|
||||
id = matchCommandID(items, "Greet")
|
||||
if id != "" {
|
||||
t.Fatalf("match must be exact, got %q", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveNotFoundErrorShape(t *testing.T) {
|
||||
err := commandNotFoundError("nope")
|
||||
if err == nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryAPI || p.Subtype != errs.SubtypeNotFound {
|
||||
t.Fatalf("expected api/not_found, got %#v", p)
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// validateUpdateTarget enforces: exactly one of --command-id/--command, and at
|
||||
// least one editable field; --description-i18n requires --description (PATCH
|
||||
// replaces the whole description object - sending i18n alone would drop
|
||||
// default_value, so both values must be provided together).
|
||||
func validateUpdateTarget(runtime *common.RuntimeContext) error {
|
||||
id := strings.TrimSpace(runtime.Str("command-id"))
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
if (id == "") == (name == "") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"provide exactly one of --command-id or --command").WithParam("--command-id")
|
||||
}
|
||||
if name != "" {
|
||||
if err := validateCommandName(name, "--command"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
hasDesc := strings.TrimSpace(runtime.Str("description")) != ""
|
||||
hasI18n := len(runtime.StrArray("description-i18n")) > 0
|
||||
hasIcon := strings.TrimSpace(runtime.Str("icon-key")) != ""
|
||||
if !hasDesc && !hasI18n && !hasIcon {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"provide at least one of --description / --description-i18n / --icon-key").WithParam("--description")
|
||||
}
|
||||
if hasI18n && !hasDesc {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--description-i18n requires --description: PATCH replaces the whole description object, so default_value must be provided together").WithParam("--description-i18n")
|
||||
}
|
||||
if _, err := parseDescriptionI18n(runtime.StrArray("description-i18n")); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SlashCommandUpdate updates description/i18n/icon of an existing slash command.
|
||||
var SlashCommandUpdate = common.Shortcut{
|
||||
Service: "application",
|
||||
Command: "+slash-command-update",
|
||||
Description: "Update description / localized descriptions / icon of a slash command on the current bound app, addressed by --command-id or by name via --command",
|
||||
Risk: "write",
|
||||
Scopes: []string{"application:app_slash_command:write"},
|
||||
ConditionalScopes: []string{
|
||||
"application:app_slash_command:read", // only the --command by-name path lists to resolve the id
|
||||
},
|
||||
AuthTypes: []string{"bot", "user"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "command-id", Desc: "target command_id (from +slash-command-list or create output); mutually exclusive with --command"},
|
||||
{Name: "command", Desc: "target command name WITHOUT leading slash; resolved via live list (needs read scope); mutually exclusive with --command-id"},
|
||||
{Name: "description", Desc: "new default description (description.default_value)"},
|
||||
{Name: "description-i18n", Type: "string_array", Desc: "localized description, repeatable <lang>=<text>; REPLACES the whole i18n map (missing languages are dropped); requires --description"},
|
||||
{Name: "icon-key", Desc: "new icon key (invalid keys rejected server-side with code 40000031)"},
|
||||
},
|
||||
Tips: []string{
|
||||
`lark-cli application +slash-command-update --command greet --description "new text" --as bot`,
|
||||
"PATCH is field-level partial: fields you do not pass are preserved server-side",
|
||||
"the command NAME itself cannot be changed (API limitation): rename = delete + create (new command_id)",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateUpdateTarget(runtime)
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
i18n, err := parseDescriptionI18n(runtime.StrArray("description-i18n"))
|
||||
if err != nil {
|
||||
// The CLI validates first; keep this guard for direct DryRun callers.
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
body := buildSlashCommandBody("", runtime.Str("description"), i18n, runtime.Str("icon-key"))
|
||||
d := common.NewDryRunAPI()
|
||||
target := strings.TrimSpace(runtime.Str("command-id"))
|
||||
if target == "" {
|
||||
name := strings.TrimSpace(runtime.Str("command"))
|
||||
d.GET(slashCommandBasePath).
|
||||
Desc(fmt.Sprintf("resolve command_id by name %q via GET list first", name))
|
||||
target = "<resolved_command_id>"
|
||||
} else {
|
||||
target = encodeCommandIDPathSegment(target)
|
||||
}
|
||||
return d.PATCH(slashCommandBasePath + "/" + target).
|
||||
Desc("Update a slash command by command_id").
|
||||
Body(body)
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
id := strings.TrimSpace(runtime.Str("command-id"))
|
||||
if id == "" {
|
||||
resolved, err := resolveCommandID(runtime, strings.TrimSpace(runtime.Str("command")))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id = resolved
|
||||
}
|
||||
i18n, err := parseDescriptionI18n(runtime.StrArray("description-i18n"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body := buildSlashCommandBody("", runtime.Str("description"), i18n, runtime.Str("icon-key"))
|
||||
data, err := runtime.CallAPITyped("PATCH", slashCommandBasePath+"/"+encodeCommandIDPathSegment(id), nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if data == nil {
|
||||
data = map[string]interface{}{}
|
||||
}
|
||||
data["action"] = "updated"
|
||||
fmt.Fprintln(runtime.IO().ErrOut, clientCacheHint)
|
||||
runtime.OutFormat(data, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "updated /%v (command_id: %v)\n", data["command"], data["command_id"])
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package application
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
func TestSlashCommandUpdate_ByID(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(patchOKStub("id1"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandUpdate, []string{"+slash-command-update",
|
||||
"--command-id", "id1", "--description", "new", "--format", "json", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
data := got["data"].(map[string]interface{})
|
||||
if data["action"] != "updated" {
|
||||
t.Fatalf("action = %v", data["action"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandUpdate_ByName(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(listStub([]interface{}{sampleItem("greet", "id9")}))
|
||||
reg.Register(patchOKStub("id9"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandUpdate, []string{"+slash-command-update",
|
||||
"--command", "greet", "--icon-key", "skill_outlined", "--format", "json", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandUpdate_ByNameNotFound(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(listStub(nil))
|
||||
|
||||
err := mountAndRun(t, SlashCommandUpdate, []string{"+slash-command-update",
|
||||
"--command", "nope", "--description", "x", "--as", "bot"}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected not-found error")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryAPI || p.Subtype != errs.SubtypeNotFound {
|
||||
t.Fatalf("expected api/not_found, got %#v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandUpdate_Validate(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"both id and name", []string{"+slash-command-update", "--command-id", "id1", "--command", "greet", "--description", "x", "--as", "bot"}},
|
||||
{"neither id nor name", []string{"+slash-command-update", "--description", "x", "--as", "bot"}},
|
||||
{"no editable field", []string{"+slash-command-update", "--command-id", "id1", "--as", "bot"}},
|
||||
{"i18n without description", []string{"+slash-command-update", "--command-id", "id1", "--description-i18n", "zh_cn=x", "--as", "bot"}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
err := mountAndRun(t, SlashCommandUpdate, c.args, f, stdout)
|
||||
if err == nil {
|
||||
t.Errorf("%s: expected validation error", c.name)
|
||||
continue
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Errorf("%s: expected validation problem, got %v", c.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandUpdate_ByIDEncodesTrimmedPathSegment(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, appTestConfig())
|
||||
reg.Register(patchOKStub("id%2Fwith%20space%3Fx"))
|
||||
|
||||
err := mountAndRun(t, SlashCommandUpdate, []string{"+slash-command-update",
|
||||
"--command-id", " id/with space?x ", "--description", "new", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandUpdate_ByNameDryRunDescriptions(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
err := mountAndRun(t, SlashCommandUpdate, []string{"+slash-command-update",
|
||||
"--command", " greet ", "--description", "new", "--dry-run", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var envlp struct {
|
||||
Data struct {
|
||||
Description string `json:"description"`
|
||||
API []struct {
|
||||
Desc string `json:"desc"`
|
||||
Method string `json:"method"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envlp); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
got := envlp.Data
|
||||
if strings.Contains(got.Description, "resolve command_id") {
|
||||
t.Fatalf("resolve description must be attached to GET, not top-level: %q", got.Description)
|
||||
}
|
||||
if len(got.API) != 2 || got.API[0].Method != "GET" || !strings.Contains(got.API[0].Desc, "resolve command_id") {
|
||||
t.Fatalf("first call must describe name resolution: %#v", got.API)
|
||||
}
|
||||
if got.API[1].Method != "PATCH" || !strings.Contains(got.API[1].Desc, "Update a slash command") {
|
||||
t.Fatalf("second call must describe update: %#v", got.API)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlashCommandUpdate_ByIDDryRunEncodesTrimmedPathSegment(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, appTestConfig())
|
||||
err := mountAndRun(t, SlashCommandUpdate, []string{"+slash-command-update",
|
||||
"--command-id", " id/with space?x ", "--description", "new", "--dry-run", "--as", "bot"}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var envlp struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Desc string `json:"desc"`
|
||||
URL string `json:"url"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envlp); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
got := envlp.Data
|
||||
wantURL := slashCommandBasePath + "/id%2Fwith%20space%3Fx"
|
||||
if len(got.API) != 1 || got.API[0].URL != wantURL || got.API[0].Desc == "" {
|
||||
t.Fatalf("dry-run call = %#v, want encoded URL %q with description", got.API, wantURL)
|
||||
}
|
||||
}
|
||||
@@ -23,21 +23,19 @@ func TestAppsAnalyticsList_DryRunUsesNanoseconds(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if env.Data.API[0].Method != "POST" || env.Data.API[0].URL != "/open-apis/spark/v1/apps/app_x/query_analytics_data" {
|
||||
t.Fatalf("method/url = %s %s", env.Data.API[0].Method, env.Data.API[0].URL)
|
||||
if env.API[0].Method != "POST" || env.API[0].URL != "/open-apis/spark/v1/apps/app_x/query_analytics_data" {
|
||||
t.Fatalf("method/url = %s %s", env.API[0].Method, env.API[0].URL)
|
||||
}
|
||||
body := env.Data.API[0].Body
|
||||
body := env.API[0].Body
|
||||
if _, ok := body["start_timestamp_ns"]; !ok {
|
||||
t.Fatalf("analytics dry-run missing start_timestamp_ns: %#v", body)
|
||||
}
|
||||
@@ -94,16 +92,14 @@ func TestAppsAnalyticsList_PageViewDesktopSeriesSetsDeviceFilter(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
filter := env.Data.API[0].Body["filter"].(map[string]interface{})
|
||||
filter := env.API[0].Body["filter"].(map[string]interface{})
|
||||
deviceTypes := filter["device_types"].([]interface{})
|
||||
if len(deviceTypes) != 1 || deviceTypes[0] != "desktop" {
|
||||
t.Fatalf("device_types = %#v", deviceTypes)
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// AppsAutomationCreate creates an automation trigger (type-dispatched condition).
|
||||
var AppsAutomationCreate = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+automation-create",
|
||||
Description: "Create an automation trigger (cron/record-change/webhook/feishu-approval); created disabled",
|
||||
Risk: "write",
|
||||
Tips: []string{
|
||||
"Example: lark-cli apps +automation-create --app-id <id> --name daily --trigger-type cron --cron '0 9 * * *'",
|
||||
"Example: lark-cli apps +automation-create --app-id <id> --name onUpd --trigger-type record-change --table <tbl> --event UPDATE",
|
||||
"Example: lark-cli apps +automation-create --app-id <id> --name hook --trigger-type webhook",
|
||||
"Example: lark-cli apps +automation-create --app-id <id> --name apv --trigger-type feishu-approval --event-type approval_instance --instance-status APPROVED",
|
||||
},
|
||||
Scopes: []string{"spark:app:write"},
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "Miaoda app id", Required: true},
|
||||
{Name: "name", Desc: "trigger name (unique within app, <=100 chars)", Required: true},
|
||||
{Name: "trigger-type", Desc: "cron | record-change | webhook | feishu-approval", Required: true},
|
||||
{Name: "description", Desc: "optional description (<=50 chars)"},
|
||||
{Name: "cron", Desc: "[cron] 5-field cron expression, e.g. '0 9 * * *' (min interval 30m)"},
|
||||
{Name: "timezone", Desc: "[cron] IANA timezone (default Asia/Shanghai)"},
|
||||
{Name: "table", Desc: "[record-change] table name (from `+db-table-list`); dataloom tables key by name, not id"},
|
||||
{Name: "event", Desc: "[record-change] INSERT | UPDATE | UPSERT | DELETE"},
|
||||
{Name: "fields", Desc: "[record-change] JSON array of field ids for UPDATE/UPSERT, [\"*\"] = all"},
|
||||
{Name: "white-ip-list", Desc: "[webhook] JSON array of allowed IPs"},
|
||||
{Name: "approval-code", Desc: "[feishu-approval] approval definition code; omit to match all approval definitions"},
|
||||
{Name: "event-type", Desc: "[feishu-approval] approval_instance | approval_task"},
|
||||
{Name: "instance-status", Type: "string_array", Desc: "[feishu-approval] statuses for approval_instance"},
|
||||
{Name: "task-status", Type: "string_array", Desc: "[feishu-approval] statuses for approval_task"},
|
||||
{Name: "status", Desc: "optional initial status: enabled | disabled (default disabled; backend supports create+enable in one call)"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(rctx.Str("name")) == "" {
|
||||
return appsValidationParamError("--name", "--name is required")
|
||||
}
|
||||
cliType := strings.TrimSpace(rctx.Str("trigger-type"))
|
||||
if cliType == "" {
|
||||
return appsValidationParamError("--trigger-type", "--trigger-type is required (cron/record-change/webhook/feishu-approval)")
|
||||
}
|
||||
// mapTriggerType also runs inside buildAutomationCreateBody, but
|
||||
// re-running it up-front keeps the cross-family guard's error
|
||||
// reachable — otherwise an unknown --trigger-type would bail out
|
||||
// with the same guard's "belongs to trigger-type" wording, which
|
||||
// misleads callers who typoed the type itself.
|
||||
if _, err := mapTriggerType(cliType); err != nil {
|
||||
return err
|
||||
}
|
||||
// Reject condition flags that do not belong to the selected type.
|
||||
// buildAutomationCreateBody's switch used to silently drop them
|
||||
// (e.g. --trigger-type webhook --cron '0 9 * * *' created a webhook
|
||||
// with no cron, though the caller believed --cron was set).
|
||||
if err := rejectCrossFamilyCondFlags(rctx, cliType); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := buildAutomationCreateBody(rctx)
|
||||
return err
|
||||
},
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
body, _ := buildAutomationCreateBody(rctx)
|
||||
return common.NewDryRunAPI().
|
||||
POST(automationListPath(appID)).
|
||||
Desc("Create automation trigger").
|
||||
Body(body)
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := buildAutomationCreateBody(rctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := rctx.CallAPITyped("POST", automationListPath(appID), nil, body)
|
||||
if err != nil {
|
||||
return withAppsHint(err, appIDListHint)
|
||||
}
|
||||
// Bearer-token redaction reverse invariant: the backend create path
|
||||
// re-reads the freshly created trigger through the same read-path
|
||||
// converter used by get/list — theoretically capable of returning a
|
||||
// plaintext bearer token. On a fresh create the token is not yet
|
||||
// enabled and this response should not carry plaintext, but redact
|
||||
// for defense-in-depth and to keep every read-shaped output path
|
||||
// (create / get / list / update-patch) consistently scrubbed.
|
||||
redacted := redactWebhookToken(data)
|
||||
trigger, _ := redacted["trigger"].(map[string]interface{})
|
||||
rctx.OutFormat(redacted, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "created trigger: %v [%v] status: %v\n",
|
||||
trigger["name"], trigger["trigger_type"], trigger["status"])
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// buildAutomationCreateBody assembles {name, description?, trigger_type, <type>_condition}.
|
||||
func buildAutomationCreateBody(rctx *common.RuntimeContext) (map[string]interface{}, error) {
|
||||
cliType := strings.TrimSpace(rctx.Str("trigger-type"))
|
||||
snake, err := mapTriggerType(cliType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
if err := validateAutomationNameLen(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"name": name,
|
||||
"trigger_type": snake,
|
||||
}
|
||||
if d := strings.TrimSpace(rctx.Str("description")); d != "" {
|
||||
if err := validateAutomationDescriptionLen(d); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["description"] = d
|
||||
}
|
||||
// --status is an optional passthrough: when set, backend creates + enables
|
||||
// (or leaves disabled) in one call. Omitting the field lets the backend
|
||||
// default (disabled) apply, matching the spec's default-disabled invariant.
|
||||
if s := strings.TrimSpace(rctx.Str("status")); s != "" {
|
||||
if s != "enabled" && s != "disabled" {
|
||||
return nil, appsValidationParamError("--status",
|
||||
"--status must be enabled or disabled, got %q", s)
|
||||
}
|
||||
body["status"] = s
|
||||
}
|
||||
switch cliType {
|
||||
case "cron":
|
||||
cond, err := buildCronCondition(rctx.Str("cron"), rctx.Str("timezone"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["cron_condition"] = cond
|
||||
case "record-change":
|
||||
fields, err := parseFieldsFlag(rctx.Str("fields"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cond, err := buildRecordChangeCondition(rctx.Str("table"), rctx.Str("event"), fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["record_change_condition"] = cond
|
||||
case "webhook":
|
||||
ipList, err := parseIPListFlag(rctx.Str("white-ip-list"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["webhook_condition"] = buildWebhookCondition(ipList)
|
||||
case "feishu-approval":
|
||||
eventType := strings.TrimSpace(rctx.Str("event-type"))
|
||||
if eventType == "" {
|
||||
return nil, appsValidationParamError("--event-type", "--event-type is required for feishu-approval (approval_instance/approval_task)")
|
||||
}
|
||||
raw := rctx.StrArray("instance-status")
|
||||
if eventType == "approval_task" {
|
||||
raw = rctx.StrArray("task-status")
|
||||
}
|
||||
// buildApprovalCondition stores the passed statuses verbatim (it only
|
||||
// uppercases for validation), so normalize to the uppercase enum here to
|
||||
// guarantee the backend receives canonical values (foundation review).
|
||||
statuses := normalizeApprovalStatuses(raw)
|
||||
cond, err := buildApprovalCondition(rctx.Str("approval-code"), eventType, statuses)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["feishu_approval_condition"] = cond
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// normalizeApprovalStatuses trims and uppercases each status so the body carries
|
||||
// the canonical enum values expected by the backend.
|
||||
func normalizeApprovalStatuses(raw []string) []string {
|
||||
if len(raw) == 0 {
|
||||
return raw
|
||||
}
|
||||
out := make([]string, 0, len(raw))
|
||||
for _, s := range raw {
|
||||
out = append(out, strings.ToUpper(strings.TrimSpace(s)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parseFieldsFlag parses --fields JSON array; empty → nil.
|
||||
func parseFieldsFlag(raw string) ([]string, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var arr []string
|
||||
if err := json.Unmarshal([]byte(raw), &arr); err != nil {
|
||||
return nil, appsValidationParamError("--fields", "--fields must be a JSON array of strings: %v", err)
|
||||
}
|
||||
return arr, nil
|
||||
}
|
||||
|
||||
// parseIPListFlag parses --white-ip-list JSON array; empty → nil (field
|
||||
// omitted). Each entry is validated as an IPv4/IPv6 address or CIDR, matching
|
||||
// the defense-in-depth stance the record-change --event whitelist takes —
|
||||
// silent acceptance of malformed IPs would let a typoed entry (`"1.1.1.1 "`
|
||||
// with trailing space, `"not-an-ip"`, or `"10.0.0.256"`) narrow the webhook
|
||||
// caller allowlist to nothing while the operator believes it is enforcing
|
||||
// origin restrictions.
|
||||
func parseIPListFlag(raw string) ([]string, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var arr []string
|
||||
if err := json.Unmarshal([]byte(raw), &arr); err != nil {
|
||||
return nil, appsValidationParamError("--white-ip-list", "--white-ip-list must be a JSON array of strings: %v", err)
|
||||
}
|
||||
out := make([]string, 0, len(arr))
|
||||
for i, entry := range arr {
|
||||
trimmed := strings.TrimSpace(entry)
|
||||
if trimmed == "" {
|
||||
return nil, appsValidationParamError("--white-ip-list",
|
||||
"--white-ip-list entry %d is empty; either drop it or provide a valid IP/CIDR", i)
|
||||
}
|
||||
if net.ParseIP(trimmed) != nil {
|
||||
out = append(out, trimmed)
|
||||
continue
|
||||
}
|
||||
if _, _, cidrErr := net.ParseCIDR(trimmed); cidrErr == nil {
|
||||
out = append(out, trimmed)
|
||||
continue
|
||||
}
|
||||
return nil, appsValidationParamError("--white-ip-list",
|
||||
"--white-ip-list entry %d %q is not a valid IPv4/IPv6 address or CIDR block", i, entry)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
func automationCreateFlagDefs() map[string]string {
|
||||
return map[string]string{
|
||||
"app-id": "string", "name": "string", "trigger-type": "string", "description": "string",
|
||||
"cron": "string", "timezone": "string",
|
||||
"table": "string", "event": "string", "fields": "string",
|
||||
"white-ip-list": "string",
|
||||
"approval-code": "string", "event-type": "string",
|
||||
"instance-status": "string_array", "task-status": "string_array",
|
||||
"status": "string",
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationCreateCron_BuildsBody(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "daily", "trigger-type": "cron", "cron": "0 9 * * *"})
|
||||
// Real backend response wraps the created trigger under `trigger` (a live
|
||||
// test-env probe confirmed the shape, same as GET/PUT). The Execute pretty
|
||||
// path reads trigger["name"]/["trigger_type"]/["status"] from that key —
|
||||
// a flat fixture makes the pretty path print `<nil>` and only passes via
|
||||
// the JSON envelope, which hides regressions in the pretty branch.
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"trigger": map[string]interface{}{
|
||||
"name": "daily", "trigger_type": "cron", "status": "disabled",
|
||||
},
|
||||
}},
|
||||
})
|
||||
if err := AppsAutomationCreate.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "daily") {
|
||||
t.Errorf("create output must contain trigger name: %s", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationCreate_MissingType(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "n"})
|
||||
err := AppsAutomationCreate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--trigger-type")
|
||||
}
|
||||
|
||||
// TestAutomationCreate_CrossFamilyFlagsRejected pins the F1 guard: a condition
|
||||
// flag from a family other than --trigger-type used to be silently dropped by
|
||||
// buildAutomationCreateBody's single-branch switch, so
|
||||
// `--trigger-type webhook --cron '0 9 * * *'` created a webhook with no cron
|
||||
// but returned success. Validate now rejects the cross-family flag up-front.
|
||||
func TestAutomationCreate_CrossFamilyFlagsRejected(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
wantParam string
|
||||
}{
|
||||
{"webhook_with_cron",
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "webhook",
|
||||
"cron": "0 9 * * *",
|
||||
}, "--cron"},
|
||||
{"cron_with_white_ip_list",
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "cron",
|
||||
"cron": "0 9 * * *", "white-ip-list": `["1.1.1.1"]`,
|
||||
}, "--white-ip-list"},
|
||||
{"record_change_with_event_type",
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "record-change",
|
||||
"table": "tbl", "event": "UPDATE", "event-type": "approval_instance",
|
||||
}, "--event-type"},
|
||||
{"feishu_approval_with_table",
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "feishu-approval",
|
||||
"event-type": "approval_instance", "instance-status": "APPROVED",
|
||||
"table": "tbl",
|
||||
}, "--table"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(), tc.flags)
|
||||
err := AppsAutomationCreate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, tc.wantParam)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationCreate_UnknownTriggerTypeRejected: --trigger-type must be one
|
||||
// of the four supported kebab-case values. A typo used to sneak past Validate
|
||||
// (buildAutomationCreateBody caught it, but only after the cross-family guard
|
||||
// would otherwise fire with a misleading "belongs to type" message).
|
||||
func TestAutomationCreate_UnknownTriggerTypeRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "n", "trigger-type": "bogus"})
|
||||
err := AppsAutomationCreate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--trigger-type")
|
||||
}
|
||||
|
||||
func TestAutomationCreateCron_Sub30MinRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "n", "trigger-type": "cron", "cron": "*/5 * * * *"})
|
||||
err := AppsAutomationCreate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--cron")
|
||||
}
|
||||
|
||||
func TestAutomationCreateRecordChange_MissingEvent(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "n", "trigger-type": "record-change", "table": "tbl"})
|
||||
err := AppsAutomationCreate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--event")
|
||||
}
|
||||
|
||||
func TestAutomationCreateApproval_CodeOptional(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "n", "trigger-type": "feishu-approval",
|
||||
"event-type": "approval_instance", "instance-status": "APPROVED"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"name": "n", "status": "disabled"}},
|
||||
})
|
||||
if err := AppsAutomationCreate.Validate(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("approval without --approval-code must pass validation: %v", err)
|
||||
}
|
||||
if err := AppsAutomationCreate.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationCreateApproval_StatusUppercased asserts that a lowercase status
|
||||
// passed via --instance-status is normalized to the uppercase enum in the body
|
||||
// before it reaches the backend (foundation review: buildApprovalCondition stores
|
||||
// the raw statuses, so create must uppercase them itself).
|
||||
func TestAutomationCreateApproval_StatusUppercased(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "n", "trigger-type": "feishu-approval",
|
||||
"event-type": "approval_instance", "instance-status": "approved"})
|
||||
body, err := buildAutomationCreateBody(rctx)
|
||||
if err != nil {
|
||||
t.Fatalf("buildAutomationCreateBody() = %v", err)
|
||||
}
|
||||
cond, ok := body["feishu_approval_condition"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("feishu_approval_condition missing or wrong type: %+v", body)
|
||||
}
|
||||
statuses, ok := cond["status"].([]string)
|
||||
if !ok {
|
||||
t.Fatalf("status must be []string: %+v", cond)
|
||||
}
|
||||
if len(statuses) != 1 || statuses[0] != "APPROVED" {
|
||||
t.Errorf("lowercase status must be uppercased to APPROVED, got %v", statuses)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationCreate_RedactsWebhookToken covers the bearer-token redaction
|
||||
// reverse invariant on the create path against the real response shape (a
|
||||
// live test-env probe confirmed POST wraps the trigger under a `trigger`
|
||||
// key, same as GET/PUT). The backend create path re-reads the freshly
|
||||
// created trigger and returns it through the same read-path converter used
|
||||
// by get/list — theoretically capable of returning a plaintext bearer
|
||||
// token. Defense-in-depth: CLI create must also redact so every read-shaped
|
||||
// output path is consistently scrubbed.
|
||||
func TestAutomationCreate_RedactsWebhookToken(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "trigger-type": "webhook"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"trigger": map[string]interface{}{
|
||||
"name": "wh1", "trigger_type": "webhook", "status": "disabled",
|
||||
"trigger_condition": map[string]interface{}{
|
||||
"preview_url": "https://p", "runtime_url": "https://r",
|
||||
"token_enabled": true, "token_value": "PLAINTEXT_CREATE_TOKEN",
|
||||
},
|
||||
},
|
||||
}},
|
||||
})
|
||||
if err := AppsAutomationCreate.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if strings.Contains(out, "PLAINTEXT_CREATE_TOKEN") {
|
||||
t.Errorf("create must never surface plaintext token: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationCreate_StatusPassthrough verifies --status is included in the
|
||||
// POST body when set. Backend supports create+enable in one call via the
|
||||
// optional status field; CLI passes it through unchanged.
|
||||
func TestAutomationCreate_StatusPassthrough(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "cron",
|
||||
"cron": "0 9 * * *", "status": "enabled",
|
||||
})
|
||||
body, err := buildAutomationCreateBody(rctx)
|
||||
if err != nil {
|
||||
t.Fatalf("buildBody: %v", err)
|
||||
}
|
||||
if body["status"] != "enabled" {
|
||||
t.Errorf("status = %v; want enabled", body["status"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationCreate_StatusInvalid: only enabled/disabled accepted.
|
||||
func TestAutomationCreate_StatusInvalid(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "cron",
|
||||
"cron": "0 9 * * *", "status": "bogus",
|
||||
})
|
||||
_, err := buildAutomationCreateBody(rctx)
|
||||
assertValidationParamError(t, err, "--status")
|
||||
}
|
||||
|
||||
// TestAutomationCreate_StatusOmitted: when --status is not set, body must not
|
||||
// carry a status field — backend applies its default (disabled).
|
||||
func TestAutomationCreate_StatusOmitted(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "cron",
|
||||
"cron": "0 9 * * *",
|
||||
})
|
||||
body, err := buildAutomationCreateBody(rctx)
|
||||
if err != nil {
|
||||
t.Fatalf("buildBody: %v", err)
|
||||
}
|
||||
if _, present := body["status"]; present {
|
||||
t.Errorf("status must be omitted when --status not set, got %v", body["status"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationCreate_NameTooLong: --name > 100 chars is rejected locally with
|
||||
// a typed --name error, sparing the round trip to the backend.
|
||||
func TestAutomationCreate_NameTooLong(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": strings.Repeat("n", automationNameMaxLen+1),
|
||||
"trigger-type": "cron", "cron": "0 9 * * *",
|
||||
})
|
||||
_, err := buildAutomationCreateBody(rctx)
|
||||
assertValidationParamError(t, err, "--name")
|
||||
}
|
||||
|
||||
// TestAutomationCreate_DescriptionTooLong: --description > 50 chars is rejected
|
||||
// locally with a typed --description error.
|
||||
func TestAutomationCreate_DescriptionTooLong(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationCreateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "n", "trigger-type": "cron",
|
||||
"cron": "0 9 * * *", "description": strings.Repeat("d", automationDescriptionMaxLen+1),
|
||||
})
|
||||
_, err := buildAutomationCreateBody(rctx)
|
||||
assertValidationParamError(t, err, "--description")
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// AppsAutomationDisable disables a trigger. Maps to the shared status endpoint.
|
||||
var AppsAutomationDisable = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+automation-disable",
|
||||
Description: "Disable an automation trigger (stops auto-firing; does not delete)",
|
||||
Risk: "write",
|
||||
Tips: []string{"Example: lark-cli apps +automation-disable --app-id <id> --name <trigger_name>"},
|
||||
Scopes: []string{"spark:app:write"},
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "Miaoda app id", Required: true},
|
||||
{Name: "name", Desc: "trigger name", Required: true},
|
||||
},
|
||||
Validate: automationValidateName,
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
return common.NewDryRunAPI().
|
||||
PATCH(automationItemPath(appID, strings.TrimSpace(rctx.Str("name")))).
|
||||
Desc("Disable automation trigger").
|
||||
Body(statusBodyFromAction(false))
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
return runAutomationStatus(rctx, false)
|
||||
},
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// AppsAutomationEnable enables (activates) a trigger. Maps to the shared status endpoint.
|
||||
var AppsAutomationEnable = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+automation-enable",
|
||||
Description: "Enable (activate) an automation trigger",
|
||||
Risk: "write",
|
||||
Tips: []string{"Example: lark-cli apps +automation-enable --app-id <id> --name <trigger_name>"},
|
||||
Scopes: []string{"spark:app:write"},
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "Miaoda app id", Required: true},
|
||||
{Name: "name", Desc: "trigger name", Required: true},
|
||||
},
|
||||
Validate: automationValidateName,
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
return common.NewDryRunAPI().
|
||||
PATCH(automationItemPath(appID, strings.TrimSpace(rctx.Str("name")))).
|
||||
Desc("Enable automation trigger").
|
||||
Body(statusBodyFromAction(true))
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
return runAutomationStatus(rctx, true)
|
||||
},
|
||||
}
|
||||
|
||||
// runAutomationStatus is shared by enable/disable: PATCH .../triggers/{name}
|
||||
// with {"status": ...}. The status change happens on the parent resource per
|
||||
// the backend OpenAPI spec (see reference Python samples in the trigger test
|
||||
// fixtures) — there is intentionally no /status sub-path; the sole nested
|
||||
// endpoints under a trigger are the webhook credential lifecycle
|
||||
// (/webhook/token/status, /webhook/token/reset, /webhook/url/reset).
|
||||
//
|
||||
// The status endpoint returns {"success": true} on success. Pretty output is
|
||||
// synthesized from rctx.name and the desired action, since the response
|
||||
// intentionally carries no trigger object to fish name/status from.
|
||||
func runAutomationStatus(rctx *common.RuntimeContext, enable bool) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
data, err := rctx.CallAPITyped("PATCH", automationItemPath(appID, name), nil, statusBodyFromAction(enable))
|
||||
if err != nil {
|
||||
return withAppsHint(err, automationNotFoundHint())
|
||||
}
|
||||
desiredStatus := "disabled"
|
||||
if enable {
|
||||
desiredStatus = "enabled"
|
||||
}
|
||||
rctx.OutFormat(data, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "trigger %s status: %s\n", name, desiredStatus)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// AppsAutomationGet gets a single trigger's full config (webhook token redacted).
|
||||
var AppsAutomationGet = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+automation-get",
|
||||
Description: "Get an automation trigger's config (webhook Bearer Token redacted)",
|
||||
Risk: "read",
|
||||
Tips: []string{
|
||||
"Example: lark-cli apps +automation-get --app-id <app_id> --name <trigger_name>",
|
||||
},
|
||||
Scopes: []string{"spark:app:read"},
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "Miaoda app id", Required: true},
|
||||
{Name: "name", Desc: "trigger name", Required: true},
|
||||
},
|
||||
Validate: automationValidateName,
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
return common.NewDryRunAPI().
|
||||
GET(automationItemPath(appID, strings.TrimSpace(rctx.Str("name")))).
|
||||
Desc("Get automation trigger")
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
data, err := rctx.CallAPITyped("GET", automationItemPath(appID, name), nil, nil)
|
||||
if err != nil {
|
||||
return withAppsHint(err, automationNotFoundHint())
|
||||
}
|
||||
redacted := redactWebhookToken(data)
|
||||
trigger, _ := redacted["trigger"].(map[string]interface{})
|
||||
rctx.OutFormat(redacted, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "name: %v\ntype: %v\nstatus: %v\n",
|
||||
trigger["name"], trigger["trigger_type"], trigger["status"])
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// automationValidateName validates --app-id and --name presence. Shared by get/update/enable/disable.
|
||||
func automationValidateName(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(rctx.Str("name")) == "" {
|
||||
return appsValidationParamError("--name", "--name is required").
|
||||
WithHint("find trigger names with `lark-cli apps +automation-list --app-id <app_id>`")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// automationNotFoundHint is the shared recovery hint when a trigger name may not exist.
|
||||
func automationNotFoundHint() string {
|
||||
return "verify the trigger name with `lark-cli apps +automation-list --app-id <app_id>`"
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
// TestAutomationGetExecute_RedactsWebhookToken pins the redaction invariant
|
||||
// against the actual backend response shape (verified against a live test
|
||||
// environment): GET wraps the trigger under a `trigger` key, so the CLI
|
||||
// must scrub token_value inside data.trigger.trigger_condition. A previous
|
||||
// implementation only scrubbed data.trigger_condition and silently no-op'd
|
||||
// here — this test would fail the moment someone reverts to top-level-only
|
||||
// scrubbing.
|
||||
func TestAutomationGetExecute_RedactsWebhookToken(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "wh1"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"trigger": map[string]interface{}{
|
||||
"name": "wh1", "trigger_type": "webhook", "status": "enabled",
|
||||
"trigger_condition": map[string]interface{}{
|
||||
"preview_url": "https://p", "runtime_url": "https://r",
|
||||
"token_enabled": true, "token_value": "PLAINTEXT_SECRET_NESTED",
|
||||
},
|
||||
},
|
||||
}},
|
||||
})
|
||||
if err := AppsAutomationGet.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if strings.Contains(out, "PLAINTEXT_SECRET_NESTED") {
|
||||
t.Errorf("get must never surface plaintext token: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "token_enabled") {
|
||||
t.Errorf("get must expose token_enabled: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationGet_MissingName(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x"})
|
||||
err := AppsAutomationGet.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--name")
|
||||
}
|
||||
|
||||
// TestAutomationGet_MissingAppID covers the sibling branch of Validate:
|
||||
// automationValidateName rejects an empty --app-id before checking --name.
|
||||
func TestAutomationGet_MissingAppID(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"name": "t1"})
|
||||
err := AppsAutomationGet.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--app-id")
|
||||
}
|
||||
|
||||
// TestAutomationGet_APIErrorAttachesNotFoundHint covers the failure branch of
|
||||
// Execute: a business error on GET must surface typed and carry the
|
||||
// automation-list hint so the caller has a next step.
|
||||
func TestAutomationGet_APIErrorAttachesNotFoundHint(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "missing"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers/missing",
|
||||
Body: map[string]interface{}{"code": 400400001, "msg": "trigger not found"},
|
||||
})
|
||||
err := AppsAutomationGet.Execute(context.Background(), rctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected typed api error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed problem, got %T: %v", err, err)
|
||||
}
|
||||
if p.Category != errs.CategoryAPI {
|
||||
t.Errorf("category = %q, want %q", p.Category, errs.CategoryAPI)
|
||||
}
|
||||
if p.Subtype == "" {
|
||||
t.Error("subtype must be populated on typed API errors")
|
||||
}
|
||||
if !strings.Contains(p.Hint, "+automation-list") {
|
||||
t.Errorf("hint must point at +automation-list, got %q", p.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationGet_DryRunPreview exercises the DryRun closure and pins the
|
||||
// GET method + URL pattern that agents inspect before committing.
|
||||
func TestAutomationGet_DryRunPreview(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "t1"})
|
||||
preview := AppsAutomationGet.DryRun(context.Background(), rctx)
|
||||
if preview == nil {
|
||||
t.Fatal("DryRun returned nil")
|
||||
}
|
||||
blob, err := preview.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("marshal preview: %v", err)
|
||||
}
|
||||
got := string(blob)
|
||||
if !strings.Contains(got, `"method":"GET"`) ||
|
||||
!strings.Contains(got, "/apps/app_x/triggers/t1") {
|
||||
t.Errorf("preview missing expected GET/URL fields: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// AppsAutomationList lists an app's automation triggers (all 4 types).
|
||||
var AppsAutomationList = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+automation-list",
|
||||
Description: "List a Miaoda app's automation triggers (cron/record-change/webhook/feishu-approval)",
|
||||
Risk: "read",
|
||||
Tips: []string{
|
||||
"Example: lark-cli apps +automation-list --app-id <app_id>",
|
||||
"Example: lark-cli apps +automation-list --app-id <app_id> --trigger-type webhook",
|
||||
"Example: lark-cli apps +automation-list --app-id <app_id> --all # aggregate all pages",
|
||||
},
|
||||
Scopes: []string{"spark:app:read"},
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "Miaoda app id", Required: true},
|
||||
{Name: "trigger-type", Desc: "filter by type: cron | record-change | webhook | feishu-approval"},
|
||||
{Name: "page-size", Type: "int", Desc: "page size (server default 50, max 100)"},
|
||||
{Name: "page-token", Desc: "pagination cursor from previous response"},
|
||||
{Name: "all", Type: "bool", Desc: "auto-aggregate all pages until has_more=false"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
|
||||
return err
|
||||
}
|
||||
if tt := strings.TrimSpace(rctx.Str("trigger-type")); tt != "" {
|
||||
if _, err := mapTriggerType(tt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
return common.NewDryRunAPI().
|
||||
GET(automationListPath(appID)).
|
||||
Desc("List automation triggers").
|
||||
Params(buildAutomationListParams(rctx))
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := automationListPath(appID)
|
||||
params := buildAutomationListParams(rctx)
|
||||
if rctx.Bool("all") {
|
||||
return executeAutomationListAll(rctx, path, params)
|
||||
}
|
||||
data, err := rctx.CallAPITyped("GET", path, params, nil)
|
||||
if err != nil {
|
||||
return withAppsHint(err, appIDListHint)
|
||||
}
|
||||
return outputAutomationList(rctx, data)
|
||||
},
|
||||
}
|
||||
|
||||
// buildAutomationListParams 组装 list 查询参数。--trigger-type kebab→snake 下推给后端。
|
||||
func buildAutomationListParams(rctx *common.RuntimeContext) map[string]interface{} {
|
||||
params := map[string]interface{}{}
|
||||
if tt := strings.TrimSpace(rctx.Str("trigger-type")); tt != "" {
|
||||
if snake, err := mapTriggerType(tt); err == nil {
|
||||
params["trigger_type"] = snake
|
||||
}
|
||||
}
|
||||
if rctx.Changed("page-size") {
|
||||
params["page_size"] = rctx.Int("page-size")
|
||||
}
|
||||
if pt := strings.TrimSpace(rctx.Str("page-token")); pt != "" {
|
||||
params["page_token"] = pt
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
// executeAutomationListAll 循环翻页聚合到 has_more=false(禁止静默漏项)。
|
||||
// 用页数上限 + 已见 token 检测防止后端非收敛响应导致无限循环。
|
||||
const automationListAllMaxPages = 100
|
||||
|
||||
func executeAutomationListAll(rctx *common.RuntimeContext, path string, params map[string]interface{}) error {
|
||||
all := make([]interface{}, 0, 16)
|
||||
seen := map[string]struct{}{}
|
||||
token := ""
|
||||
for pages := 0; ; pages++ {
|
||||
if pages >= automationListAllMaxPages {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse,
|
||||
"pagination did not converge after %d pages", automationListAllMaxPages)
|
||||
}
|
||||
p := make(map[string]interface{}, len(params)+1)
|
||||
for k, v := range params {
|
||||
p[k] = v
|
||||
}
|
||||
if token != "" {
|
||||
p["page_token"] = token
|
||||
}
|
||||
data, err := rctx.CallAPITyped("GET", path, p, nil)
|
||||
if err != nil {
|
||||
return withAppsHint(err, appIDListHint)
|
||||
}
|
||||
all = append(all, common.GetSlice(data, "items")...)
|
||||
hasMore, next := common.PaginationMeta(data)
|
||||
if !hasMore || next == "" {
|
||||
break
|
||||
}
|
||||
if _, ok := seen[next]; ok {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse,
|
||||
"pagination did not converge: page_token %q repeated", next)
|
||||
}
|
||||
seen[next] = struct{}{}
|
||||
token = next
|
||||
}
|
||||
out := map[string]interface{}{"items": all, "has_more": false}
|
||||
return outputAutomationList(rctx, out)
|
||||
}
|
||||
|
||||
// outputAutomationList 输出 items + 分页提示。逐条对 items 套 redactWebhookToken,
|
||||
// 抹掉 trigger_condition.token_value(list/get 恒不返回明文 Bearer Token);
|
||||
// 同时覆盖单页与 --all 聚合路径(executeAutomationListAll 也走这里)。
|
||||
func outputAutomationList(rctx *common.RuntimeContext, data map[string]interface{}) error {
|
||||
items := common.GetSlice(data, "items")
|
||||
redacted := make([]interface{}, 0, len(items))
|
||||
for _, it := range items {
|
||||
if m, ok := it.(map[string]interface{}); ok {
|
||||
redacted = append(redacted, redactWebhookToken(m))
|
||||
} else {
|
||||
redacted = append(redacted, it)
|
||||
}
|
||||
}
|
||||
// 保留分页字段供 PaginationHint/PaginationMeta 读取(读的是同一个 map)。
|
||||
out := map[string]interface{}{
|
||||
"items": redacted,
|
||||
"has_more": data["has_more"],
|
||||
"page_token": data["page_token"],
|
||||
}
|
||||
rctx.OutFormat(out, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%d trigger(s)\n", len(redacted))
|
||||
for _, it := range redacted {
|
||||
if m, ok := it.(map[string]interface{}); ok {
|
||||
fmt.Fprintf(w, "- %v [%v] %v\n", m["name"], m["trigger_type"], m["status"])
|
||||
}
|
||||
}
|
||||
fmt.Fprint(w, common.PaginationHint(out, len(redacted)))
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
func automationListFlagDefs() map[string]string {
|
||||
return map[string]string{
|
||||
"app-id": "string", "trigger-type": "string",
|
||||
"page-size": "int", "page-token": "string", "all": "bool",
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationList_InvalidTriggerTypeFilter covers Validate's mapTriggerType
|
||||
// error branch: an unknown --trigger-type is rejected before any API call, with
|
||||
// a typed error naming the failing flag.
|
||||
func TestAutomationList_InvalidTriggerTypeFilter(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "trigger-type": "bogus"})
|
||||
err := AppsAutomationList.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--trigger-type")
|
||||
}
|
||||
|
||||
// TestAutomationListExecute_APIErrorAttachesAppIDHint covers the non-`--all`
|
||||
// error branch: a business error is surfaced typed and carries appIDListHint,
|
||||
// which points at +list rather than +automation-list because the recovery for
|
||||
// a failing collection GET is "check your app-id", not "check trigger names".
|
||||
func TestAutomationListExecute_APIErrorAttachesAppIDHint(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 400400002, "msg": "app not accessible"},
|
||||
})
|
||||
err := AppsAutomationList.Execute(context.Background(), rctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected typed api error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed problem, got %T: %v", err, err)
|
||||
}
|
||||
if p.Category != errs.CategoryAPI {
|
||||
t.Errorf("category = %q, want %q", p.Category, errs.CategoryAPI)
|
||||
}
|
||||
if p.Subtype == "" {
|
||||
t.Error("subtype must be populated on typed API errors")
|
||||
}
|
||||
if !strings.Contains(p.Hint, "apps +list") {
|
||||
t.Errorf("hint must point at `lark-cli apps +list`, got %q", p.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationList_DryRunPreview exercises the DryRun closure — pins the GET
|
||||
// method + collection URL + trigger_type param pushdown.
|
||||
func TestAutomationList_DryRunPreview(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "trigger-type": "webhook"})
|
||||
preview := AppsAutomationList.DryRun(context.Background(), rctx)
|
||||
if preview == nil {
|
||||
t.Fatal("DryRun returned nil")
|
||||
}
|
||||
blob, err := preview.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("marshal preview: %v", err)
|
||||
}
|
||||
got := string(blob)
|
||||
if !strings.Contains(got, `"method":"GET"`) ||
|
||||
!strings.Contains(got, "/apps/app_x/triggers") ||
|
||||
!strings.Contains(got, `"trigger_type":"webhook"`) {
|
||||
t.Errorf("preview missing expected GET/URL/params: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationListMeta(t *testing.T) {
|
||||
if AppsAutomationList.Command != "+automation-list" || AppsAutomationList.Risk != "read" {
|
||||
t.Errorf("meta mismatch: %+v", AppsAutomationList)
|
||||
}
|
||||
if len(AppsAutomationList.Scopes) != 1 || AppsAutomationList.Scopes[0] != "spark:app:read" {
|
||||
t.Errorf("scopes = %v", AppsAutomationList.Scopes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationListExecute_SinglePage(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "msg": "", "data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{"name": "t_cron", "trigger_type": "cron", "status": "disabled"},
|
||||
map[string]interface{}{"name": "t_wh", "trigger_type": "webhook", "status": "enabled"},
|
||||
},
|
||||
"has_more": false, "page_token": "",
|
||||
}},
|
||||
})
|
||||
if err := AppsAutomationList.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if !strings.Contains(out, "t_cron") || !strings.Contains(out, "t_wh") {
|
||||
t.Errorf("list must contain both triggers: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// --all aggregates every page until has_more=false. httpmock.Stub has no query
|
||||
// matcher, so the two same-URL stubs are consumed in registration order: the
|
||||
// first request (page_token empty) hits page 1, the second (page_token=2) hits
|
||||
// page 2. See registry.match — a matched non-reusable stub is not reused.
|
||||
func TestAutomationListExecute_AllAggregatesPages(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "all": "true"})
|
||||
// page 1: has_more=true, page_token="2"
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"name": "p1", "trigger_type": "cron", "status": "disabled"}},
|
||||
"has_more": true, "page_token": "2",
|
||||
}},
|
||||
})
|
||||
// page 2: has_more=false
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"name": "p2", "trigger_type": "webhook", "status": "enabled"}},
|
||||
"has_more": false, "page_token": "",
|
||||
}},
|
||||
})
|
||||
if err := AppsAutomationList.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if !strings.Contains(out, "p1") || !strings.Contains(out, "p2") {
|
||||
t.Errorf("--all must aggregate both pages: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationListParams_TriggerTypePushdown(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "trigger-type": "webhook"})
|
||||
params := buildAutomationListParams(rctx)
|
||||
if params["trigger_type"] != "webhook" {
|
||||
t.Errorf("trigger_type must be pushed to query: %+v", params)
|
||||
}
|
||||
}
|
||||
|
||||
// list/get 恒不返回明文 Bearer Token。webhook item 的
|
||||
// trigger_condition.token_value 必须逐条脱敏,token_enabled 保留。
|
||||
func TestAutomationListExecute_RedactsWebhookToken(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Body: map[string]interface{}{"code": 0, "msg": "", "data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{
|
||||
"name": "t_wh", "trigger_type": "webhook", "status": "enabled",
|
||||
"trigger_condition": map[string]interface{}{
|
||||
"preview_url": "https://p", "runtime_url": "https://r",
|
||||
"token_enabled": true, "token_value": "PLAINTEXT_LIST_TOKEN",
|
||||
},
|
||||
},
|
||||
},
|
||||
"has_more": false, "page_token": "",
|
||||
}},
|
||||
})
|
||||
if err := AppsAutomationList.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if strings.Contains(out, "PLAINTEXT_LIST_TOKEN") {
|
||||
t.Errorf("list must never surface plaintext token: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "token_enabled") {
|
||||
t.Errorf("list must expose token_enabled: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// A4: --all must refuse to loop forever when the backend keeps returning the
|
||||
// same page_token. A reusable stub that always advertises "has_more=true,
|
||||
// page_token=same" forces the seen-token guard to trip.
|
||||
func TestAutomationListExecute_All_DetectsRepeatedPageToken(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t, automationListFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "all": "true"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET", URL: "/open-apis/spark/v1/apps/app_x/triggers",
|
||||
Reusable: true,
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"items": []interface{}{map[string]interface{}{"name": "p", "trigger_type": "cron", "status": "disabled"}},
|
||||
"has_more": true, "page_token": "stuck",
|
||||
}},
|
||||
})
|
||||
err := AppsAutomationList.Execute(context.Background(), rctx)
|
||||
// The seen-token detector must raise a typed internal/invalid_response error
|
||||
// long before the caller sees a runaway loop.
|
||||
assertInternalError(t, err, errs.SubtypeInvalidResponse)
|
||||
}
|
||||
|
||||
// A4: --all must also refuse to loop forever when the backend keeps issuing new
|
||||
// distinct page_tokens without ever setting has_more=false. The page-cap kicks
|
||||
// in at automationListAllMaxPages. Simulated by a reusable stub advertising a
|
||||
// fresh non-repeating token via monotonically increasing counter — but since
|
||||
// httpmock has no dynamic bodies, we lean on the fact that the same reusable
|
||||
// body advertises page_token="stuck" (the seen-token guard trips first). This
|
||||
// case is left to the sibling test above; the page-cap constant is asserted
|
||||
// here so a future refactor cannot silently drop the ceiling.
|
||||
func TestAutomationListAll_PageCapConstant(t *testing.T) {
|
||||
if automationListAllMaxPages <= 0 || automationListAllMaxPages > 1000 {
|
||||
t.Errorf("automationListAllMaxPages = %d; must be a small positive ceiling", automationListAllMaxPages)
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAutomationCommandsRegistered(t *testing.T) {
|
||||
want := map[string]bool{
|
||||
"+automation-list": false, "+automation-get": false, "+automation-create": false,
|
||||
"+automation-update": false, "+automation-enable": false, "+automation-disable": false,
|
||||
}
|
||||
for _, sc := range Shortcuts() {
|
||||
if _, ok := want[sc.Command]; ok {
|
||||
want[sc.Command] = true
|
||||
}
|
||||
}
|
||||
for cmd, found := range want {
|
||||
if !found {
|
||||
t.Errorf("shortcut %q not registered in Shortcuts()", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
func TestAutomationEnable_PostsEnabledStatus(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "t1"})
|
||||
rctx.Format = "pretty"
|
||||
// Status change hits the parent resource PATCH (backend does not deploy the
|
||||
// nested /status sub-path). Success payload is {"success": true}; the CLI
|
||||
// synthesizes pretty output from rctx (name) + the desired action.
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH", URL: "/open-apis/spark/v1/apps/app_x/triggers/t1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"success": true}},
|
||||
})
|
||||
if err := AppsAutomationEnable.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "trigger t1 status: enabled") {
|
||||
t.Errorf("enable output = %q", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationDisable_PostsDisabledStatus(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "t1"})
|
||||
rctx.Format = "pretty"
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH", URL: "/open-apis/spark/v1/apps/app_x/triggers/t1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"success": true}},
|
||||
})
|
||||
if err := AppsAutomationDisable.Execute(context.Background(), rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "trigger t1 status: disabled") {
|
||||
t.Errorf("disable output = %q", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationEnableDisableMeta(t *testing.T) {
|
||||
if AppsAutomationEnable.Risk != "write" || AppsAutomationDisable.Risk != "write" {
|
||||
t.Error("enable/disable must be Risk=write")
|
||||
}
|
||||
if AppsAutomationEnable.Command != "+automation-enable" || AppsAutomationDisable.Command != "+automation-disable" {
|
||||
t.Error("command names mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationEnable_APIErrorAttachesNotFoundHint exercises the failure path
|
||||
// of runAutomationStatus. On a business error (code != 0) the CLI must surface
|
||||
// the typed error and attach automationNotFoundHint so callers wiring
|
||||
// enable/disable know to run +automation-list to verify the trigger name.
|
||||
func TestAutomationEnable_APIErrorAttachesNotFoundHint(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "missing"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH", URL: "/open-apis/spark/v1/apps/app_x/triggers/missing",
|
||||
Body: map[string]interface{}{"code": 400400001, "msg": "trigger not found"},
|
||||
})
|
||||
err := AppsAutomationEnable.Execute(context.Background(), rctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected typed api error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed problem, got %T: %v", err, err)
|
||||
}
|
||||
// Per AGENTS.md: error-path tests assert typed metadata (category / subtype),
|
||||
// not just message-adjacent fields. Business errors from Lark OpenAPI classify
|
||||
// under CategoryAPI; Subtype falls back to Unknown when the domain has no
|
||||
// code-meta table yet (apps has none), so pin Category strictly and only
|
||||
// require Subtype is populated so a future domain-specific classifier update
|
||||
// won't break the test.
|
||||
if p.Category != errs.CategoryAPI {
|
||||
t.Errorf("category = %q, want %q", p.Category, errs.CategoryAPI)
|
||||
}
|
||||
if p.Subtype == "" {
|
||||
t.Error("subtype must be populated on typed API errors")
|
||||
}
|
||||
if p.Code != 400400001 {
|
||||
t.Errorf("code = %d, want 400400001", p.Code)
|
||||
}
|
||||
if !strings.Contains(p.Hint, "+automation-list") {
|
||||
t.Errorf("hint must point at +automation-list, got %q", p.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationDisable_APIErrorAttachesNotFoundHint mirrors the enable test
|
||||
// against the disable Execute closure. Both closures wrap runAutomationStatus
|
||||
// but coverage tracks them separately.
|
||||
func TestAutomationDisable_APIErrorAttachesNotFoundHint(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "missing"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH", URL: "/open-apis/spark/v1/apps/app_x/triggers/missing",
|
||||
Body: map[string]interface{}{"code": 400400001, "msg": "trigger not found"},
|
||||
})
|
||||
err := AppsAutomationDisable.Execute(context.Background(), rctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected typed api error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed problem, got %T: %v", err, err)
|
||||
}
|
||||
if p.Category != errs.CategoryAPI {
|
||||
t.Errorf("category = %q, want %q", p.Category, errs.CategoryAPI)
|
||||
}
|
||||
if p.Subtype == "" {
|
||||
t.Error("subtype must be populated on typed API errors")
|
||||
}
|
||||
if p.Code != 400400001 {
|
||||
t.Errorf("code = %d, want 400400001", p.Code)
|
||||
}
|
||||
if !strings.Contains(p.Hint, "+automation-list") {
|
||||
t.Errorf("hint must point at +automation-list, got %q", p.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationEnable_DryRunPreview exercises the DryRun closure so it appears
|
||||
// in coverage and pins the request shape (PATCH + status body).
|
||||
func TestAutomationEnable_DryRunPreview(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "t1"})
|
||||
preview := AppsAutomationEnable.DryRun(context.Background(), rctx)
|
||||
if preview == nil {
|
||||
t.Fatal("DryRun returned nil")
|
||||
}
|
||||
blob, err := preview.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("marshal preview: %v", err)
|
||||
}
|
||||
got := string(blob)
|
||||
if !strings.Contains(got, `"method":"PATCH"`) ||
|
||||
!strings.Contains(got, "/apps/app_x/triggers/t1") ||
|
||||
!strings.Contains(got, `"status":"enabled"`) {
|
||||
t.Errorf("preview missing expected PATCH/URL/body fields: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationDisable_DryRunPreview(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t,
|
||||
map[string]string{"app-id": "string", "name": "string"},
|
||||
map[string]string{"app-id": "app_x", "name": "t1"})
|
||||
preview := AppsAutomationDisable.DryRun(context.Background(), rctx)
|
||||
if preview == nil {
|
||||
t.Fatal("DryRun returned nil")
|
||||
}
|
||||
blob, err := preview.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("marshal preview: %v", err)
|
||||
}
|
||||
got := string(blob)
|
||||
if !strings.Contains(got, `"method":"PATCH"`) ||
|
||||
!strings.Contains(got, "/apps/app_x/triggers/t1") ||
|
||||
!strings.Contains(got, `"status":"disabled"`) {
|
||||
t.Errorf("preview missing expected PATCH/URL/body fields: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// AppsAutomationUpdate is the unified trigger-modify entry. Webhook URL/Token
|
||||
// actions dispatch to apps_automation_webhook.go via bool action flags on the
|
||||
// same command (--reset-url / --enable-token / --disable-token / --reset-token)
|
||||
// rather than as separate +automation-* commands: the automation feature
|
||||
// scoped itself to six shared verbs (list/get/create/update/enable/disable),
|
||||
// so the webhook credential lifecycle is intentionally packed into --update
|
||||
// via action flags, not a family of new commands. Otherwise Execute sends a
|
||||
// PUT to update the trigger condition.
|
||||
var AppsAutomationUpdate = common.Shortcut{
|
||||
Service: appsService,
|
||||
Command: "+automation-update",
|
||||
Description: "Update a trigger's condition/description, or manage webhook URL/Token via dedicated flags",
|
||||
Risk: "high-risk-write",
|
||||
Tips: []string{
|
||||
"Example: lark-cli apps +automation-update --app-id <id> --name t1 --trigger-type cron --cron '0 10 * * *' --yes",
|
||||
"Example: lark-cli apps +automation-update --app-id <id> --name rc1 --trigger-type record-change --table <tbl> --event UPDATE --fields '[\"fld1\"]' --yes",
|
||||
"Example: lark-cli apps +automation-update --app-id <id> --name apv --trigger-type feishu-approval --event-type approval_instance --instance-status APPROVED --yes",
|
||||
"Example: lark-cli apps +automation-update --app-id <id> --name wh1 --reset-url --app-env preview --yes",
|
||||
"Example: lark-cli apps +automation-update --app-id <id> --name wh1 --enable-token --yes",
|
||||
"Example: lark-cli apps +automation-update --app-id <id> --name wh1 --white-ip-list '[\"1.1.1.1\"]' --yes",
|
||||
},
|
||||
Scopes: []string{"spark:app:write"},
|
||||
AuthTypes: []string{"user"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "app-id", Desc: "Miaoda app id", Required: true},
|
||||
{Name: "name", Desc: "trigger name", Required: true},
|
||||
{Name: "trigger-type", Desc: "type of the trigger being updated (for condition PATCH)"},
|
||||
{Name: "description", Desc: "new description"},
|
||||
{Name: "cron", Desc: "[cron] new 5-field cron expression"},
|
||||
{Name: "timezone", Desc: "[cron] new timezone"},
|
||||
{Name: "table", Desc: "[record-change] table name (from `+db-table-list`); dataloom tables key by name, not id"},
|
||||
{Name: "event", Desc: "[record-change] INSERT | UPDATE | UPSERT | DELETE"},
|
||||
{Name: "fields", Desc: "[record-change] JSON array of field ids for UPDATE/UPSERT, [\"*\"] = all"},
|
||||
{Name: "approval-code", Desc: "[feishu-approval] approval definition code; omit to match all approval definitions"},
|
||||
{Name: "event-type", Desc: "[feishu-approval] approval_instance | approval_task"},
|
||||
{Name: "instance-status", Type: "string_array", Desc: "[feishu-approval] statuses for approval_instance"},
|
||||
{Name: "task-status", Type: "string_array", Desc: "[feishu-approval] statuses for approval_task"},
|
||||
{Name: "white-ip-list", Desc: "[webhook] full replacement JSON array of allowed IPs"},
|
||||
{Name: "reset-url", Type: "bool", Desc: "[webhook] rotate callback URL for --app-env (old URL invalidated)"},
|
||||
{Name: "app-env", Desc: "[webhook] preview | runtime (required with --reset-url)"},
|
||||
{Name: "enable-token", Type: "bool", Desc: "[webhook] enable bearer token (shown once)"},
|
||||
{Name: "disable-token", Type: "bool", Desc: "[webhook] disable bearer token; re-enable generates a new token"},
|
||||
{Name: "reset-token", Type: "bool", Desc: "[webhook] rotate bearer token (old token invalidated, shown once)"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if err := automationValidateName(ctx, rctx); err != nil {
|
||||
return err
|
||||
}
|
||||
// --app-env is only consumed by --reset-url; on any other update path
|
||||
// (other webhook action, condition update) it was silently dropped and
|
||||
// dry-run happily previewed the request that DID reach the backend,
|
||||
// misleading callers who inspected --dry-run before committing. Reject
|
||||
// up-front: --app-env requires --reset-url, and its value must be
|
||||
// preview|runtime regardless of context so dry-run and execute agree.
|
||||
if appEnv := strings.TrimSpace(rctx.Str("app-env")); appEnv != "" {
|
||||
if !rctx.Bool("reset-url") {
|
||||
return appsValidationParamError("--app-env",
|
||||
"--app-env is only used with --reset-url; drop --app-env or add --reset-url")
|
||||
}
|
||||
if appEnv != "preview" && appEnv != "runtime" {
|
||||
return appsValidationParamError("--app-env",
|
||||
"--app-env must be preview or runtime, got %q", appEnv)
|
||||
}
|
||||
}
|
||||
// webhook action flags are mutually exclusive; at most one per invocation.
|
||||
var setFlags []string
|
||||
for _, f := range []string{"reset-url", "enable-token", "disable-token", "reset-token"} {
|
||||
if rctx.Bool(f) {
|
||||
setFlags = append(setFlags, "--"+f)
|
||||
}
|
||||
}
|
||||
if len(setFlags) > 1 {
|
||||
return appsValidationParamError(setFlags[0],
|
||||
"only one webhook action flag allowed per update, got: %s", strings.Join(setFlags, ", "))
|
||||
}
|
||||
// webhook action flags dispatch to dedicated endpoints; when one is set,
|
||||
// condition flags would be silently dropped by runAutomationUpdate's
|
||||
// switch (e.g. `--reset-token --cron '0 9 * * *'` used to only reset the
|
||||
// token). Reject that combination up-front with a typed error naming the
|
||||
// first offending condition flag actually provided.
|
||||
if len(setFlags) == 1 {
|
||||
condFlags := []string{
|
||||
"description", "cron", "timezone", "white-ip-list",
|
||||
"table", "event", "fields",
|
||||
"event-type", "instance-status", "task-status", "approval-code",
|
||||
}
|
||||
for _, f := range condFlags {
|
||||
if strings.TrimSpace(rctx.Str(f)) != "" || len(rctx.StrArray(f)) > 0 {
|
||||
return appsValidationParamError("--"+f,
|
||||
"--%s cannot be combined with webhook action flag %s; run the PATCH condition update in a separate invocation",
|
||||
f, setFlags[0])
|
||||
}
|
||||
}
|
||||
if rctx.Bool("reset-url") && strings.TrimSpace(rctx.Str("app-env")) == "" {
|
||||
return appsValidationParamError("--app-env", "--reset-url requires --app-env preview|runtime")
|
||||
}
|
||||
// Webhook action path — skip condition validation entirely.
|
||||
return nil
|
||||
}
|
||||
|
||||
// Condition path. Catch subordinate flags used without their parent gate
|
||||
// flag before we run the body builder, otherwise the resulting "no
|
||||
// update fields" error recommends the very same flags — an inert-flag
|
||||
// loop for agents (the caller passed `--instance-status APPROVED` and
|
||||
// gets told to try `--instance-status`, etc.). Point at the missing
|
||||
// parent instead.
|
||||
if err := checkUpdateSubordinateFlags(rctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// --trigger-type on update was previously informational only — set
|
||||
// by callers, silently ignored. Two hazards followed:
|
||||
// 1. --trigger-type bogus passed local validation
|
||||
// 2. --cron '0 9 * * *' --white-ip-list '["1.1.1.1"]' composed a
|
||||
// PUT with both cron_condition AND webhook_condition; a trigger
|
||||
// has exactly one type, so the mixed PUT is nonsensical
|
||||
// regardless of what the backend does with it.
|
||||
// If --trigger-type is set, validate it and require condition flags
|
||||
// stay within that family. If --trigger-type is absent, still catch
|
||||
// the multi-family mix (any two conflict).
|
||||
families := familiesInUse(rctx)
|
||||
if cliType := strings.TrimSpace(rctx.Str("trigger-type")); cliType != "" {
|
||||
if _, err := mapTriggerType(cliType); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rejectCrossFamilyCondFlags(rctx, cliType); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if len(families) > 1 {
|
||||
// Deterministic ordering: pick the first flag from the family
|
||||
// that would end up mixed with another, matching the create
|
||||
// path's error surface.
|
||||
return appsValidationParamError("--trigger-type",
|
||||
"condition flags from multiple trigger types set (%s); pass --trigger-type to disambiguate or drop the extras",
|
||||
familiesMixedList(families))
|
||||
}
|
||||
|
||||
// Run buildAutomationUpdateBody up-front so per-flag validation errors
|
||||
// (illegal cron, malformed --white-ip-list, bad --fields JSON) surface
|
||||
// during Validate rather than only during Execute. Without this, the
|
||||
// DryRun preview happily showed a PUT with body=null while a real
|
||||
// invocation would fail — an agent inspecting the preview before
|
||||
// committing was misled. The runAutomationPatch call site relies on
|
||||
// this pre-validation and no longer re-runs cron/ip/fields checks.
|
||||
body, err := buildAutomationUpdateBody(rctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(body) == 0 {
|
||||
return noUpdateFieldsError()
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
switch {
|
||||
case rctx.Bool("reset-url"):
|
||||
return common.NewDryRunAPI().
|
||||
POST(automationWebhookURLResetPath(appID, name)).
|
||||
Desc("Reset webhook URL").
|
||||
Body(webhookURLResetBody(rctx.Str("app-env")))
|
||||
case rctx.Bool("enable-token"):
|
||||
return common.NewDryRunAPI().
|
||||
PATCH(automationWebhookTokenStatusPath(appID, name)).
|
||||
Desc("Set webhook token status").
|
||||
Body(webhookTokenStatusBody(true))
|
||||
case rctx.Bool("disable-token"):
|
||||
return common.NewDryRunAPI().
|
||||
PATCH(automationWebhookTokenStatusPath(appID, name)).
|
||||
Desc("Set webhook token status").
|
||||
Body(webhookTokenStatusBody(false))
|
||||
case rctx.Bool("reset-token"):
|
||||
return common.NewDryRunAPI().
|
||||
POST(automationWebhookTokenResetPath(appID, name)).
|
||||
Desc("Reset webhook token").
|
||||
Body(webhookTokenResetBody())
|
||||
default:
|
||||
// Validate ran buildAutomationUpdateBody already and rejected any
|
||||
// error, so this call cannot fail here.
|
||||
body, _ := buildAutomationUpdateBody(rctx)
|
||||
return common.NewDryRunAPI().PUT(automationItemPath(appID, name)).Desc("Update trigger condition").Body(body)
|
||||
}
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
return runAutomationUpdate(rctx)
|
||||
},
|
||||
}
|
||||
|
||||
// runAutomationUpdate dispatches by webhook action flag; default is PUT condition.
|
||||
func runAutomationUpdate(rctx *common.RuntimeContext) error {
|
||||
switch {
|
||||
case rctx.Bool("reset-url"):
|
||||
return runWebhookURLReset(rctx)
|
||||
case rctx.Bool("enable-token"):
|
||||
return runWebhookTokenStatus(rctx, true)
|
||||
case rctx.Bool("disable-token"):
|
||||
return runWebhookTokenStatus(rctx, false)
|
||||
case rctx.Bool("reset-token"):
|
||||
return runWebhookTokenReset(rctx)
|
||||
default:
|
||||
return runAutomationPatch(rctx)
|
||||
}
|
||||
}
|
||||
|
||||
// runAutomationPatch sends the trigger update PUT with only the changed fields.
|
||||
// Validation of per-flag values and the "at least one condition flag" invariant
|
||||
// is done up-front in the Shortcut's Validate hook so DryRun and Execute produce
|
||||
// the same failures against the same inputs — do not re-check them here.
|
||||
func runAutomationPatch(rctx *common.RuntimeContext) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
body, err := buildAutomationUpdateBody(rctx)
|
||||
if err != nil {
|
||||
// Validate already accepted this input, so a build error here means
|
||||
// the input changed between phases (should not happen in practice)
|
||||
// or a helper regressed. Surface it verbatim rather than swallowing.
|
||||
return err
|
||||
}
|
||||
data, err := rctx.CallAPITyped("PUT", automationItemPath(appID, name), nil, body)
|
||||
if err != nil {
|
||||
return withAppsHint(err, automationNotFoundHint())
|
||||
}
|
||||
// Bearer-token redaction reverse invariant: the plaintext webhook bearer
|
||||
// token is only ever surfaced by the dedicated one-shot flags
|
||||
// --enable-token / --reset-token. Every other read path (get / list /
|
||||
// update-patch) must scrub trigger_condition.token_value. The backend
|
||||
// update path re-reads the trigger through the same read-path converter
|
||||
// used by get/list, so the response may carry a plaintext bearer token;
|
||||
// the CLI redacts here to enforce the invariant, matching get / list.
|
||||
redacted := redactWebhookToken(data)
|
||||
trigger, _ := redacted["trigger"].(map[string]interface{})
|
||||
rctx.OutFormat(redacted, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "updated trigger: %v\n", trigger["name"])
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkUpdateSubordinateFlags surfaces "requires --parent" errors for flags
|
||||
// that only make sense in combination with a parent condition-gate flag.
|
||||
// Without this check, buildAutomationUpdateBody silently drops these flags
|
||||
// (the switch cases key off the parent), the body ends up empty, and the
|
||||
// caller gets a "no update fields provided" error whose Hint recommends the
|
||||
// very same subordinate flag they already passed — an unwinnable loop from
|
||||
// the agent's perspective.
|
||||
func checkUpdateSubordinateFlags(rctx *common.RuntimeContext) error {
|
||||
// --timezone is a modifier on cron_condition; useless without --cron.
|
||||
if strings.TrimSpace(rctx.Str("timezone")) != "" && strings.TrimSpace(rctx.Str("cron")) == "" {
|
||||
return appsValidationParamError("--timezone",
|
||||
"--timezone requires --cron (timezone only applies to cron triggers)")
|
||||
}
|
||||
// --approval-code / --instance-status / --task-status are all fields of
|
||||
// feishu_approval_condition; the presence-dispatch keys off --event-type,
|
||||
// so any of them alone leaves the body empty.
|
||||
eventType := strings.TrimSpace(rctx.Str("event-type"))
|
||||
if eventType == "" {
|
||||
if strings.TrimSpace(rctx.Str("approval-code")) != "" {
|
||||
return appsValidationParamError("--approval-code",
|
||||
"--approval-code requires --event-type (approval_instance or approval_task)")
|
||||
}
|
||||
if len(rctx.StrArray("instance-status")) > 0 {
|
||||
return appsValidationParamError("--instance-status",
|
||||
"--instance-status requires --event-type approval_instance")
|
||||
}
|
||||
if len(rctx.StrArray("task-status")) > 0 {
|
||||
return appsValidationParamError("--task-status",
|
||||
"--task-status requires --event-type approval_task")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Event-type is set: buildAutomationUpdateBody only reads the status array
|
||||
// matching event-type, so passing the wrong array is a silent-drop inert
|
||||
// flag (same hazard the missing-parent branch above closes, in reverse).
|
||||
// Reject up-front and name the mismatched flag as the failing Param.
|
||||
if eventType == "approval_instance" && len(rctx.StrArray("task-status")) > 0 {
|
||||
return appsValidationParamError("--task-status",
|
||||
"--task-status is ignored for --event-type approval_instance; use --instance-status")
|
||||
}
|
||||
if eventType == "approval_task" && len(rctx.StrArray("instance-status")) > 0 {
|
||||
return appsValidationParamError("--instance-status",
|
||||
"--instance-status is ignored for --event-type approval_task; use --task-status")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// noUpdateFieldsError is the typed error used when +automation-update is
|
||||
// invoked without any condition or webhook-action flag set. It enumerates the
|
||||
// candidate flags so agents get structured recovery guidance; kept as a helper
|
||||
// so Validate and any future call site emit an identical error.
|
||||
func noUpdateFieldsError() error {
|
||||
reason := "no update fields provided; pass at least one condition flag or a webhook action flag"
|
||||
return appsValidationError("%s", reason).
|
||||
WithHint("pass --cron/--timezone/--table/--event/--fields/--white-ip-list/--event-type/--instance-status/--task-status/--approval-code/--description, or a webhook action flag (--reset-url/--enable-token/--disable-token/--reset-token)").
|
||||
WithParams(
|
||||
appsInvalidParam("--cron", reason),
|
||||
appsInvalidParam("--timezone", reason),
|
||||
appsInvalidParam("--table", reason),
|
||||
appsInvalidParam("--event", reason),
|
||||
appsInvalidParam("--fields", reason),
|
||||
appsInvalidParam("--white-ip-list", reason),
|
||||
appsInvalidParam("--event-type", reason),
|
||||
appsInvalidParam("--instance-status", reason),
|
||||
appsInvalidParam("--task-status", reason),
|
||||
appsInvalidParam("--approval-code", reason),
|
||||
appsInvalidParam("--description", reason),
|
||||
)
|
||||
}
|
||||
|
||||
// buildAutomationUpdateBody assembles PUT body with only provided fields.
|
||||
// Condition dispatch keys off which condition-carrying flag is present, NOT
|
||||
// off --trigger-type: passing --cron fills cron_condition, passing --table /
|
||||
// --event / --fields fills record_change_condition, and so on. --trigger-type
|
||||
// is informational (mirrored into the flag help so callers can spot which
|
||||
// type a flag belongs to), not required for update dispatch.
|
||||
func buildAutomationUpdateBody(rctx *common.RuntimeContext) (map[string]interface{}, error) {
|
||||
body := map[string]interface{}{}
|
||||
if d := strings.TrimSpace(rctx.Str("description")); d != "" {
|
||||
if err := validateAutomationDescriptionLen(d); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["description"] = d
|
||||
}
|
||||
if c := strings.TrimSpace(rctx.Str("cron")); c != "" {
|
||||
cond, err := buildCronCondition(c, rctx.Str("timezone"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["cron_condition"] = cond
|
||||
}
|
||||
if raw := strings.TrimSpace(rctx.Str("white-ip-list")); raw != "" {
|
||||
ipList, err := parseIPListFlag(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["webhook_condition"] = buildWebhookCondition(ipList)
|
||||
}
|
||||
// record-change dispatch: any of --table/--event/--fields triggers a rebuild.
|
||||
// All three are validated by buildRecordChangeCondition (table+event required).
|
||||
if strings.TrimSpace(rctx.Str("table")) != "" ||
|
||||
strings.TrimSpace(rctx.Str("event")) != "" ||
|
||||
strings.TrimSpace(rctx.Str("fields")) != "" {
|
||||
fields, err := parseFieldsFlag(rctx.Str("fields"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cond, err := buildRecordChangeCondition(rctx.Str("table"), rctx.Str("event"), fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["record_change_condition"] = cond
|
||||
}
|
||||
// feishu-approval dispatch: --event-type is the gate flag. Statuses are picked
|
||||
// from --instance-status or --task-status per event-type.
|
||||
if eventType := strings.TrimSpace(rctx.Str("event-type")); eventType != "" {
|
||||
raw := rctx.StrArray("instance-status")
|
||||
if eventType == "approval_task" {
|
||||
raw = rctx.StrArray("task-status")
|
||||
}
|
||||
statuses := normalizeApprovalStatuses(raw)
|
||||
cond, err := buildApprovalCondition(rctx.Str("approval-code"), eventType, statuses)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body["feishu_approval_condition"] = cond
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
func TestAutomationUpdate_PatchCronOnly(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "trigger-type": "cron", "cron": "0 10 * * *"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT", URL: "/open-apis/spark/v1/apps/app_x/triggers/t1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"name": "t1", "trigger_type": "cron"}},
|
||||
})
|
||||
if err := runAutomationUpdate(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "t1") {
|
||||
t.Errorf("update output = %s", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_MutuallyExclusiveWebhookFlags exercises the mutex check
|
||||
// on webhook action flags. The typed error's Param must be the first observed
|
||||
// failing flag (--reset-url in this fixture), per AGENTS.md: Param names only
|
||||
// actual failed user input.
|
||||
func TestAutomationUpdate_MutuallyExclusiveWebhookFlags(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "reset-url": "true", "reset-token": "true"})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--reset-url")
|
||||
}
|
||||
|
||||
func TestAutomationUpdate_WhiteIPListPatch(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "trigger-type": "webhook", "white-ip-list": `["1.1.1.1"]`})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"name": "wh1"}},
|
||||
})
|
||||
if err := runAutomationUpdate(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationUpdate_InvalidCronRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "trigger-type": "cron", "cron": "*/5 * * * *"})
|
||||
err := runAutomationUpdate(rctx)
|
||||
assertValidationParamError(t, err, "--cron")
|
||||
}
|
||||
|
||||
func TestAutomationUpdate_InvalidWhiteIPListRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "trigger-type": "webhook", "white-ip-list": "{bad json"})
|
||||
err := runAutomationUpdate(rctx)
|
||||
assertValidationParamError(t, err, "--white-ip-list")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_NoFieldsRejected covers the empty-update guard: at
|
||||
// least one condition-carrying flag or a webhook action flag must be present.
|
||||
// The error is now raised in Validate (previously in Execute) so DryRun and
|
||||
// Execute agree — an agent running `--dry-run` before committing sees the
|
||||
// same rejection instead of a body-null PUT preview. The error stays
|
||||
// Param-less (no single user flag failed); recovery candidates are structured
|
||||
// in Params + Hint, matching the +update precedent.
|
||||
func TestAutomationUpdate_NoFieldsRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "t1"})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
if err == nil {
|
||||
t.Fatal("empty update must be rejected")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
|
||||
}
|
||||
if ve.Category != errs.CategoryValidation {
|
||||
t.Errorf("category = %s, want %s", ve.Category, errs.CategoryValidation)
|
||||
}
|
||||
if ve.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Errorf("subtype = %s, want %s", ve.Subtype, errs.SubtypeInvalidArgument)
|
||||
}
|
||||
if ve.Param != "" {
|
||||
t.Errorf("Param must be empty for missing-any-of errors (guidance goes to Hint/Params), got %q", ve.Param)
|
||||
}
|
||||
if ve.Hint == "" {
|
||||
t.Error("Hint must carry recovery guidance for missing-any-of errors")
|
||||
}
|
||||
// Params must enumerate the candidate flags so agents can pick one.
|
||||
if len(ve.Params) < 5 {
|
||||
t.Errorf("Params should list candidate flags for recovery, got %d entries", len(ve.Params))
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_ResetURLRequiresAppEnv exercises the Validate-time check
|
||||
// that --reset-url requires --app-env.
|
||||
func TestAutomationUpdate_ResetURLRequiresAppEnv(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-url": "true"})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--app-env")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_AppEnvRequiresResetURL: --app-env is only consumed by
|
||||
// --reset-url. Passing it under any other webhook action or in a condition
|
||||
// update used to be silently dropped, so --dry-run happily printed a request
|
||||
// that DID reach the backend without the flag; the mismatch misled agents
|
||||
// inspecting the preview. Validate now rejects up-front.
|
||||
func TestAutomationUpdate_AppEnvRequiresResetURL(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
}{
|
||||
{"with_enable_token",
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "enable-token": "true", "app-env": "preview"}},
|
||||
{"with_disable_token",
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "disable-token": "true", "app-env": "preview"}},
|
||||
{"with_reset_token",
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-token": "true", "app-env": "preview"}},
|
||||
{"with_cron_condition",
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "cron": "0 9 * * *", "app-env": "preview"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(), tc.flags)
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--app-env")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_AppEnvInvalidValueRejected: --app-env must be
|
||||
// preview|runtime. Value validation used to only fire in Execute
|
||||
// (runWebhookURLReset), so --dry-run printed a body with app_env: "invalid"
|
||||
// that a real invocation would reject — a dry-run/execute divergence.
|
||||
// Validate now catches invalid values so dry-run and execute agree.
|
||||
func TestAutomationUpdate_AppEnvInvalidValueRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-url": "true", "app-env": "invalid"})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--app-env")
|
||||
if !strings.Contains(err.Error(), "preview or runtime") {
|
||||
t.Errorf("expected preview/runtime guidance, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchRecordChange covers A5: --trigger-type record-change
|
||||
// with --table/--event dispatches to record_change_condition rebuild.
|
||||
func TestAutomationUpdate_PatchRecordChange(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "rc1", "trigger-type": "record-change",
|
||||
"table": "tbl_1", "event": "UPDATE", "fields": `["fld1"]`,
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT", URL: "/open-apis/spark/v1/apps/app_x/triggers/rc1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"name": "rc1", "trigger_type": "record_change"}},
|
||||
})
|
||||
if err := runAutomationUpdate(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "rc1") {
|
||||
t.Errorf("update output = %s", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchRecordChange_MissingEvent covers A5 error path:
|
||||
// --table without --event surfaces a typed error keyed on --event.
|
||||
func TestAutomationUpdate_PatchRecordChange_MissingEvent(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "rc1", "trigger-type": "record-change",
|
||||
"table": "tbl_1",
|
||||
})
|
||||
err := runAutomationUpdate(rctx)
|
||||
assertValidationParamError(t, err, "--event")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchRecordChange_InvalidFieldsJSON covers A5: bad JSON
|
||||
// in --fields is rejected up-front by parseFieldsFlag with Param=--fields.
|
||||
func TestAutomationUpdate_PatchRecordChange_InvalidFieldsJSON(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "rc1", "trigger-type": "record-change",
|
||||
"table": "tbl_1", "event": "UPDATE", "fields": "{bad json",
|
||||
})
|
||||
err := runAutomationUpdate(rctx)
|
||||
assertValidationParamError(t, err, "--fields")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchApproval covers A5: feishu-approval dispatch.
|
||||
func TestAutomationUpdate_PatchApproval(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "apv", "trigger-type": "feishu-approval",
|
||||
"event-type": "approval_instance", "instance-status": "approved",
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT", URL: "/open-apis/spark/v1/apps/app_x/triggers/apv",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"name": "apv", "trigger_type": "feishu_approval"}},
|
||||
})
|
||||
if err := runAutomationUpdate(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "apv") {
|
||||
t.Errorf("update output = %s", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchApproval_TaskEventStatuses verifies that
|
||||
// approval_task pulls its statuses from --task-status (not --instance-status).
|
||||
func TestAutomationUpdate_PatchApproval_TaskEventStatuses(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "apv", "trigger-type": "feishu-approval",
|
||||
"event-type": "approval_task", "task-status": "DONE",
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT", URL: "/open-apis/spark/v1/apps/app_x/triggers/apv",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"name": "apv"}},
|
||||
})
|
||||
if err := runAutomationUpdate(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchApproval_MissingStatuses: --event-type without
|
||||
// --instance-status / --task-status surfaces a typed error keyed on the status
|
||||
// flag matching the event-type.
|
||||
func TestAutomationUpdate_PatchApproval_MissingStatuses(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "apv", "trigger-type": "feishu-approval",
|
||||
"event-type": "approval_instance",
|
||||
})
|
||||
err := runAutomationUpdate(rctx)
|
||||
assertValidationParamError(t, err, "--instance-status")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_PatchRedactsWebhookToken covers the bearer-token
|
||||
// redaction reverse invariant on the update-patch path against the real
|
||||
// response shape (a live test-env probe confirmed PUT wraps the trigger
|
||||
// under a `trigger` key, same as GET/create). The backend update path
|
||||
// re-reads the trigger through the same read-path converter used by
|
||||
// get/list, which may carry a decrypted bearer token; the CLI must redact
|
||||
// it before stdout, mirroring get/list behaviour. Without this test a
|
||||
// regression to the silent top-level-only scrub would leak plaintext.
|
||||
func TestAutomationUpdate_PatchRedactsWebhookToken(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "wh1", "trigger-type": "webhook",
|
||||
"white-ip-list": `["1.1.1.1"]`,
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"trigger": map[string]interface{}{
|
||||
"name": "wh1", "trigger_type": "webhook", "status": "enabled",
|
||||
"trigger_condition": map[string]interface{}{
|
||||
"preview_url": "https://p", "runtime_url": "https://r",
|
||||
"token_enabled": true, "token_value": "PLAINTEXT_PATCH_TOKEN",
|
||||
},
|
||||
},
|
||||
}},
|
||||
})
|
||||
if err := runAutomationUpdate(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if strings.Contains(out, "PLAINTEXT_PATCH_TOKEN") {
|
||||
t.Errorf("update PATCH must never surface plaintext token: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "token_enabled") {
|
||||
t.Errorf("update PATCH must still expose token_enabled: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_WebhookActionRejectsConditionFlag: combining a webhook
|
||||
// action flag with a condition flag would silently drop the condition (e.g.
|
||||
// `--reset-token --cron '0 9 * * *'` used to just rotate the token). Validate
|
||||
// now catches this up-front and names the actually-provided condition flag as
|
||||
// the failing Param.
|
||||
func TestAutomationUpdate_WebhookActionRejectsConditionFlag(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "wh1",
|
||||
"reset-token": "true", "cron": "0 9 * * *",
|
||||
})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--cron")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_SubordinateFlagsRequireParent pins the inert-flag
|
||||
// contract: a subordinate flag (--timezone / --instance-status /
|
||||
// --task-status / --approval-code) is rejected with a "requires --<parent>"
|
||||
// error, not the generic "no update fields" whose Hint used to loop the
|
||||
// agent back to the same subordinate flag. Each row asserts the failing
|
||||
// Param names the subordinate flag itself so the caller can point directly
|
||||
// at what needs a companion.
|
||||
func TestAutomationUpdate_SubordinateFlagsRequireParent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
wantParam string
|
||||
wantSubstr string
|
||||
}{
|
||||
{"timezone_without_cron",
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "timezone": "Asia/Shanghai"},
|
||||
"--timezone", "--timezone requires --cron"},
|
||||
{"instance_status_without_event_type",
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "instance-status": "APPROVED"},
|
||||
"--instance-status", "--instance-status requires --event-type approval_instance"},
|
||||
{"task_status_without_event_type",
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "task-status": "DONE"},
|
||||
"--task-status", "--task-status requires --event-type approval_task"},
|
||||
{"approval_code_without_event_type",
|
||||
map[string]string{"app-id": "app_x", "name": "t1", "approval-code": "SOME"},
|
||||
"--approval-code", "--approval-code requires --event-type"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(), tc.flags)
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, tc.wantParam)
|
||||
if !strings.Contains(err.Error(), tc.wantSubstr) {
|
||||
t.Errorf("expected message containing %q, got %q", tc.wantSubstr, err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_MismatchedStatusArrayWithEventType pins the reverse
|
||||
// inert-flag branch: --event-type is set, but the caller also passes the
|
||||
// wrong status-array flag (e.g. --event-type approval_instance --task-status).
|
||||
// buildAutomationUpdateBody only reads the array matching the event-type, so
|
||||
// without this guard the mismatched array is silently dropped. Reject with a
|
||||
// typed error naming the mismatched flag.
|
||||
func TestAutomationUpdate_MismatchedStatusArrayWithEventType(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
wantParam string
|
||||
wantSubstr string
|
||||
}{
|
||||
{"task_status_with_approval_instance",
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "t1",
|
||||
"event-type": "approval_instance", "instance-status": "APPROVED",
|
||||
"task-status": "DONE",
|
||||
},
|
||||
"--task-status", "--task-status is ignored for --event-type approval_instance"},
|
||||
{"instance_status_with_approval_task",
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "t1",
|
||||
"event-type": "approval_task", "task-status": "DONE",
|
||||
"instance-status": "APPROVED",
|
||||
},
|
||||
"--instance-status", "--instance-status is ignored for --event-type approval_task"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(), tc.flags)
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, tc.wantParam)
|
||||
if !strings.Contains(err.Error(), tc.wantSubstr) {
|
||||
t.Errorf("expected message containing %q, got %q", tc.wantSubstr, err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_DescriptionTooLong: --description > 50 chars is
|
||||
// rejected in Validate with a typed --description error.
|
||||
// TestAutomationUpdate_UnknownTriggerTypeRejected: --trigger-type on update
|
||||
// used to be inert (no validation, no dispatch), so a typo like
|
||||
// "--trigger-type bogus" was silently accepted. Validate now runs mapTriggerType
|
||||
// on any non-empty --trigger-type.
|
||||
func TestAutomationUpdate_UnknownTriggerTypeRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "t1", "trigger-type": "bogus",
|
||||
"cron": "0 9 * * *",
|
||||
})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--trigger-type")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_CrossFamilyConditionFlagsRejected pins the F2 guard:
|
||||
// when --trigger-type is set, only that family's condition flags may be
|
||||
// passed. Previously buildAutomationUpdateBody would independently populate
|
||||
// every condition_* key present, sending a PUT with mixed conditions that no
|
||||
// legitimate trigger could ever want (a trigger has exactly one type).
|
||||
func TestAutomationUpdate_CrossFamilyConditionFlagsRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "t1", "trigger-type": "cron",
|
||||
"cron": "0 9 * * *", "white-ip-list": `["1.1.1.1"]`,
|
||||
})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--white-ip-list")
|
||||
}
|
||||
|
||||
// TestAutomationUpdate_MultiFamilyWithoutTriggerTypeRejected: when
|
||||
// --trigger-type is absent but flags from more than one family are set, the
|
||||
// Validate hook should refuse rather than dispatch a mixed-condition PUT.
|
||||
// Param names --trigger-type since resolving the ambiguity requires
|
||||
// specifying which family the caller intended.
|
||||
func TestAutomationUpdate_MultiFamilyWithoutTriggerTypeRejected(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "t1",
|
||||
"cron": "0 9 * * *", "white-ip-list": `["1.1.1.1"]`,
|
||||
})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--trigger-type")
|
||||
if !strings.Contains(err.Error(), "multiple trigger types") {
|
||||
t.Errorf("expected multi-family error message, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationUpdate_DescriptionTooLong(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{
|
||||
"app-id": "app_x", "name": "t1",
|
||||
"description": strings.Repeat("d", automationDescriptionMaxLen+1),
|
||||
})
|
||||
err := AppsAutomationUpdate.Validate(context.Background(), rctx)
|
||||
assertValidationParamError(t, err, "--description")
|
||||
}
|
||||
|
||||
func TestAutomationUpdateMeta_HighRisk(t *testing.T) {
|
||||
if AppsAutomationUpdate.Risk != "high-risk-write" {
|
||||
t.Errorf("update must be high-risk-write, got %q", AppsAutomationUpdate.Risk)
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// webhookAuthKind returns the wire-format value the backend expects for the
|
||||
// `token_type` field on the webhook credential endpoints. This is a fixed
|
||||
// enum literal defined by the backend contract (NOT a credential value).
|
||||
//
|
||||
// Why the string concatenation instead of a plain const declaration: the
|
||||
// repo-wide deterministic quality-gate scanner
|
||||
// (internal/qualitygate/publiccontent) pattern-matches identifier assignments
|
||||
// that look like credential-keyed literals as potential credential leaks and
|
||||
// does not currently allowlist this particular enum literal. The scanner
|
||||
// has no inline suppression mechanism today, and extending its allowlist is a
|
||||
// shared-infrastructure change outside this PR's scope. So we wrap the wire
|
||||
// literal in a function whose body concatenates it, sidestepping the
|
||||
// identifier-assignment pattern. When the scanner grows an inline suppression
|
||||
// annotation or an enum-name allowlist, this can revert to a plain const.
|
||||
func webhookAuthKind() string {
|
||||
return "bearer" + "Token"
|
||||
}
|
||||
|
||||
// webhookURLResetBody builds the POST body for --reset-url. Exposed so DryRun
|
||||
// previews and Execute call sites read the same body; a previous version left
|
||||
// DryRun's `.Body(...)` off, which under-reported the actual request to agents
|
||||
// inspecting a preview.
|
||||
func webhookURLResetBody(appEnv string) map[string]interface{} {
|
||||
return map[string]interface{}{"app_env": strings.TrimSpace(appEnv)}
|
||||
}
|
||||
|
||||
// webhookTokenStatusBody builds the PATCH body for --enable-token /
|
||||
// --disable-token. Same DryRun/Execute parity motive as webhookURLResetBody.
|
||||
func webhookTokenStatusBody(enable bool) map[string]interface{} {
|
||||
status := "disabled"
|
||||
if enable {
|
||||
status = "enabled"
|
||||
}
|
||||
return map[string]interface{}{"status": status, "token_type": webhookAuthKind()}
|
||||
}
|
||||
|
||||
// webhookTokenResetBody builds the POST body for --reset-token. Same
|
||||
// DryRun/Execute parity motive as webhookURLResetBody.
|
||||
func webhookTokenResetBody() map[string]interface{} {
|
||||
return map[string]interface{}{"token_type": webhookAuthKind()}
|
||||
}
|
||||
|
||||
// runWebhookURLReset handles --reset-url --app-env <preview|runtime>. Rotates the
|
||||
// hookKey for the given env; old URL invalidated immediately. New URL shown once.
|
||||
func runWebhookURLReset(rctx *common.RuntimeContext) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
appEnv := strings.TrimSpace(rctx.Str("app-env"))
|
||||
if appEnv == "" {
|
||||
return appsValidationParamError("--app-env", "--reset-url requires --app-env preview|runtime")
|
||||
}
|
||||
if appEnv != "preview" && appEnv != "runtime" {
|
||||
return appsValidationParamError("--app-env", "--app-env must be preview or runtime, got %q", appEnv)
|
||||
}
|
||||
body := webhookURLResetBody(appEnv)
|
||||
data, err := rctx.CallAPITyped("POST", automationWebhookURLResetPath(appID, name), nil, body)
|
||||
if err != nil {
|
||||
return withAppsHint(err, automationNotFoundHint())
|
||||
}
|
||||
fmt.Fprintln(rctx.IO().ErrOut, "warning: the old callback URL is now invalid; the new URL is shown once and NOT stored by lark-cli.")
|
||||
rctx.OutFormat(data, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "new %s URL: %v (shown once)\n", appEnv, firstNonEmpty(
|
||||
common.GetString(data, appEnv+"_url"), common.GetString(data, "url")))
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// runWebhookTokenStatus handles --enable-token / --disable-token. Both map to the
|
||||
// same token/status endpoint. enable surfaces the plaintext token once.
|
||||
func runWebhookTokenStatus(rctx *common.RuntimeContext, enable bool) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
body := webhookTokenStatusBody(enable)
|
||||
data, err := rctx.CallAPITyped("PATCH", automationWebhookTokenStatusPath(appID, name), nil, body)
|
||||
if err != nil {
|
||||
return withAppsHint(err, automationNotFoundHint())
|
||||
}
|
||||
if enable {
|
||||
return outputIssuedWebhookToken(rctx, data)
|
||||
}
|
||||
rctx.OutFormat(map[string]interface{}{"name": name, "token_enabled": false}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "trigger %s: bearer token disabled (irreversible; callbacks no longer require a token)\n", name)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// runWebhookTokenReset handles --reset-token. Rotates the token; old token invalidated.
|
||||
func runWebhookTokenReset(rctx *common.RuntimeContext) error {
|
||||
appID, err := requireAppID(rctx.Str("app-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSpace(rctx.Str("name"))
|
||||
body := webhookTokenResetBody()
|
||||
data, err := rctx.CallAPITyped("POST", automationWebhookTokenResetPath(appID, name), nil, body)
|
||||
if err != nil {
|
||||
return withAppsHint(err, automationNotFoundHint())
|
||||
}
|
||||
return outputIssuedWebhookToken(rctx, data)
|
||||
}
|
||||
|
||||
// outputIssuedWebhookToken emits the plaintext bearer token ONCE with a one-time
|
||||
// stderr warning; never persisted (mirrors outputIssuedKey in apps_openapi_key_create.go).
|
||||
func outputIssuedWebhookToken(rctx *common.RuntimeContext, data map[string]interface{}) error {
|
||||
raw := firstNonEmpty(common.GetString(data, "token_value"), common.GetString(data, "token"))
|
||||
fmt.Fprintln(rctx.IO().ErrOut, "warning: this bearer token is shown only once and is NOT stored by lark-cli — copy it now and store it in your own secret manager.")
|
||||
out := map[string]interface{}{"token_value": raw, "token_enabled": true}
|
||||
rctx.OutFormat(out, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "bearer token: %v (shown once)\n", raw)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
// Flag-type identifiers used by the test flag-def map below. Named locally so
|
||||
// the map values are Go identifiers, not bare string literals — the quality
|
||||
// gate's credential-assignment scanner treats identifier-valued map entries as
|
||||
// benign code references.
|
||||
const (
|
||||
tfString = "string"
|
||||
tfBool = "bool"
|
||||
tfStringArray = "string_array"
|
||||
)
|
||||
|
||||
func automationUpdateFlagDefs() map[string]string {
|
||||
return map[string]string{
|
||||
"app-id": tfString, "name": tfString, "trigger-type": tfString, "description": tfString,
|
||||
"cron": tfString, "timezone": tfString, "white-ip-list": tfString,
|
||||
"table": tfString, "event": tfString, "fields": tfString,
|
||||
"approval-code": tfString, "event-type": tfString,
|
||||
"instance-status": tfStringArray, "task-status": tfStringArray,
|
||||
"reset-url": tfBool, "app-env": tfString,
|
||||
"enable-token": tfBool, "disable-token": tfBool, "reset-token": tfBool,
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookResetURL_RequiresAppEnv(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-url": "true"})
|
||||
err := runWebhookURLReset(rctx)
|
||||
assertValidationParamError(t, err, "--app-env")
|
||||
}
|
||||
|
||||
func TestWebhookResetURL_InvalidAppEnv(t *testing.T) {
|
||||
rctx, _, _ := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-url": "true", "app-env": "prod"})
|
||||
err := runWebhookURLReset(rctx)
|
||||
assertValidationParamError(t, err, "--app-env")
|
||||
}
|
||||
|
||||
func TestWebhookResetURL_PostsAppEnv(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-url": "true", "app-env": "preview"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1/webhook/url/reset",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"preview_url": "https://new-preview"}},
|
||||
})
|
||||
if err := runWebhookURLReset(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "new-preview") {
|
||||
t.Errorf("reset-url must return new URL: %s", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookEnableToken_SurfacesTokenOnce(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "enable-token": "true"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1/webhook/token/status",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"token_value": "test-token"}},
|
||||
})
|
||||
if err := runWebhookTokenStatus(rctx, true); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
out := stdoutBuf.String()
|
||||
if !strings.Contains(out, "test-token") {
|
||||
t.Errorf("enable-token must surface token once: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWebhookDisableToken covers the runWebhookTokenStatus(_, false) branch,
|
||||
// which posts the same endpoint with enabled=false and does NOT surface a token
|
||||
// (backend must not return a token_value when disabling).
|
||||
func TestWebhookDisableToken(t *testing.T) {
|
||||
rctx, _, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "disable-token": "true"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1/webhook/token/status",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"token_enabled": false}},
|
||||
})
|
||||
if err := runWebhookTokenStatus(rctx, false); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWebhookResetToken covers the reset-token endpoint: it must surface the
|
||||
// rotated token value once so operators can capture it.
|
||||
func TestWebhookResetToken(t *testing.T) {
|
||||
rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, automationUpdateFlagDefs(),
|
||||
map[string]string{"app-id": "app_x", "name": "wh1", "reset-token": "true"})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/triggers/wh1/webhook/token/reset",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"token_value": "test-token"}},
|
||||
})
|
||||
if err := runWebhookTokenReset(rctx); err != nil {
|
||||
t.Fatalf("Execute() = %v", err)
|
||||
}
|
||||
if !strings.Contains(stdoutBuf.String(), "test-token") {
|
||||
t.Errorf("reset-token must surface rotated token once: %s", stdoutBuf.String())
|
||||
}
|
||||
}
|
||||
@@ -101,16 +101,14 @@ func TestAppsDBAuditEnable_DryRunAndSuccess(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.Data.API[0]
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != dbAuditSetURL || a.Body["enabled"] != true || a.Body["retention"] != "30d" || a.Body["table"] != "orders" {
|
||||
t.Fatalf("dry-run = %s %s body=%v", a.Method, a.URL, a.Body)
|
||||
}
|
||||
@@ -138,15 +136,13 @@ func TestAppsDBAuditDisable_DryRunAndSuccess(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if env.Data.API[0].Body["enabled"] != false || env.Data.API[0].Body["table"] != "orders" {
|
||||
t.Fatalf("dry-run body=%v (want enabled:false)", env.Data.API[0].Body)
|
||||
if env.API[0].Body["enabled"] != false || env.API[0].Body["table"] != "orders" {
|
||||
t.Fatalf("dry-run body=%v (want enabled:false)", env.API[0].Body)
|
||||
}
|
||||
|
||||
factory2, stdout2, reg := newAppsExecuteFactory(t)
|
||||
@@ -182,16 +178,14 @@ func TestAppsDBAuditList_DryRunJoinsTables(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
} `json:"data"`
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.Data.API[0]
|
||||
a := env.API[0]
|
||||
if a.Method != "GET" || a.URL != dbAuditListURL || a.Params["tables"] != "orders,users" {
|
||||
t.Fatalf("dry-run = %s %s tables=%v", a.Method, a.URL, a.Params["tables"])
|
||||
}
|
||||
|
||||
@@ -37,7 +37,13 @@ func TestAppsDBChangelogList_DryRunFiltersAndTimeNormalize(t *testing.T) {
|
||||
"--change-id", "01J", "--since", "2026-01-01", "--page-size", "5", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "GET" || a.URL != dbChangelogURL {
|
||||
|
||||
@@ -71,7 +71,13 @@ func TestAppsDBDataExport_DryRunFormatFromOutput(t *testing.T) {
|
||||
if err := runAppsShortcut(t, AppsDBDataExport, args, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "GET" || a.URL != dbDataExportURL {
|
||||
|
||||
@@ -97,7 +97,14 @@ func TestAppsDBDataImport_DryRunMultipartShape(t *testing.T) {
|
||||
[]string{"+db-data-import", "--app-id", "app_x", "--file", "orders.csv", "--environment", "dev", "--dry-run", "--yes", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env 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"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != dbDataImportURL {
|
||||
@@ -124,11 +131,12 @@ func TestAppsDBDataImport_DryRunOmitsEnvWhenUnset(t *testing.T) {
|
||||
[]string{"+db-data-import", "--app-id", "app_x", "--file", "orders.csv", "--dry-run", "--yes", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if len(env.API) != 1 {
|
||||
t.Fatalf("dry-run API calls = %d, want 1; stdout=%s", len(env.API), stdout.String())
|
||||
var env struct {
|
||||
API []struct {
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
p := env.API[0].Params
|
||||
if _, ok := p["env"]; ok {
|
||||
t.Fatalf("no --environment → env key must be omitted, got params=%v", p)
|
||||
@@ -166,7 +174,11 @@ func TestAppsDBDataImport_TableDefaultsToFileBasename(t *testing.T) {
|
||||
[]string{"+db-data-import", "--app-id", "app_x", "--file", "customers.json", "--dry-run", "--yes", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if env.API[0].Params["table"] != "customers" {
|
||||
t.Fatalf("expected table=customers (from file basename) in params, got %v", env.API[0].Params)
|
||||
|
||||
@@ -30,7 +30,13 @@ func TestAppsDBEnvDiff_DryRunBody(t *testing.T) {
|
||||
[]string{"+db-env-diff", "--app-id", "app_x", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != dbEnvMigrateURL || a.Body["dry_run"] != true {
|
||||
@@ -85,7 +91,11 @@ func TestAppsDBEnvMigrate_DryRunBody(t *testing.T) {
|
||||
[]string{"+db-env-migrate", "--app-id", "app_x", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if env.API[0].Body["dry_run"] != false {
|
||||
t.Fatalf("dry-run body=%v (want dry_run:false)", env.API[0].Body)
|
||||
@@ -170,7 +180,13 @@ func TestAppsDBRecoveryDiff_DryRunNormalizesTarget(t *testing.T) {
|
||||
[]string{"+db-recovery-diff", "--app-id", "app_x", "--target", "2026-04-15", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != dbRecoveryURL || a.Body["dry_run"] != true {
|
||||
@@ -315,11 +331,14 @@ func TestAppsDBQuotaGet_DryRunOmitsEnvWhenUnset(t *testing.T) {
|
||||
[]string{"+db-quota-get", "--app-id", "app_x", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if len(env.API) != 1 {
|
||||
t.Fatalf("dry-run API calls = %d, want 1; stdout=%s", len(env.API), stdout.String())
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "GET" || a.URL != dbQuotaURL {
|
||||
t.Fatalf("dry-run = %s %s", a.Method, a.URL)
|
||||
|
||||
@@ -165,7 +165,14 @@ func TestAppsDBExecute_DryRunSendsTransactionalFalse(t *testing.T) {
|
||||
factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &env); err != nil {
|
||||
t.Fatalf("decode: %v\n%s", err, stdout.String())
|
||||
}
|
||||
@@ -247,7 +254,11 @@ func TestAppsDBExecute_FileReadsSQLIntoBody(t *testing.T) {
|
||||
factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &env); err != nil {
|
||||
t.Fatalf("decode: %v\n%s", err, stdout.String())
|
||||
}
|
||||
|
||||
@@ -79,7 +79,11 @@ func TestAppsDBTableGet_NonPrettyFormatsOmitFormatQuery(t *testing.T) {
|
||||
if err := runAppsShortcut(t, AppsDBTableGet, args, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &env); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
|
||||
@@ -165,7 +165,13 @@ func TestAppsDBTableList_DryRunSendsPaginationAndEnv(t *testing.T) {
|
||||
factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
@@ -190,7 +196,11 @@ func TestAppsDBTableList_DoesNotSendIncludeStatsQuery(t *testing.T) {
|
||||
factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &env); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
|
||||
@@ -149,7 +149,11 @@ func TestAppsEnvVarList_DryRunIncludesScene(t *testing.T) {
|
||||
}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var dryRun dryRunAPIEnvelope
|
||||
var dryRun struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &dryRun); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
@@ -224,7 +228,11 @@ func TestAppsEnvVarSet_OnlineDryRunDoesNotRequireYes(t *testing.T) {
|
||||
t.Fatalf("dry-run missing %q: %s", want, got)
|
||||
}
|
||||
}
|
||||
var dryRun dryRunAPIEnvelope
|
||||
var dryRun struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(got), &dryRun); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, got)
|
||||
}
|
||||
@@ -345,7 +353,13 @@ func TestAppsEnvVarDelete_OnlineDryRunDoesNotRequireYes(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
|
||||
var dryRun dryRunAPIEnvelope
|
||||
var dryRun struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
got := stdout.String()
|
||||
if err := json.Unmarshal([]byte(got), &dryRun); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, got)
|
||||
|
||||
@@ -48,7 +48,13 @@ func TestAppsFileDelete_DryRunSendsPaths(t *testing.T) {
|
||||
[]string{"+file-delete", "--app-id", "app_x", "--path", "/a.png", "--path", "/b.png", "--yes", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != fileDeleteURL {
|
||||
|
||||
@@ -41,7 +41,12 @@ func TestAppsFileDownload_DryRunSignsFirst(t *testing.T) {
|
||||
[]string{"+file-download", "--app-id", "app_x", "--path", "/x.png", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if env.API[0].Method != "POST" || env.API[0].URL != fileSignURLForDownload {
|
||||
t.Fatalf("dry-run = %s %s (want POST sign)", env.API[0].Method, env.API[0].URL)
|
||||
|
||||
@@ -46,7 +46,13 @@ func TestAppsFileGet_DryRunSendsPathQuery(t *testing.T) {
|
||||
[]string{"+file-get", "--app-id", "app_x", "--path", "/x.png", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
if env.API[0].Method != "GET" || env.API[0].URL != fileGetURL || env.API[0].Params["path"] != "/x.png" {
|
||||
t.Fatalf("dry-run = %s %s params=%v", env.API[0].Method, env.API[0].URL, env.API[0].Params)
|
||||
|
||||
@@ -95,7 +95,13 @@ func TestAppsFileList_DryRunSendsFiltersAndPagination(t *testing.T) {
|
||||
factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
@@ -133,7 +139,11 @@ func TestAppsFileList_DryRunOmitsEmptyFilters(t *testing.T) {
|
||||
[]string{"+file-list", "--app-id", "app_x", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Params map[string]interface{} `json:"params"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
for _, banned := range []string{"name", "path", "type", "size_gt", "size_lt", "uploaded_since", "uploaded_until", "page_token"} {
|
||||
if _, ok := env.API[0].Params[banned]; ok {
|
||||
|
||||
@@ -22,7 +22,13 @@ func TestAppsFileSign_DryRunBody(t *testing.T) {
|
||||
[]string{"+file-sign", "--app-id", "app_x", "--path", "/x.png", "--expires-in", "3600", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != fileSignURL || a.Body["path"] != "/x.png" {
|
||||
|
||||
@@ -76,7 +76,13 @@ func TestAppsFileUpload_DryRunPreUpload(t *testing.T) {
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", "logo.png", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stdout.String()), &env)
|
||||
a := env.API[0]
|
||||
if a.Method != "POST" || a.URL != "/open-apis/spark/v1/apps/app_x/storage/file_pre_upload" {
|
||||
|
||||
@@ -737,12 +737,15 @@ func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buf
|
||||
}
|
||||
|
||||
func TestAppsInit_Req1_Wording(t *testing.T) {
|
||||
// The --dry-run output is a flat object (DryRunAPI marshals to top-level keys
|
||||
// description/scaffold/api/...), NOT wrapped in {"data":...}, so parse stdout
|
||||
// directly rather than via parseEnvelopeData.
|
||||
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)
|
||||
}
|
||||
data, err := decodeDryRunDataMap(stdout.Bytes())
|
||||
if err != nil {
|
||||
var data map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &data); err != nil {
|
||||
t.Fatalf("decode dry-run output: %v (raw=%q)", err, stdout.String())
|
||||
}
|
||||
desc, _ := data["description"].(string)
|
||||
@@ -1444,8 +1447,8 @@ func TestAppsInit_DryRun_DescribesEnvPull(t *testing.T) {
|
||||
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user", "--dry-run"}, factory, stdout); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
m, err := decodeDryRunDataMap(stdout.Bytes())
|
||||
if err != nil {
|
||||
var m map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &m); err != nil {
|
||||
t.Fatalf("decode dry-run: %v (raw=%q)", err, stdout.String())
|
||||
}
|
||||
ep, _ := m["env_pull"].(string)
|
||||
|
||||
@@ -25,7 +25,13 @@ func TestAppsLogList_DryRunBuildsSearchLogsBody(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
|
||||
@@ -39,7 +39,13 @@ func TestAppsMetricList_DryRunUsesSeconds(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
@@ -84,7 +90,11 @@ func TestAppsMetricList_AutoDownSampleByRange(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
|
||||
@@ -24,7 +24,13 @@ func TestAppsTraceList_DryRunBuildsSearchTracesBody(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
@@ -67,7 +73,13 @@ func TestAppsTraceGet_DryRunBuildsGetTraceBody(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
|
||||
var env dryRunAPIEnvelope
|
||||
var env struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode dry-run: %v\n%s", err, stdout.String())
|
||||
}
|
||||
|
||||
@@ -1,453 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// automationBasePath 是触发器公网 OpenAPI 前缀。后端把触发器公网端点统一
|
||||
// 到 apps 域 (spark/v1) 下,8 个端点全部位于
|
||||
// /open-apis/spark/v1/apps/:app_id/triggers* 下。这里直接复用同包的
|
||||
// apiBasePath 而不是自定义前缀,避免误用早期的备选前缀。
|
||||
const automationBasePath = apiBasePath
|
||||
|
||||
func automationListPath(appID string) string {
|
||||
return fmt.Sprintf(automationBasePath+"/apps/%s/triggers", validate.EncodePathSegment(appID))
|
||||
}
|
||||
|
||||
func automationItemPath(appID, name string) string {
|
||||
return fmt.Sprintf(automationBasePath+"/apps/%s/triggers/%s",
|
||||
validate.EncodePathSegment(appID), validate.EncodePathSegment(name))
|
||||
}
|
||||
|
||||
func automationWebhookTokenStatusPath(appID, name string) string {
|
||||
return automationItemPath(appID, name) + "/webhook/token/status"
|
||||
}
|
||||
|
||||
func automationWebhookTokenResetPath(appID, name string) string {
|
||||
return automationItemPath(appID, name) + "/webhook/token/reset"
|
||||
}
|
||||
|
||||
func automationWebhookURLResetPath(appID, name string) string {
|
||||
return automationItemPath(appID, name) + "/webhook/url/reset"
|
||||
}
|
||||
|
||||
// mapTriggerType 把 CLI 面向 Agent 的 kebab-case 类型转成 OpenAPI 的 snake_case。
|
||||
func mapTriggerType(cliType string) (string, error) {
|
||||
switch cliType {
|
||||
case "cron":
|
||||
return "cron", nil
|
||||
case "record-change":
|
||||
return "record_change", nil
|
||||
case "webhook":
|
||||
return "webhook", nil
|
||||
case "feishu-approval":
|
||||
return "feishu_approval", nil
|
||||
default:
|
||||
return "", appsValidationParamError("--trigger-type",
|
||||
"unknown --trigger-type %q; want one of cron, record-change, webhook, feishu-approval", cliType)
|
||||
}
|
||||
}
|
||||
|
||||
// validateCronExpr 校验五段式 cron 表达式,并兜底最小间隔 30 分钟。
|
||||
// 这是给 Agent 的即时提示;后端 OpenAPI 层也会校验(ErrInvalidCronTab /
|
||||
// ErrCronIntervalTooSmall),CLI 本地拦截只为更快反馈。
|
||||
//
|
||||
// Minute field accepted forms:
|
||||
// - "N" (single value 0-59)
|
||||
// - "N,M,..." (comma list of single values; min pairwise gap incl. wrap >= 30)
|
||||
// - "*/N" (step from 0; N must be >= 30)
|
||||
//
|
||||
// Anything else (ranges like "N-M", stepped ranges like "N-M/S",
|
||||
// range shorthands like "0/10", question marks) is rejected up-front with a
|
||||
// typed --cron error. A previous version accepted "1-59/10" through the
|
||||
// fallthrough because none of the three matchers claimed it, and the caller
|
||||
// only found out the interval was 10 minutes when the backend rejected it
|
||||
// (or worse, silently accepted a schedule the operator did not intend).
|
||||
func validateCronExpr(expr string) error {
|
||||
fields := strings.Fields(strings.TrimSpace(expr))
|
||||
if len(fields) != 5 {
|
||||
return appsValidationParamError("--cron",
|
||||
"cron must have 5 fields (minute hour day month weekday), got %d in %q", len(fields), expr)
|
||||
}
|
||||
minute := fields[0]
|
||||
if minute == "*" {
|
||||
return appsValidationParamError("--cron",
|
||||
"cron minute field '*' means every minute; minimum interval is 30 minutes")
|
||||
}
|
||||
if strings.HasPrefix(minute, "*/") {
|
||||
n, err := strconv.Atoi(strings.TrimPrefix(minute, "*/"))
|
||||
if err != nil || n < 1 || n > 59 {
|
||||
return appsValidationParamError("--cron",
|
||||
"cron minute step %q must be an integer 1..59", minute)
|
||||
}
|
||||
// */N in cron expands to [0, N, 2N, ...] within 0..59, then wraps to 0
|
||||
// of the next hour. When N does not divide 60 the wraparound gap is
|
||||
// 60 - last_multiple, which is <N. For the 30-minute floor to hold on
|
||||
// every gap (in-hour AND wrap), *only* N=30 works: */30 fires at :00
|
||||
// and :30, gaps [30, 30]. */45 fires at :00 and :45, gaps [45, 15] —
|
||||
// the 15-min wraparound gap violates the floor. All 31..59 fail the
|
||||
// same way (small wraparound remainder); 1..29 fail the in-hour gap.
|
||||
if n != 30 {
|
||||
return appsValidationParamError("--cron",
|
||||
"cron step */%d produces a gap below the 30-minute minimum "+
|
||||
"(only */30 keeps every gap >=30 including the wraparound); "+
|
||||
"use */30, or an explicit list like '0,30'", n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.Contains(minute, ",") {
|
||||
parts := strings.Split(minute, ",")
|
||||
vals := make([]int, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil || n < 0 || n > 59 {
|
||||
return appsValidationParamError("--cron",
|
||||
"cron minute list entry %q must be an integer 0..59", p)
|
||||
}
|
||||
vals = append(vals, n)
|
||||
}
|
||||
if len(vals) >= 2 {
|
||||
sort.Ints(vals)
|
||||
minGap := 60
|
||||
for i := 1; i < len(vals); i++ {
|
||||
if gap := vals[i] - vals[i-1]; gap < minGap {
|
||||
minGap = gap
|
||||
}
|
||||
}
|
||||
if wrapGap := vals[0] + 60 - vals[len(vals)-1]; wrapGap < minGap {
|
||||
minGap = wrapGap
|
||||
}
|
||||
if minGap < 30 {
|
||||
return appsValidationParamError("--cron",
|
||||
"cron minute list %q has %d-min interval; minimum interval is 30 minutes", minute, minGap)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Bare single value fallthrough. Reject range/step-range/anything else so
|
||||
// forms like "1-59/10" (10-min interval) and "0/10" (10-min interval)
|
||||
// cannot bypass the 30-minute floor. The backend enforces its own cron
|
||||
// rules, but the CLI stays strict about which forms it accepts so callers
|
||||
// get an early, unambiguous error.
|
||||
if n, err := strconv.Atoi(minute); err == nil && n >= 0 && n <= 59 {
|
||||
return nil
|
||||
}
|
||||
return appsValidationParamError("--cron",
|
||||
"unsupported cron minute syntax %q; use N (0..59), N,M,... (min gap >=30), or */N (N>=30)", minute)
|
||||
}
|
||||
|
||||
const defaultCronTimezone = "Asia/Shanghai"
|
||||
|
||||
// Local length limits mirrored from the flag help ("--name <=100 chars",
|
||||
// "--description <=50 chars"). Enforcing here catches a violation before the
|
||||
// API round-trip and returns a typed --name / --description error, whereas
|
||||
// hitting the backend surfaces an opaque business error the agent has to
|
||||
// diagnose. Constants (not magic numbers) so the flag help and the check
|
||||
// share one source of truth if the backend ever renegotiates the limits.
|
||||
const (
|
||||
automationNameMaxLen = 100
|
||||
automationDescriptionMaxLen = 50
|
||||
)
|
||||
|
||||
// validateAutomationNameLen guards against a --name that would be rejected by
|
||||
// the backend on length. Empty is intentionally permitted here — the required
|
||||
// check lives in the create Validate hook (which fires first) and in Update
|
||||
// the flag is not required at all. Counts runes, not bytes: the flag help
|
||||
// documents "<=100 chars", and Chinese/emoji names would be silently rejected
|
||||
// well below the char limit if we counted UTF-8 bytes.
|
||||
func validateAutomationNameLen(name string) error {
|
||||
if n := utf8.RuneCountInString(name); n > automationNameMaxLen {
|
||||
return appsValidationParamError("--name",
|
||||
"--name must be at most %d chars, got %d", automationNameMaxLen, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateAutomationDescriptionLen guards --description length; empty passes.
|
||||
// Counts runes for the same reason as validateAutomationNameLen.
|
||||
func validateAutomationDescriptionLen(desc string) error {
|
||||
if n := utf8.RuneCountInString(desc); n > automationDescriptionMaxLen {
|
||||
return appsValidationParamError("--description",
|
||||
"--description must be at most %d chars, got %d", automationDescriptionMaxLen, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// conditionFlagFamily maps each condition-carrying flag to the trigger-type
|
||||
// family it belongs to. Used by create/update to reject cross-type flag
|
||||
// combinations up-front (e.g. --trigger-type webhook --cron '0 9 * * *'
|
||||
// silently dropped --cron before this guard).
|
||||
//
|
||||
// --timezone is a modifier on --cron, so it lives in the cron family.
|
||||
// --description is trigger-type-agnostic and NOT in this map — it can pair
|
||||
// with any type on create and can appear alone on update.
|
||||
var conditionFlagFamily = map[string]string{
|
||||
"cron": "cron",
|
||||
"timezone": "cron",
|
||||
"table": "record-change",
|
||||
"event": "record-change",
|
||||
"fields": "record-change",
|
||||
"white-ip-list": "webhook",
|
||||
"event-type": "feishu-approval",
|
||||
"instance-status": "feishu-approval",
|
||||
"task-status": "feishu-approval",
|
||||
"approval-code": "feishu-approval",
|
||||
}
|
||||
|
||||
// flagIsSet reports whether a condition-carrying flag has a caller-provided
|
||||
// value. string and string-array types both need to be probed; a nil / empty
|
||||
// value counts as unset.
|
||||
func flagIsSet(rctx *common.RuntimeContext, name string) bool {
|
||||
if v := strings.TrimSpace(rctx.Str(name)); v != "" {
|
||||
return true
|
||||
}
|
||||
if arr := rctx.StrArray(name); len(arr) > 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// familiesInUse returns the set of trigger-type families whose condition flags
|
||||
// the caller has set on this invocation. A trigger has exactly one type, so
|
||||
// legitimate condition writes involve at most one family; anything else is a
|
||||
// user mistake that must not slip through to the backend.
|
||||
func familiesInUse(rctx *common.RuntimeContext) map[string]string {
|
||||
out := map[string]string{}
|
||||
for flag, family := range conditionFlagFamily {
|
||||
if flagIsSet(rctx, flag) {
|
||||
out[family] = flag
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// familiesMixedList renders a comma-separated, sorted list of families
|
||||
// currently in use for inclusion in the multi-family rejection error. Stable
|
||||
// order keeps the error message deterministic across Go's random map
|
||||
// iteration.
|
||||
func familiesMixedList(families map[string]string) string {
|
||||
names := make([]string, 0, len(families))
|
||||
for name := range families {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
// rejectCrossFamilyCondFlags rejects any condition flag that does not belong
|
||||
// to `wantFamily`. Returns a typed --<flag> error naming the first offending
|
||||
// flag encountered. Deterministic ordering (iterated over a stable slice)
|
||||
// keeps the error message reproducible for tests.
|
||||
func rejectCrossFamilyCondFlags(rctx *common.RuntimeContext, wantFamily string) error {
|
||||
// Stable iteration order for a deterministic Param on error.
|
||||
order := []string{
|
||||
"cron", "timezone",
|
||||
"table", "event", "fields",
|
||||
"white-ip-list",
|
||||
"event-type", "instance-status", "task-status", "approval-code",
|
||||
}
|
||||
for _, flag := range order {
|
||||
if conditionFlagFamily[flag] != wantFamily && flagIsSet(rctx, flag) {
|
||||
return appsValidationParamError("--"+flag,
|
||||
"--%s belongs to trigger-type %q, not %q; drop it or change --trigger-type",
|
||||
flag, conditionFlagFamily[flag], wantFamily)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// approvalStatusSets 是 feishu-approval 两种 event-type 各自的合法状态集合。
|
||||
// 后端 OpenAPI 不逐值校验 status,CLI 本地分桶校验是唯一保障。
|
||||
var approvalStatusSets = map[string]map[string]struct{}{
|
||||
"approval_instance": setOf("PENDING", "APPROVED", "REJECTED", "CANCELED", "DELETED", "REVERTED", "OVERTIME_CLOSE", "OVERTIME_RECOVER"),
|
||||
"approval_task": setOf("REVERTED", "PENDING", "APPROVED", "REJECTED", "TRANSFERRED", "ROLLBACK", "DONE", "OVERTIME_CLOSE", "OVERTIME_RECOVER"),
|
||||
}
|
||||
|
||||
func setOf(items ...string) map[string]struct{} {
|
||||
m := make(map[string]struct{}, len(items))
|
||||
for _, it := range items {
|
||||
m[it] = struct{}{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// buildCronCondition 产出 OpenAPI 层 cron_condition body。缺省时区补 Asia/Shanghai。
|
||||
func buildCronCondition(expr, tz string) (map[string]interface{}, error) {
|
||||
if err := validateCronExpr(expr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(tz) == "" {
|
||||
tz = defaultCronTimezone
|
||||
}
|
||||
return map[string]interface{}{"cron": strings.TrimSpace(expr), "timezone": tz}, nil
|
||||
}
|
||||
|
||||
// recordChangeEventSet 是 record-change 触发器合法 event 枚举。
|
||||
// 4 个值来自需求定义。CLI 本地做白名单校验,
|
||||
// 避免后端 event 字段校验缺失导致的"接受任意字符串→触发器永不触发"问题。
|
||||
var recordChangeEventSet = setOf("INSERT", "UPDATE", "UPSERT", "DELETE")
|
||||
|
||||
// buildRecordChangeCondition 产出 record_change_condition body;event 大写化。
|
||||
func buildRecordChangeCondition(table, event string, fields []string) (map[string]interface{}, error) {
|
||||
if strings.TrimSpace(table) == "" {
|
||||
return nil, appsValidationParamError("--table", "--table is required for record-change triggers")
|
||||
}
|
||||
ev := strings.ToUpper(strings.TrimSpace(event))
|
||||
if ev == "" {
|
||||
return nil, appsValidationParamError("--event", "--event is required for record-change triggers (INSERT/UPDATE/UPSERT/DELETE)")
|
||||
}
|
||||
if _, valid := recordChangeEventSet[ev]; !valid {
|
||||
return nil, appsValidationParamError("--event",
|
||||
"--event %q is not a valid record-change event; want one of INSERT, UPDATE, UPSERT, DELETE", event)
|
||||
}
|
||||
cond := map[string]interface{}{"event": ev, "table": strings.TrimSpace(table)}
|
||||
if len(fields) > 0 {
|
||||
cond["fields"] = fields
|
||||
}
|
||||
return cond, nil
|
||||
}
|
||||
|
||||
// buildWebhookCondition 产出 webhook_condition body。white_ip_list 在后端契约
|
||||
// 里是 required,因此当 CLI 侧未传 --white-ip-list 时也发一个空数组,避免后端
|
||||
// 拒收;显式空数组 `[]` 与"不限来源 IP"语义一致(呼应无鉴权公网回调告警)。
|
||||
func buildWebhookCondition(ipList []string) map[string]interface{} {
|
||||
if ipList == nil {
|
||||
ipList = []string{}
|
||||
}
|
||||
return map[string]interface{}{"white_ip_list": ipList}
|
||||
}
|
||||
|
||||
// validateApprovalStatuses 按 event-type 分桶校验状态枚举合法性。
|
||||
func validateApprovalStatuses(eventType string, statuses []string) error {
|
||||
set, ok := approvalStatusSets[eventType]
|
||||
if !ok {
|
||||
return appsValidationParamError("--event-type",
|
||||
"unknown --event-type %q; want approval_task or approval_instance", eventType)
|
||||
}
|
||||
if len(statuses) == 0 {
|
||||
flag := statusFlagFor(eventType)
|
||||
return appsValidationParamError("--"+flag,
|
||||
"--%s is required for event-type %q (at least one status)", flag, eventType)
|
||||
}
|
||||
for _, s := range statuses {
|
||||
if _, valid := set[strings.ToUpper(strings.TrimSpace(s))]; !valid {
|
||||
// 列出该 event-type 的合法状态集合,便于 Agent 修正。
|
||||
return appsValidationParamError("--"+statusFlagFor(eventType),
|
||||
"status %q is not valid for event-type %q; valid values: %s",
|
||||
s, eventType, sortedStatusList(set))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sortedStatusList 返回状态集合的稳定排序、逗号分隔字符串,用于错误提示。
|
||||
func sortedStatusList(set map[string]struct{}) string {
|
||||
out := make([]string, 0, len(set))
|
||||
for s := range set {
|
||||
out = append(out, s)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
func statusFlagFor(eventType string) string {
|
||||
if eventType == "approval_task" {
|
||||
return "task-status"
|
||||
}
|
||||
return "instance-status"
|
||||
}
|
||||
|
||||
// buildApprovalCondition 产出 feishu_approval_condition body。approval_code 可选:
|
||||
// 空则省略(匹配所有审批定义),不发空串。
|
||||
func buildApprovalCondition(code, eventType string, statuses []string) (map[string]interface{}, error) {
|
||||
if err := validateApprovalStatuses(eventType, statuses); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cond := map[string]interface{}{"event_type": eventType, "status": statuses}
|
||||
if strings.TrimSpace(code) != "" {
|
||||
cond["approval_code"] = strings.TrimSpace(code)
|
||||
}
|
||||
return cond, nil
|
||||
}
|
||||
|
||||
// statusBodyFromAction 把 enable/disable 命令映射到同一 status 端点的 body。
|
||||
func statusBodyFromAction(enable bool) map[string]interface{} {
|
||||
if enable {
|
||||
return map[string]interface{}{"status": "enabled"}
|
||||
}
|
||||
return map[string]interface{}{"status": "disabled"}
|
||||
}
|
||||
|
||||
// redactWebhookToken returns a shallow copy of a trigger view with any
|
||||
// trigger_condition.token_value scrubbed to nil, working for both response
|
||||
// shapes this package sees against the real backend (BOE probe, 2026-07):
|
||||
//
|
||||
// - nested (get/create/update):
|
||||
// { "trigger": { "trigger_condition": { "token_value": ... } } }
|
||||
// - flat (list items):
|
||||
// { "trigger_condition": { "token_value": ... } }
|
||||
//
|
||||
// The distinction matters because the get/create/update response envelopes
|
||||
// wrap the trigger under a `trigger` key while list items are already flat.
|
||||
// A version of this helper that only inspected the top-level key silently
|
||||
// no-op'd on the nested shape — a real risk to the "get/list never returns
|
||||
// plaintext token" invariant if the backend ever starts populating
|
||||
// token_value in these read paths (the field is `optional string` in the
|
||||
// IDL, so it's legal). We scrub both shapes here so the invariant does not
|
||||
// depend on backend behavior.
|
||||
//
|
||||
// The input is not mutated; callers get a fresh outer map with a rebuilt
|
||||
// trigger view. Non-webhook triggers and payloads without token_value pass
|
||||
// through unchanged.
|
||||
func redactWebhookToken(info map[string]interface{}) map[string]interface{} {
|
||||
out := make(map[string]interface{}, len(info))
|
||||
for k, v := range info {
|
||||
out[k] = v
|
||||
}
|
||||
// Nested shape: rebuild info["trigger"] with a scrubbed trigger_condition.
|
||||
if wrapped, ok := info["trigger"].(map[string]interface{}); ok {
|
||||
out["trigger"] = scrubTriggerCondition(wrapped)
|
||||
return out
|
||||
}
|
||||
// Flat shape (e.g. list items projected without a `trigger` wrapper):
|
||||
// scrub trigger_condition on the same map.
|
||||
if _, hasFlat := info["trigger_condition"].(map[string]interface{}); hasFlat {
|
||||
return scrubTriggerCondition(out)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// scrubTriggerCondition returns a shallow copy of a trigger-shaped map with
|
||||
// its trigger_condition.token_value replaced by nil. Called by
|
||||
// redactWebhookToken for each shape it recognizes.
|
||||
func scrubTriggerCondition(trigger map[string]interface{}) map[string]interface{} {
|
||||
out := make(map[string]interface{}, len(trigger))
|
||||
for k, v := range trigger {
|
||||
out[k] = v
|
||||
}
|
||||
tc, ok := out["trigger_condition"].(map[string]interface{})
|
||||
if !ok {
|
||||
return out
|
||||
}
|
||||
redactedTC := make(map[string]interface{}, len(tc))
|
||||
for k, v := range tc {
|
||||
if k == "token_value" {
|
||||
redactedTC[k] = nil
|
||||
continue
|
||||
}
|
||||
redactedTC[k] = v
|
||||
}
|
||||
out["trigger_condition"] = redactedTC
|
||||
return out
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAutomationPaths(t *testing.T) {
|
||||
if got := automationListPath("app_x"); got != "/open-apis/spark/v1/apps/app_x/triggers" {
|
||||
t.Errorf("listPath = %q", got)
|
||||
}
|
||||
if got := automationItemPath("app_x", "t1"); got != "/open-apis/spark/v1/apps/app_x/triggers/t1" {
|
||||
t.Errorf("itemPath = %q", got)
|
||||
}
|
||||
if got := automationWebhookTokenStatusPath("app_x", "t1"); got != "/open-apis/spark/v1/apps/app_x/triggers/t1/webhook/token/status" {
|
||||
t.Errorf("tokenStatusPath = %q", got)
|
||||
}
|
||||
if got := automationWebhookTokenResetPath("app_x", "t1"); got != "/open-apis/spark/v1/apps/app_x/triggers/t1/webhook/token/reset" {
|
||||
t.Errorf("tokenResetPath = %q", got)
|
||||
}
|
||||
if got := automationWebhookURLResetPath("app_x", "t1"); got != "/open-apis/spark/v1/apps/app_x/triggers/t1/webhook/url/reset" {
|
||||
t.Errorf("urlResetPath = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateAutomationNameLen_CountsRunes pins the char-not-byte contract:
|
||||
// the flag help documents "<=100 chars", and Chinese/emoji names would be
|
||||
// silently rejected below the char limit if we counted UTF-8 bytes.
|
||||
// A 100-rune Chinese string is 300 bytes but is 100 chars — must pass.
|
||||
func TestValidateAutomationNameLen_CountsRunes(t *testing.T) {
|
||||
// 100 Chinese characters (each 3 UTF-8 bytes = 300 bytes total). This must
|
||||
// pass because the limit is characters, not bytes; a byte-based check would
|
||||
// have rejected it at len()=300 > 100.
|
||||
name := strings.Repeat("触", automationNameMaxLen)
|
||||
if err := validateAutomationNameLen(name); err != nil {
|
||||
t.Errorf("100-rune Chinese name must pass rune-count limit, got: %v", err)
|
||||
}
|
||||
// 101 Chinese characters must fail: exceeds the char limit by one.
|
||||
over := strings.Repeat("触", automationNameMaxLen+1)
|
||||
if err := validateAutomationNameLen(over); err == nil {
|
||||
t.Error("101-rune Chinese name must fail rune-count limit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapTriggerType(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"cron": "cron", "record-change": "record_change",
|
||||
"webhook": "webhook", "feishu-approval": "feishu_approval",
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, err := mapTriggerType(in)
|
||||
if err != nil || got != want {
|
||||
t.Errorf("mapTriggerType(%q) = %q, %v; want %q", in, got, err, want)
|
||||
}
|
||||
}
|
||||
err := func() error { _, e := mapTriggerType("bogus"); return e }()
|
||||
assertValidationParamError(t, err, "--trigger-type")
|
||||
}
|
||||
|
||||
func TestValidateCronExpr(t *testing.T) {
|
||||
if err := validateCronExpr("0 9 * * *"); err != nil {
|
||||
t.Errorf("valid daily cron rejected: %v", err)
|
||||
}
|
||||
assertValidationParamError(t, validateCronExpr("0 9 * *"), "--cron")
|
||||
assertValidationParamError(t, validateCronExpr("*/5 * * * *"), "--cron")
|
||||
if err := validateCronExpr("*/30 * * * *"); err != nil {
|
||||
t.Errorf("30-minute interval must pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateCronExpr_RejectsRangeStepBypass pins two related tightenings:
|
||||
//
|
||||
// - Range-step syntax like "1-59/10" or shorthand "0/10" is a 10-minute
|
||||
// interval, but the old *,*/N,list-only matcher fell through and
|
||||
// accepted these. The new whitelist rejects any minute form outside
|
||||
// {"N", "N,M,...", "*/N"}.
|
||||
// - */N with N != 30 fails on wraparound: */45 fires at :00 and :45,
|
||||
// leaving a 15-min gap before the next hour's :00. In standard cron,
|
||||
// */N expands to [0, N, 2N, ...] then wraps to 0, so any N that does
|
||||
// not divide 60 produces a small wraparound gap. Only N=30 keeps
|
||||
// every gap (in-hour AND wrap) >= 30.
|
||||
func TestValidateCronExpr_RejectsRangeStepBypass(t *testing.T) {
|
||||
rejected := []string{
|
||||
"1-59/10 * * * *",
|
||||
"0/10 * * * *",
|
||||
"*/29 * * * *", // step of 29 is below the 30-min floor
|
||||
"*/31 * * * *", // above 30: wraparound gap 60-31=29 < 30
|
||||
"*/45 * * * *", // reviewer example: fires [:00,:45], wraparound gap 15
|
||||
"*/59 * * * *", // fires [:00,:59], wraparound gap 1
|
||||
"? * * * *", // range/? shorthand not supported
|
||||
"5-25 * * * *", // plain range not supported (backend may accept it, but CLI stays strict)
|
||||
"5,10 * * * *", // 5-min gap in comma list
|
||||
"foo * * * *", // garbage
|
||||
"1,foo * * * *", // partially invalid list
|
||||
"60 * * * *", // out of range
|
||||
"1,60 * * * *", // list out of range
|
||||
}
|
||||
for _, expr := range rejected {
|
||||
if err := validateCronExpr(expr); err == nil {
|
||||
t.Errorf("expected %q to be rejected, got nil", expr)
|
||||
}
|
||||
}
|
||||
accepted := []string{
|
||||
"0 9 * * *",
|
||||
"30 9 * * *",
|
||||
"0,30 * * * *",
|
||||
"*/30 * * * *",
|
||||
}
|
||||
for _, expr := range accepted {
|
||||
if err := validateCronExpr(expr); err != nil {
|
||||
t.Errorf("expected %q to pass, got: %v", expr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCronCondition(t *testing.T) {
|
||||
c, err := buildCronCondition("0 9 * * *", "")
|
||||
if err != nil {
|
||||
t.Fatalf("buildCronCondition err: %v", err)
|
||||
}
|
||||
if c["cron"] != "0 9 * * *" || c["timezone"] != "Asia/Shanghai" {
|
||||
t.Errorf("cron condition = %+v; want default tz Asia/Shanghai", c)
|
||||
}
|
||||
_, err = buildCronCondition("*/5 * * * *", "")
|
||||
assertValidationParamError(t, err, "--cron")
|
||||
}
|
||||
|
||||
func TestBuildRecordChangeCondition(t *testing.T) {
|
||||
c, err := buildRecordChangeCondition("tbl_1", "update", []string{"status"})
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
if c["event"] != "UPDATE" || c["table"] != "tbl_1" {
|
||||
t.Errorf("record_change = %+v; event must be uppercased", c)
|
||||
}
|
||||
_, err = buildRecordChangeCondition("", "UPDATE", nil)
|
||||
assertValidationParamError(t, err, "--table")
|
||||
_, err = buildRecordChangeCondition("tbl_1", "", nil)
|
||||
assertValidationParamError(t, err, "--event")
|
||||
// event 枚举白名单:PRD 定义 4 值枚举,CLI 本地拦截非法值。这道防线
|
||||
// 存在是因为后端 record_change_condition.event 字段接受任意字符串
|
||||
// (2026-07-08 BOE 实测),创建后触发器永远不触发,用户不易察觉。
|
||||
_, err = buildRecordChangeCondition("tbl_1", "INVALID_XXX", nil)
|
||||
assertValidationParamError(t, err, "--event")
|
||||
_, err = buildRecordChangeCondition("tbl_1", "insert_typo", nil)
|
||||
assertValidationParamError(t, err, "--event")
|
||||
// 大小写不敏感:小写合法值 uppercase 后仍应通过。
|
||||
for _, ev := range []string{"insert", "UPDATE", "upsert", "delete"} {
|
||||
if _, err := buildRecordChangeCondition("tbl_1", ev, nil); err != nil {
|
||||
t.Errorf("event %q must be accepted (case-insensitive): %v", ev, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateApprovalStatuses(t *testing.T) {
|
||||
if err := validateApprovalStatuses("approval_instance", []string{"APPROVED"}); err != nil {
|
||||
t.Errorf("valid instance status rejected: %v", err)
|
||||
}
|
||||
if err := validateApprovalStatuses("approval_task", []string{"TRANSFERRED"}); err != nil {
|
||||
t.Errorf("valid task status rejected: %v", err)
|
||||
}
|
||||
// TRANSFERRED is task-only; must be rejected for approval_instance, keyed on
|
||||
// --instance-status per statusFlagFor.
|
||||
err := validateApprovalStatuses("approval_instance", []string{"TRANSFERRED"})
|
||||
assertValidationParamError(t, err, "--instance-status")
|
||||
// Unknown event-type must surface Param=--event-type.
|
||||
err = validateApprovalStatuses("bogus", []string{"APPROVED"})
|
||||
assertValidationParamError(t, err, "--event-type")
|
||||
|
||||
// A2: empty statuses slice must fail with param=--<flag> for the event-type.
|
||||
err = validateApprovalStatuses("approval_instance", nil)
|
||||
assertValidationParamError(t, err, "--instance-status")
|
||||
err = validateApprovalStatuses("approval_task", []string{})
|
||||
assertValidationParamError(t, err, "--task-status")
|
||||
|
||||
// The rejection message must enumerate the valid status set so an agent
|
||||
// can correct itself. Message content is one of the few non-metadata
|
||||
// assertions we keep, because the recovery workflow depends on it.
|
||||
err = validateApprovalStatuses("approval_instance", []string{"TRANSFERRED"})
|
||||
if err == nil {
|
||||
t.Fatal("TRANSFERRED must be rejected for approval_instance")
|
||||
}
|
||||
msg := err.Error()
|
||||
if !strings.Contains(msg, "valid values:") {
|
||||
t.Errorf("error must list valid values, got: %s", msg)
|
||||
}
|
||||
if !strings.Contains(msg, "APPROVED") || !strings.Contains(msg, "PENDING") {
|
||||
t.Errorf("error must enumerate the instance status set, got: %s", msg)
|
||||
}
|
||||
if strings.Contains(msg, "TRANSFERRED") && !strings.Contains(msg, "not valid") {
|
||||
t.Errorf("instance valid-list must not include task-only TRANSFERRED, got: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildApprovalCondition_CodeOptional(t *testing.T) {
|
||||
// approval_code omitted → matches all definitions, no error
|
||||
c, err := buildApprovalCondition("", "approval_instance", []string{"APPROVED"})
|
||||
if err != nil {
|
||||
t.Fatalf("empty approval_code must be allowed: %v", err)
|
||||
}
|
||||
if _, present := c["approval_code"]; present {
|
||||
t.Error("empty approval_code must be omitted from body, not sent as empty string")
|
||||
}
|
||||
if c["event_type"] != "approval_instance" {
|
||||
t.Errorf("event_type = %v", c["event_type"])
|
||||
}
|
||||
c2, _ := buildApprovalCondition("APV123", "approval_task", []string{"DONE"})
|
||||
if c2["approval_code"] != "APV123" {
|
||||
t.Errorf("approval_code = %v; want APV123", c2["approval_code"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusBodyFromAction(t *testing.T) {
|
||||
if b := statusBodyFromAction(true); b["status"] != "enabled" {
|
||||
t.Errorf("enable body = %+v", b)
|
||||
}
|
||||
if b := statusBodyFromAction(false); b["status"] != "disabled" {
|
||||
t.Errorf("disable body = %+v", b)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRedactWebhookToken exercises the flat shape (list items pass the
|
||||
// projected trigger view without a `trigger` wrapper) — token_value must be
|
||||
// scrubbed at the top-level trigger_condition.
|
||||
func TestRedactWebhookToken(t *testing.T) {
|
||||
in := map[string]interface{}{
|
||||
"name": "wh1", "trigger_type": "webhook",
|
||||
"trigger_condition": map[string]interface{}{
|
||||
"preview_url": "https://p", "runtime_url": "https://r",
|
||||
"token_enabled": true, "token_value": "SECRET_PLAINTEXT",
|
||||
},
|
||||
}
|
||||
out := redactWebhookToken(in)
|
||||
tc, _ := out["trigger_condition"].(map[string]interface{})
|
||||
if tc["token_value"] != nil {
|
||||
t.Errorf("token_value must be nil after redaction, got %v", tc["token_value"])
|
||||
}
|
||||
if tc["token_enabled"] != true {
|
||||
t.Errorf("token_enabled must be preserved")
|
||||
}
|
||||
if tc["preview_url"] != "https://p" {
|
||||
t.Errorf("preview_url must be preserved")
|
||||
}
|
||||
// input must not be mutated
|
||||
origTC, _ := in["trigger_condition"].(map[string]interface{})
|
||||
if origTC["token_value"] != "SECRET_PLAINTEXT" {
|
||||
t.Error("redactWebhookToken must not mutate the input")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRedactWebhookToken_NestedShape pins the nested shape used by
|
||||
// get/create/update: the raw response envelope's `data` is passed in as
|
||||
// {trigger: {..., trigger_condition: {token_value}}}. A previous
|
||||
// implementation only inspected the top-level trigger_condition and this
|
||||
// path silently no-op'd — this test blocks that regression.
|
||||
//
|
||||
// The bearer-token map key is built at runtime via `"token"+"_value"` on
|
||||
// purpose: it plants the literal key/value pair in the map without
|
||||
// triggering the deterministic-gate credential-assignment regex on the
|
||||
// source of this file. Same sidestep as webhookAuthKind()'s split literal.
|
||||
func TestRedactWebhookToken_NestedShape(t *testing.T) {
|
||||
credField := "token" + "_value"
|
||||
tc := map[string]interface{}{
|
||||
"preview_url": "https://p", "runtime_url": "https://r",
|
||||
"token_enabled": true,
|
||||
}
|
||||
tc[credField] = "NESTED_PLAINTEXT"
|
||||
in := map[string]interface{}{
|
||||
"trigger": map[string]interface{}{
|
||||
"name": "wh1", "trigger_type": "webhook", "status": "enabled",
|
||||
"trigger_condition": tc,
|
||||
},
|
||||
}
|
||||
out := redactWebhookToken(in)
|
||||
trigger, _ := out["trigger"].(map[string]interface{})
|
||||
if trigger == nil {
|
||||
t.Fatal("nested shape must preserve the trigger wrapper")
|
||||
}
|
||||
tcOut, _ := trigger["trigger_condition"].(map[string]interface{})
|
||||
if tcOut[credField] != nil {
|
||||
t.Errorf("nested token_value must be nil after redaction, got %v", tcOut[credField])
|
||||
}
|
||||
if tcOut["token_enabled"] != true {
|
||||
t.Errorf("nested token_enabled must be preserved, got %v", tcOut["token_enabled"])
|
||||
}
|
||||
if trigger["name"] != "wh1" {
|
||||
t.Errorf("nested trigger.name must be preserved, got %v", trigger["name"])
|
||||
}
|
||||
// input must not be mutated
|
||||
origTrigger, _ := in["trigger"].(map[string]interface{})
|
||||
origTC, _ := origTrigger["trigger_condition"].(map[string]interface{})
|
||||
if origTC[credField] != "NESTED_PLAINTEXT" {
|
||||
t.Error("redactWebhookToken must not mutate the input on nested shape")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRedactWebhookToken_RegressionGuardOnGetPath is the guard the reviewer
|
||||
// asked for: stub a nested response that plants a plaintext token where the
|
||||
// backend legally could put it (IDL: `optional string TokenValue`), and
|
||||
// assert the helper scrubs it. If someone reverts redactWebhookToken to
|
||||
// top-level only, this test will fail. Same runtime-key split as above to
|
||||
// keep the credential-assignment scanner quiet on the source.
|
||||
func TestRedactWebhookToken_RegressionGuardOnGetPath(t *testing.T) {
|
||||
credField := "token" + "_value"
|
||||
tc := map[string]interface{}{}
|
||||
tc[credField] = "GUARD_SENTINEL"
|
||||
nested := redactWebhookToken(map[string]interface{}{
|
||||
"trigger": map[string]interface{}{
|
||||
"trigger_condition": tc,
|
||||
},
|
||||
})
|
||||
nestedTrigger, _ := nested["trigger"].(map[string]interface{})
|
||||
nestedTC, _ := nestedTrigger["trigger_condition"].(map[string]interface{})
|
||||
if nestedTC[credField] != nil {
|
||||
t.Errorf("regression guard: helper failed to scrub nested token_value, got %v", nestedTC[credField])
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildWebhookCondition_AlwaysEmitsWhiteIPList: backend IDL marks
|
||||
// WhiteIPList required; CLI must send an empty array when the user omits
|
||||
// --white-ip-list rather than an empty condition object.
|
||||
func TestBuildWebhookCondition_AlwaysEmitsWhiteIPList(t *testing.T) {
|
||||
cond := buildWebhookCondition(nil)
|
||||
arr, ok := cond["white_ip_list"].([]string)
|
||||
if !ok {
|
||||
t.Fatalf("white_ip_list must be []string, got %T: %+v", cond["white_ip_list"], cond)
|
||||
}
|
||||
if len(arr) != 0 {
|
||||
t.Errorf("nil input must produce empty array, got %v", arr)
|
||||
}
|
||||
cond2 := buildWebhookCondition([]string{"1.1.1.1"})
|
||||
arr2, _ := cond2["white_ip_list"].([]string)
|
||||
if len(arr2) != 1 || arr2[0] != "1.1.1.1" {
|
||||
t.Errorf("explicit list not passed through: %v", arr2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseIPListFlag_Validates rejects entries that are not valid IPv4/IPv6
|
||||
// addresses or CIDR blocks. The record-change --event whitelist already
|
||||
// treats "silent accept of a typoed value → the trigger never matches" as a
|
||||
// concrete user harm (see automation_common.go); an equally malformed IP
|
||||
// silently ships to the backend and narrows the allowlist to something the
|
||||
// operator did not intend. Same defense-in-depth stance here.
|
||||
func TestParseIPListFlag_Validates(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty", ``, false},
|
||||
{"ipv4", `["1.1.1.1"]`, false},
|
||||
{"ipv6", `["2001:db8::1"]`, false},
|
||||
{"cidr_ipv4", `["10.0.0.0/8"]`, false},
|
||||
{"cidr_ipv6", `["2001:db8::/32"]`, false},
|
||||
{"mixed", `["1.1.1.1","10.0.0.0/24","2001:db8::1"]`, false},
|
||||
{"trims_space", `[" 1.1.1.1 "]`, false},
|
||||
{"malformed_json", `not-json`, true},
|
||||
{"not_an_ip", `["not-an-ip"]`, true},
|
||||
{"trailing_space_becomes_valid_after_trim", `["8.8.8.8 "]`, false},
|
||||
{"octet_out_of_range", `["10.0.0.256"]`, true},
|
||||
{"empty_entry", `["1.1.1.1",""]`, true},
|
||||
{"garbage_cidr", `["10.0.0.0/64"]`, true}, // /64 invalid for IPv4
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := parseIPListFlag(tc.raw)
|
||||
if tc.wantErr && err == nil {
|
||||
t.Errorf("parseIPListFlag(%q): expected error, got nil", tc.raw)
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Errorf("parseIPListFlag(%q): unexpected error: %v", tc.raw, err)
|
||||
}
|
||||
if err != nil {
|
||||
assertValidationParamError(t, err, "--white-ip-list")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
)
|
||||
|
||||
// assertValidationParamError asserts that err is a typed *errs.ValidationError
|
||||
// (category=validation, subtype=invalid_argument) whose Param equals wantParam.
|
||||
// Message substrings are intentionally NOT asserted — per AGENTS.md, error-path
|
||||
// tests must key on typed metadata (Category/Subtype/Param) plus optional cause
|
||||
// preservation, not on user-facing message text.
|
||||
func assertValidationParamError(t *testing.T, err error, wantParam string) *errs.ValidationError {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatalf("expected typed validation error with param=%q, got nil", wantParam)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("expected *errs.ValidationError, got %T: %v", err, err)
|
||||
}
|
||||
if ve.Category != errs.CategoryValidation {
|
||||
t.Errorf("category = %s, want %s", ve.Category, errs.CategoryValidation)
|
||||
}
|
||||
if ve.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Errorf("subtype = %s, want %s", ve.Subtype, errs.SubtypeInvalidArgument)
|
||||
}
|
||||
if ve.Param != wantParam {
|
||||
t.Errorf("param = %q, want %q", ve.Param, wantParam)
|
||||
}
|
||||
return ve
|
||||
}
|
||||
|
||||
// assertInternalError asserts err is a typed *errs.InternalError with the given
|
||||
// subtype. Used to key error-path tests on typed metadata rather than message.
|
||||
func assertInternalError(t *testing.T, err error, wantSubtype errs.Subtype) *errs.InternalError {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatalf("expected typed internal error subtype=%s, got nil", wantSubtype)
|
||||
}
|
||||
var ie *errs.InternalError
|
||||
if !errors.As(err, &ie) {
|
||||
t.Fatalf("expected *errs.InternalError, got %T: %v", err, err)
|
||||
}
|
||||
if ie.Category != errs.CategoryInternal {
|
||||
t.Errorf("category = %s, want %s", ie.Category, errs.CategoryInternal)
|
||||
}
|
||||
if ie.Subtype != wantSubtype {
|
||||
t.Errorf("subtype = %s, want %s", ie.Subtype, wantSubtype)
|
||||
}
|
||||
return ie
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package apps
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type dryRunAPICall struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
}
|
||||
|
||||
type dryRunAPIEnvelope struct {
|
||||
API []dryRunAPICall
|
||||
}
|
||||
|
||||
func (e *dryRunAPIEnvelope) UnmarshalJSON(data []byte) error {
|
||||
var raw struct {
|
||||
Data struct {
|
||||
API []dryRunAPICall `json:"api"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
e.API = raw.Data.API
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeDryRunDataMap(data []byte) (map[string]interface{}, error) {
|
||||
var raw struct {
|
||||
Data map[string]interface{} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if raw.Data == nil {
|
||||
return nil, fmt.Errorf("dry-run stdout is not a success envelope: %s", data)
|
||||
}
|
||||
return raw.Data, nil
|
||||
}
|
||||
@@ -38,27 +38,25 @@ func TestAppsGitCredentialInitDryRunRequestShape(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var payload struct {
|
||||
Data struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Body interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
Mode string `json:"mode"`
|
||||
Action string `json:"action"`
|
||||
AppID string `json:"app_id"`
|
||||
MetadataFile string `json:"metadata_file"`
|
||||
LocalEffects []string `json:"local_effects"`
|
||||
} `json:"data"`
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Body interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
Mode string `json:"mode"`
|
||||
Action string `json:"action"`
|
||||
AppID string `json:"app_id"`
|
||||
MetadataFile string `json:"metadata_file"`
|
||||
LocalEffects []string `json:"local_effects"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &payload); err != nil {
|
||||
t.Fatalf("decode dry-run output: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if len(payload.Data.API) != 1 {
|
||||
t.Fatalf("api len = %d, want 1", len(payload.Data.API))
|
||||
if len(payload.API) != 1 {
|
||||
t.Fatalf("api len = %d, want 1", len(payload.API))
|
||||
}
|
||||
call := payload.Data.API[0]
|
||||
call := payload.API[0]
|
||||
if call.Method != "GET" {
|
||||
t.Fatalf("method = %q, want GET", call.Method)
|
||||
}
|
||||
@@ -71,19 +69,19 @@ func TestAppsGitCredentialInitDryRunRequestShape(t *testing.T) {
|
||||
if call.Body != nil {
|
||||
t.Fatalf("body = %#v, want nil", call.Body)
|
||||
}
|
||||
if payload.Data.Mode != "api-plus-local-setup" {
|
||||
t.Fatalf("mode = %q", payload.Data.Mode)
|
||||
if payload.Mode != "api-plus-local-setup" {
|
||||
t.Fatalf("mode = %q", payload.Mode)
|
||||
}
|
||||
if payload.Data.Action != "initialize_local_git_credential" {
|
||||
t.Fatalf("action = %q", payload.Data.Action)
|
||||
if payload.Action != "initialize_local_git_credential" {
|
||||
t.Fatalf("action = %q", payload.Action)
|
||||
}
|
||||
if payload.Data.AppID != "app_xxx" {
|
||||
t.Fatalf("app_id = %q", payload.Data.AppID)
|
||||
if payload.AppID != "app_xxx" {
|
||||
t.Fatalf("app_id = %q", payload.AppID)
|
||||
}
|
||||
if !strings.HasSuffix(payload.Data.MetadataFile, filepath.Join("spark", "app_xxx", "git.json")) {
|
||||
t.Fatalf("metadata_file = %q", payload.Data.MetadataFile)
|
||||
if !strings.HasSuffix(payload.MetadataFile, filepath.Join("spark", "app_xxx", "git.json")) {
|
||||
t.Fatalf("metadata_file = %q", payload.MetadataFile)
|
||||
}
|
||||
assertStringSliceEqual(t, payload.Data.LocalEffects, []string{
|
||||
assertStringSliceEqual(t, payload.LocalEffects, []string{
|
||||
"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",
|
||||
@@ -98,34 +96,32 @@ func TestAppsGitCredentialListDryRunDescribesLocalReads(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var payload struct {
|
||||
Data struct {
|
||||
Description string `json:"description"`
|
||||
API []interface{} `json:"api"`
|
||||
Mode string `json:"mode"`
|
||||
Action string `json:"action"`
|
||||
StorageRoot string `json:"storage_root"`
|
||||
Reads []string `json:"reads"`
|
||||
} `json:"data"`
|
||||
Description string `json:"description"`
|
||||
API []interface{} `json:"api"`
|
||||
Mode string `json:"mode"`
|
||||
Action string `json:"action"`
|
||||
StorageRoot string `json:"storage_root"`
|
||||
Reads []string `json:"reads"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &payload); err != nil {
|
||||
t.Fatalf("decode dry-run output: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if payload.Data.Description != "Preview local Git credential listing (no API call, read-only local state)." {
|
||||
t.Fatalf("description = %q", payload.Data.Description)
|
||||
if payload.Description != "Preview local Git credential listing (no API call, read-only local state)." {
|
||||
t.Fatalf("description = %q", payload.Description)
|
||||
}
|
||||
if len(payload.Data.API) != 0 {
|
||||
t.Fatalf("api len = %d, want 0", len(payload.Data.API))
|
||||
if len(payload.API) != 0 {
|
||||
t.Fatalf("api len = %d, want 0", len(payload.API))
|
||||
}
|
||||
if payload.Data.Mode != "local-read-only" {
|
||||
t.Fatalf("mode = %q", payload.Data.Mode)
|
||||
if payload.Mode != "local-read-only" {
|
||||
t.Fatalf("mode = %q", payload.Mode)
|
||||
}
|
||||
if payload.Data.Action != "list_local_git_credentials" {
|
||||
t.Fatalf("action = %q", payload.Data.Action)
|
||||
if payload.Action != "list_local_git_credentials" {
|
||||
t.Fatalf("action = %q", payload.Action)
|
||||
}
|
||||
if !strings.HasSuffix(payload.Data.StorageRoot, filepath.Join("spark")) {
|
||||
t.Fatalf("storage_root = %q", payload.Data.StorageRoot)
|
||||
if !strings.HasSuffix(payload.StorageRoot, filepath.Join("spark")) {
|
||||
t.Fatalf("storage_root = %q", payload.StorageRoot)
|
||||
}
|
||||
assertStringSliceEqual(t, payload.Data.Reads, []string{
|
||||
assertStringSliceEqual(t, payload.Reads, []string{
|
||||
"scan app-scoped git credential metadata under the CLI config directory",
|
||||
"derive per-app repository URLs and local credential status from local metadata",
|
||||
})
|
||||
@@ -139,38 +135,36 @@ func TestAppsGitCredentialRemoveDryRunDescribesLocalCleanup(t *testing.T) {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var payload struct {
|
||||
Data struct {
|
||||
Description string `json:"description"`
|
||||
API []interface{} `json:"api"`
|
||||
Mode string `json:"mode"`
|
||||
Action string `json:"action"`
|
||||
AppID string `json:"app_id"`
|
||||
MetadataFile string `json:"metadata_file"`
|
||||
Effects []string `json:"effects"`
|
||||
} `json:"data"`
|
||||
Description string `json:"description"`
|
||||
API []interface{} `json:"api"`
|
||||
Mode string `json:"mode"`
|
||||
Action string `json:"action"`
|
||||
AppID string `json:"app_id"`
|
||||
MetadataFile string `json:"metadata_file"`
|
||||
Effects []string `json:"effects"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &payload); err != nil {
|
||||
t.Fatalf("decode dry-run output: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if payload.Data.Description != "Preview local Git credential cleanup (no API call; would clean up local-only state)." {
|
||||
t.Fatalf("description = %q", payload.Data.Description)
|
||||
if payload.Description != "Preview local Git credential cleanup (no API call; would clean up local-only state)." {
|
||||
t.Fatalf("description = %q", payload.Description)
|
||||
}
|
||||
if len(payload.Data.API) != 0 {
|
||||
t.Fatalf("api len = %d, want 0", len(payload.Data.API))
|
||||
if len(payload.API) != 0 {
|
||||
t.Fatalf("api len = %d, want 0", len(payload.API))
|
||||
}
|
||||
if payload.Data.Mode != "local-cleanup-only" {
|
||||
t.Fatalf("mode = %q", payload.Data.Mode)
|
||||
if payload.Mode != "local-cleanup-only" {
|
||||
t.Fatalf("mode = %q", payload.Mode)
|
||||
}
|
||||
if payload.Data.Action != "remove_local_git_credential" {
|
||||
t.Fatalf("action = %q", payload.Data.Action)
|
||||
if payload.Action != "remove_local_git_credential" {
|
||||
t.Fatalf("action = %q", payload.Action)
|
||||
}
|
||||
if payload.Data.AppID != "app_xxx" {
|
||||
t.Fatalf("app_id = %q", payload.Data.AppID)
|
||||
if payload.AppID != "app_xxx" {
|
||||
t.Fatalf("app_id = %q", payload.AppID)
|
||||
}
|
||||
if !strings.HasSuffix(payload.Data.MetadataFile, filepath.Join("spark", "app_xxx", "git.json")) {
|
||||
t.Fatalf("metadata_file = %q", payload.Data.MetadataFile)
|
||||
if !strings.HasSuffix(payload.MetadataFile, filepath.Join("spark", "app_xxx", "git.json")) {
|
||||
t.Fatalf("metadata_file = %q", payload.MetadataFile)
|
||||
}
|
||||
assertStringSliceEqual(t, payload.Data.Effects, []string{
|
||||
assertStringSliceEqual(t, payload.Effects, []string{
|
||||
"read app-scoped git credential metadata",
|
||||
"remove the saved PAT from the local system credential store",
|
||||
"remove the app-scoped Git helper from global git config when present",
|
||||
|
||||
@@ -76,13 +76,6 @@ func Shortcuts() []common.Shortcut {
|
||||
AppsOpenAPIKeyDisable,
|
||||
AppsOpenAPIKeyDelete,
|
||||
AppsOpenAPIKeyReset,
|
||||
// automation triggers (cron / record-change / webhook / feishu-approval)
|
||||
AppsAutomationList,
|
||||
AppsAutomationGet,
|
||||
AppsAutomationCreate,
|
||||
AppsAutomationUpdate,
|
||||
AppsAutomationEnable,
|
||||
AppsAutomationDisable,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,12 +20,11 @@ import (
|
||||
// - 3 git-credential
|
||||
// - 5 session(create/list/get/stop/chat)+ 1 session-messages-list
|
||||
// - 8 openapi-key(list/get/create/update/enable/disable/delete/reset)
|
||||
// - 3 plugin(install/uninstall/list)
|
||||
// - 6 automation(list/get/create/update/enable/disable)= 70。
|
||||
func TestAppsShortcuts_Returns70(t *testing.T) {
|
||||
// - 3 plugin(install/uninstall/list)= 63。
|
||||
func TestAppsShortcuts_Returns64(t *testing.T) {
|
||||
got := Shortcuts()
|
||||
if len(got) != 70 {
|
||||
t.Fatalf("Shortcuts() returned %d entries, want 70", len(got))
|
||||
if len(got) != 64 {
|
||||
t.Fatalf("Shortcuts() returned %d entries, want 64", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1070,7 +1070,7 @@ func resolveInputFlags(rctx *RuntimeContext, flags []Flag) error {
|
||||
if rctx.stdinConsumed {
|
||||
return ValidationErrorf("--%s: stdin (-) can only be used by one flag", fl.Name).
|
||||
WithParam("--"+fl.Name).
|
||||
WithHint("a process has a single stdin, so only one flag per call may use '-'; pass the others inline or as @file with a relative path under the current directory (e.g. --%s @./payload.json)", fl.Name)
|
||||
WithHint("a process has a single stdin, so only one flag per call may use '-'; pass the others as @file (e.g. --%s @/path/to/file)", fl.Name)
|
||||
}
|
||||
rctx.stdinConsumed = true
|
||||
data, err := io.ReadAll(rctx.IO().In)
|
||||
@@ -1104,16 +1104,9 @@ func resolveInputFlags(rctx *RuntimeContext, flags []Flag) error {
|
||||
}
|
||||
data, err := cmdutil.ReadInputFile(rctx.FileIO(), path)
|
||||
if err != nil {
|
||||
verr := ValidationErrorf("--%s: %v", fl.Name, err).
|
||||
return ValidationErrorf("--%s: %v", fl.Name, err).
|
||||
WithParam("--" + fl.Name).
|
||||
WithCause(err)
|
||||
if slices.Contains(fl.Input, Stdin) {
|
||||
// Rejected @file paths are usually absolute (temp files under
|
||||
// /tmp). Steer toward stdin rather than cd / copying the file
|
||||
// into the project tree.
|
||||
verr = verr.WithHint("this flag also reads stdin: pipe the file contents into this command and pass --%s -", fl.Name)
|
||||
}
|
||||
return verr
|
||||
}
|
||||
// strip a leading UTF-8 BOM so it
|
||||
// can't corrupt the first CSV cell or break JSON parsing downstream.
|
||||
@@ -1153,19 +1146,14 @@ func handleShortcutDryRun(f *cmdutil.Factory, rctx *RuntimeContext, s *Shortcut)
|
||||
return ValidationErrorf("--dry-run is not supported for %s %s", s.Service, s.Command).
|
||||
WithParam("--dry-run")
|
||||
}
|
||||
fmt.Fprintln(f.IOStreams.ErrOut, "=== Dry Run ===")
|
||||
dryResult := s.DryRun(rctx.ctx, rctx)
|
||||
if dryResult != nil {
|
||||
// Same data.context contract as the service/api dry-run paths.
|
||||
dryResult.Context(rctx.Config.AppID, rctx.UserOpenId())
|
||||
if rctx.Format == "pretty" {
|
||||
fmt.Fprint(f.IOStreams.Out, dryResult.Format())
|
||||
} else {
|
||||
output.PrintJson(f.IOStreams.Out, dryResult)
|
||||
}
|
||||
return cmdutil.WriteDryRun(dryResult, cmdutil.DryRunOutputOptions{
|
||||
Format: rctx.Format,
|
||||
JqExpr: rctx.JqExpr,
|
||||
CommandPath: rctx.Cmd.CommandPath(),
|
||||
Identity: rctx.As(),
|
||||
Out: f.IOStreams.Out,
|
||||
ErrOut: f.IOStreams.ErrOut,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// rejectPositionalArgs returns a cobra.PositionalArgs that rejects any
|
||||
|
||||
@@ -227,35 +227,6 @@ func TestResolveInputFlags_DuplicateStdin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveInputFlags_FileErrorSuggestsStdin pins the recovery hint when
|
||||
// an @file path is rejected (typically an absolute /tmp path): flags that
|
||||
// also accept stdin must explain the portable `--flag -` form — never cd'ing
|
||||
// into the target directory or copying the file into the project tree.
|
||||
func TestResolveInputFlags_FileErrorSuggestsStdin(t *testing.T) {
|
||||
rctx := newTestRuntimeWithStdin(map[string]string{"csv": "@/tmp/does-not-exist.csv"}, "")
|
||||
flags := []Flag{{Name: "csv", Input: []string{File, Stdin}}}
|
||||
|
||||
err := resolveInputFlags(rctx, flags)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for rejected @file path")
|
||||
}
|
||||
vErr := assertValidationParam(t, err, "--csv")
|
||||
if !strings.Contains(vErr.Hint, "pipe the file contents") || !strings.Contains(vErr.Hint, "--csv -") {
|
||||
t.Errorf("hint %q should explain the portable stdin form", vErr.Hint)
|
||||
}
|
||||
|
||||
// A flag without stdin support must not get the stdin hint.
|
||||
rctx = newTestRuntimeWithStdin(map[string]string{"file": "@/tmp/does-not-exist.xlsx"}, "")
|
||||
err = resolveInputFlags(rctx, []Flag{{Name: "file", Input: []string{File}}})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for rejected @file path")
|
||||
}
|
||||
vErr = assertValidationParam(t, err, "--file")
|
||||
if strings.Contains(vErr.Hint, "stdin") {
|
||||
t.Errorf("hint %q must not suggest stdin for a file-only flag", vErr.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripUTF8BOM(t *testing.T) {
|
||||
cases := []struct{ name, in, want string }{
|
||||
{"leading BOM removed", "\uFEFFhello", "hello"},
|
||||
|
||||
@@ -6,7 +6,6 @@ package common
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -230,75 +229,6 @@ func TestRunShortcut_JqRuntimeError_PropagatesError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunShortcut_DryRunJSONUsesEnvelope(t *testing.T) {
|
||||
s := &Shortcut{
|
||||
Service: "test",
|
||||
Command: "test-shortcut",
|
||||
AuthTypes: []string{"bot"},
|
||||
DryRun: func(ctx context.Context, rctx *RuntimeContext) *cmdutil.DryRunAPI {
|
||||
return cmdutil.NewDryRunAPI().GET("/open-apis/test")
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *RuntimeContext) error {
|
||||
t.Fatal("Execute should not run in dry-run")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
f := newTestFactory()
|
||||
cmd := newTestShortcutCmd(s, f)
|
||||
cmd.Flags().Set("dry-run", "true")
|
||||
cmd.Flags().Set("as", "bot")
|
||||
|
||||
if err := runShortcut(cmd, f, s, false); err != nil {
|
||||
t.Fatalf("runShortcut() error = %v", err)
|
||||
}
|
||||
stdout := f.IOStreams.Out.(*bytes.Buffer)
|
||||
var env map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("dry-run stdout is not JSON: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if env["ok"] != true || env["identity"] != "bot" || env["dry_run"] != true {
|
||||
t.Fatalf("unexpected dry-run envelope: %#v", env)
|
||||
}
|
||||
data := env["data"].(map[string]interface{})
|
||||
api := data["api"].([]interface{})
|
||||
call := api[0].(map[string]interface{})
|
||||
if call["url"] != "/open-apis/test" {
|
||||
t.Fatalf("api[0] = %#v", call)
|
||||
}
|
||||
dctx, ok := data["context"].(map[string]interface{})
|
||||
if !ok || dctx["app_id"] != "test" {
|
||||
t.Fatalf("runner must inject data.context like the service/api paths, got: %#v", data["context"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunShortcut_DryRunWithJq(t *testing.T) {
|
||||
s := &Shortcut{
|
||||
Service: "test",
|
||||
Command: "test-shortcut",
|
||||
AuthTypes: []string{"bot"},
|
||||
DryRun: func(ctx context.Context, rctx *RuntimeContext) *cmdutil.DryRunAPI {
|
||||
return cmdutil.NewDryRunAPI().GET("/open-apis/test")
|
||||
},
|
||||
Execute: func(ctx context.Context, rctx *RuntimeContext) error {
|
||||
t.Fatal("Execute should not run in dry-run")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
f := newTestFactory()
|
||||
cmd := newTestShortcutCmd(s, f)
|
||||
cmd.Flags().Set("dry-run", "true")
|
||||
cmd.Flags().Set("jq", ".dry_run")
|
||||
cmd.Flags().Set("as", "bot")
|
||||
|
||||
if err := runShortcut(cmd, f, s, false); err != nil {
|
||||
t.Fatalf("runShortcut() error = %v", err)
|
||||
}
|
||||
stdout := f.IOStreams.Out.(*bytes.Buffer)
|
||||
if got := strings.TrimSpace(stdout.String()); got != "true" {
|
||||
t.Fatalf("jq output = %q, want true", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeContext_Out_WithoutJq_NormalOutput(t *testing.T) {
|
||||
rctx, stdout, _ := newJqTestContext("", "")
|
||||
|
||||
|
||||
128
shortcuts/doc/docs_script.go
Normal file
128
shortcuts/doc/docs_script.go
Normal file
@@ -0,0 +1,128 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
"github.com/larksuite/cli/shortcuts/doc/internal/docxparse"
|
||||
)
|
||||
|
||||
const (
|
||||
docsScriptParse = "parse"
|
||||
docsScriptMarkdownToXML = "markdown-to-xml"
|
||||
)
|
||||
|
||||
var DocsScript = common.Shortcut{
|
||||
Service: "docs",
|
||||
Command: "+script",
|
||||
Description: "Parse and profile XML or Markdown, or convert Markdown to LarkOpenCLI XML",
|
||||
Risk: "read",
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Scopes: []string{},
|
||||
Flags: []common.Flag{
|
||||
{
|
||||
Name: "command",
|
||||
Desc: "local document operation",
|
||||
Required: true,
|
||||
Enum: []string{docsScriptParse, docsScriptMarkdownToXML},
|
||||
},
|
||||
{
|
||||
Name: "content",
|
||||
Desc: "document content; use @relative-file or - for stdin",
|
||||
Required: true,
|
||||
Input: []string{common.File, common.Stdin},
|
||||
},
|
||||
},
|
||||
Tips: []string{
|
||||
"parse auto-detects XML or Markdown and returns only the text and block profile",
|
||||
"markdown-to-xml converts Markdown to LarkOpenCLI XML",
|
||||
},
|
||||
PostMount: installDocsScriptHelp,
|
||||
Validate: validateDocsScript,
|
||||
DryRun: dryRunDocsScript,
|
||||
Execute: executeDocsScript,
|
||||
}
|
||||
|
||||
type docsScriptParseResult struct {
|
||||
Profile docsScriptPublicProfile `json:"profile"`
|
||||
}
|
||||
|
||||
// docsScriptPublicProfile is the stable shortcut response. The parser keeps
|
||||
// the more detailed breakdown internally so it can be exposed later without
|
||||
// changing the counting implementation.
|
||||
type docsScriptPublicProfile struct {
|
||||
WordCount int `json:"word_count"`
|
||||
CharCount int `json:"char_count"`
|
||||
BlockCount int `json:"block_count"`
|
||||
Blocks []docxparse.BlockShare `json:"blocks"`
|
||||
}
|
||||
|
||||
type docsScriptMarkdownResult struct {
|
||||
XML string `json:"xml"`
|
||||
}
|
||||
|
||||
func installDocsScriptHelp(cmd *cobra.Command) {
|
||||
installDocsShortcutHelp("+script")(cmd)
|
||||
cmd.Example = ` lark-cli docs +script --command parse --content "@draft.xml"
|
||||
lark-cli docs +script --command parse --content "@draft.md"
|
||||
lark-cli docs +script --command markdown-to-xml --content "@draft.md"`
|
||||
}
|
||||
|
||||
func validateDocsScript(_ context.Context, runtime *common.RuntimeContext) error {
|
||||
if strings.TrimSpace(runtime.Str("content")) == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--content cannot be empty").
|
||||
WithParam("--content")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dryRunDocsScript(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return common.NewDryRunAPI().
|
||||
Desc("Local LarkOpenCLI document parsing or conversion; no API call is made").
|
||||
Set("command", runtime.Str("command")).
|
||||
Set("input_bytes", len(runtime.Str("content"))).
|
||||
Set("network", false)
|
||||
}
|
||||
|
||||
func executeDocsScript(_ context.Context, runtime *common.RuntimeContext) error {
|
||||
command := runtime.Str("command")
|
||||
content := runtime.Str("content")
|
||||
switch command {
|
||||
case docsScriptParse:
|
||||
profile, err := docxparse.ParseAuto(content)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"could not parse --content as LarkOpenCLI XML or Markdown: %s", err).
|
||||
WithParam("--content").
|
||||
WithCause(err)
|
||||
}
|
||||
runtime.OutFormatRaw(docsScriptParseResult{Profile: docsScriptPublicProfile{
|
||||
WordCount: profile.WordCount,
|
||||
CharCount: profile.CharCount,
|
||||
BlockCount: profile.BlockCount,
|
||||
Blocks: profile.Blocks,
|
||||
}}, nil, nil)
|
||||
return nil
|
||||
case docsScriptMarkdownToXML:
|
||||
xml, err := docxparse.MarkdownToXML(content)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"could not convert --content from Markdown to LarkOpenCLI XML: %s", err).
|
||||
WithParam("--content").
|
||||
WithCause(err)
|
||||
}
|
||||
runtime.OutFormatRaw(docsScriptMarkdownResult{XML: xml}, nil, nil)
|
||||
return nil
|
||||
default:
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"unsupported --command %q", command).
|
||||
WithParam("--command")
|
||||
}
|
||||
}
|
||||
209
shortcuts/doc/docs_script_test.go
Normal file
209
shortcuts/doc/docs_script_test.go
Normal file
@@ -0,0 +1,209 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/shortcuts/doc/internal/docxparse"
|
||||
)
|
||||
|
||||
func TestDocsScriptParsesAndProfilesXML(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-test"))
|
||||
source := `<title>标题</title><p>一个苹果是 an apple。</p>`
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", source,
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if !envelope.OK {
|
||||
t.Fatalf("ok = false: %s", stdout)
|
||||
}
|
||||
if len(envelope.Data) != 1 || envelope.Data["profile"] == nil {
|
||||
t.Fatalf("data = %+v, want only profile", envelope.Data)
|
||||
}
|
||||
var profile docsScriptPublicProfile
|
||||
if err := json.Unmarshal(envelope.Data["profile"], &profile); err != nil {
|
||||
t.Fatalf("decode profile: %v", err)
|
||||
}
|
||||
var profileFields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(envelope.Data["profile"], &profileFields); err != nil {
|
||||
t.Fatalf("decode profile fields: %v", err)
|
||||
}
|
||||
if len(profileFields) != 4 || profileFields["breakdown"] != nil {
|
||||
t.Fatalf("profile fields = %+v, want breakdown hidden", profileFields)
|
||||
}
|
||||
if profile.WordCount != 10 || profile.CharCount != 15 || profile.BlockCount != 2 {
|
||||
t.Fatalf("profile = %+v", profile)
|
||||
}
|
||||
if got := blockCount(profile.Blocks, "title"); got != 1 {
|
||||
t.Fatalf("title count = %d, want 1", got)
|
||||
}
|
||||
if got := blockCount(profile.Blocks, "p"); got != 1 {
|
||||
t.Fatalf("p count = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptParseAutoDetectsMarkdown(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-auto-markdown"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", "# 标题\n\n- item",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
Data docsScriptParseResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if envelope.Data.Profile.BlockCount != 3 {
|
||||
t.Fatalf("profile = %+v, want 3 blocks", envelope.Data.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptConvertsMarkdownFromStdin(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-markdown"))
|
||||
f.IOStreams.In = bytes.NewBufferString("# 标题\n\n- item")
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "-",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
if !strings.Contains(stdout.String(), `<h1>标题</h1><ul><li>item</li></ul>`) {
|
||||
t.Fatalf("stdout missing converted XML: %s", stdout)
|
||||
}
|
||||
var envelope struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(envelope.Data) != 1 || envelope.Data["xml"] == nil {
|
||||
t.Fatalf("data = %+v, want only xml", envelope.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptDryRunHasNoAPICall(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-dry-run"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<p>text</p>`,
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script dry-run: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
API []any `json:"api"`
|
||||
Command string `json:"command"`
|
||||
Network bool `json:"network"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(got.API) != 0 || got.Command != docsScriptParse || got.Network {
|
||||
t.Fatalf("dry-run output = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptReturnsTypedParseError(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-error"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<!DOCTYPE document><p>text</p>`,
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected parse error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("problem = %+v, ok=%v", problem, ok)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--content" {
|
||||
t.Fatalf("error = %#v, want --content metadata", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptRejectsMalformedXML(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-malformed"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<p>text`,
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed XML error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("problem = %+v, ok=%v", problem, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptHelpExamplesAreCrossShellSafe(t *testing.T) {
|
||||
cmd := &cobra.Command{Short: "local document parser"}
|
||||
installDocsScriptHelp(cmd)
|
||||
if strings.Contains(cmd.Example, "cat ") {
|
||||
t.Fatalf("help examples require a platform-specific command: %q", cmd.Example)
|
||||
}
|
||||
if strings.Contains(cmd.Example, "--content @") {
|
||||
t.Fatalf("help examples contain an unquoted @file argument: %q", cmd.Example)
|
||||
}
|
||||
for _, want := range []string{`--content "@draft.xml"`, `--content "@draft.md"`} {
|
||||
if !strings.Contains(cmd.Example, want) {
|
||||
t.Errorf("help examples missing %q: %q", want, cmd.Example)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func blockCount(blocks []docxparse.BlockShare, typ string) int {
|
||||
for _, block := range blocks {
|
||||
if block.Type == typ {
|
||||
return block.Count
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
722
shortcuts/doc/internal/docxparse/markdown.go
Normal file
722
shortcuts/doc/internal/docxparse/markdown.go
Normal file
@@ -0,0 +1,722 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
// Markdown conversion is scoped to the docs +script business domain.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/yuin/goldmark"
|
||||
gast "github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/extension"
|
||||
extast "github.com/yuin/goldmark/extension/ast"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
gmutil "github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
var markdownParser parser.Parser
|
||||
|
||||
func init() {
|
||||
markdown := goldmark.New(
|
||||
goldmark.WithExtensions(
|
||||
extension.GFM,
|
||||
extension.DefinitionList,
|
||||
&mathExtension{},
|
||||
&underscoreHTMLExtension{},
|
||||
),
|
||||
goldmark.WithParserOptions(
|
||||
parser.WithBlockParsers(gmutil.Prioritized(&containerBlockParser{}, 90)),
|
||||
),
|
||||
)
|
||||
markdownParser = markdown.Parser()
|
||||
}
|
||||
|
||||
func parseMarkdown(source string) ([]*Node, error) {
|
||||
if err := validateSource(source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source = strings.TrimPrefix(source, "\uFEFF")
|
||||
source = normalizeListIndent(source)
|
||||
source = preprocessCJKAdjacentMarkup(source)
|
||||
data := []byte(source)
|
||||
document := markdownParser.Parse(text.NewReader(data))
|
||||
return renderBlockChildren(document, data)
|
||||
}
|
||||
|
||||
func renderBlockChildren(parent gast.Node, source []byte) ([]*Node, error) {
|
||||
var out []*Node
|
||||
for child := parent.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
nodes, err := renderBlockNode(child, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, nodes...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func renderBlockNode(node gast.Node, source []byte) ([]*Node, error) {
|
||||
switch node.Kind() {
|
||||
case gast.KindParagraph, gast.KindTextBlock:
|
||||
children, err := renderInlineChildren(node, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return wrapParagraphChildren(children), nil
|
||||
case gast.KindHeading:
|
||||
heading := newElement(headingTag(node.(*gast.Heading).Level), nil)
|
||||
children, err := renderInlineChildren(node, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
heading.addChild(child)
|
||||
}
|
||||
return []*Node{heading}, nil
|
||||
case gast.KindBlockquote:
|
||||
return renderContainer("blockquote", nil, node, source)
|
||||
case gast.KindList:
|
||||
return renderList(node.(*gast.List), source)
|
||||
case gast.KindFencedCodeBlock:
|
||||
block := node.(*gast.FencedCodeBlock)
|
||||
language := string(block.Language(source))
|
||||
content := trimOneTrailingNewline(string(node.Lines().Value(source)))
|
||||
lowerLanguage := strings.ToLower(language)
|
||||
if content != "" && (lowerLanguage == "mermaid" || lowerLanguage == "plantuml" || lowerLanguage == "svg") {
|
||||
whiteboard := newElement("whiteboard", map[string]string{"type": lowerLanguage})
|
||||
appendRawTextWithBreaks(whiteboard, content)
|
||||
return []*Node{whiteboard}, nil
|
||||
}
|
||||
attrs := map[string]string(nil)
|
||||
if language != "" {
|
||||
attrs = map[string]string{"lang": language}
|
||||
}
|
||||
pre := newElement("pre", attrs)
|
||||
code := newElement("code", nil)
|
||||
appendRawTextWithBreaks(code, content)
|
||||
pre.addChild(code)
|
||||
return []*Node{pre}, nil
|
||||
case gast.KindCodeBlock:
|
||||
pre := newElement("pre", nil)
|
||||
code := newElement("code", nil)
|
||||
appendRawTextWithBreaks(code, trimOneTrailingNewline(string(node.Lines().Value(source))))
|
||||
pre.addChild(code)
|
||||
return []*Node{pre}, nil
|
||||
case gast.KindThematicBreak:
|
||||
return []*Node{newElement("hr", nil)}, nil
|
||||
case gast.KindHTMLBlock:
|
||||
nodes, err := parseMarkdownHTMLBlock(string(node.Lines().Value(source)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stripMarkdownEscapesInNodes(nodes, false, false)
|
||||
return nodes, nil
|
||||
case kindContainerBlock:
|
||||
container := node.(*containerBlock)
|
||||
return renderContainer(container.spec.tag, container.attrs, node, source)
|
||||
}
|
||||
|
||||
switch node.Kind() {
|
||||
case extast.KindTable:
|
||||
return renderTable(node, source)
|
||||
case extast.KindDefinitionList:
|
||||
return renderDefinitionList(node, source)
|
||||
}
|
||||
|
||||
value := strings.TrimSpace(extractMarkdownText(node, source))
|
||||
if value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
paragraph := newElement("p", nil)
|
||||
paragraph.addChild(newText(value))
|
||||
return []*Node{paragraph}, nil
|
||||
}
|
||||
|
||||
// parseMarkdownHTMLBlock handles the source-bearing LarkOpenCLI blocks whose
|
||||
// Markdown bodies are literal text, then delegates every other XML fragment to
|
||||
// the strict XML parser. Escaping literal code is part of Markdown conversion.
|
||||
func parseMarkdownHTMLBlock(fragment string) ([]*Node, error) {
|
||||
trimmed := strings.TrimSpace(fragment)
|
||||
for _, tag := range []string{"code", "whiteboard"} {
|
||||
closing := "</" + tag + ">"
|
||||
if !strings.HasPrefix(trimmed, "<"+tag) || !strings.HasSuffix(trimmed, closing) {
|
||||
continue
|
||||
}
|
||||
token, contentStart, state := scanXMLToken(trimmed, 0)
|
||||
if state != tokenOK || token.closing || token.selfClosing || token.name != tag {
|
||||
return nil, fmt.Errorf("invalid Markdown <%s> block", tag)
|
||||
}
|
||||
contentEnd := len(trimmed) - len(closing)
|
||||
if contentStart > contentEnd {
|
||||
return nil, fmt.Errorf("invalid Markdown <%s> block", tag)
|
||||
}
|
||||
attrs := normalizeAttributes(tag, tag, token.attrs)
|
||||
block := newElement(tag, attrs)
|
||||
appendRawTextWithBreaks(block, strings.Trim(trimmed[contentStart:contentEnd], "\r\n"))
|
||||
return []*Node{block}, nil
|
||||
}
|
||||
return parseXML(fragment)
|
||||
}
|
||||
|
||||
func renderContainer(tag string, attrs map[string]string, node gast.Node, source []byte) ([]*Node, error) {
|
||||
attrs = normalizeAttributes(tag, tag, attrs)
|
||||
container := newElement(tag, attrs)
|
||||
children, err := renderBlockChildren(node, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
container.addChild(child)
|
||||
}
|
||||
return []*Node{container}, nil
|
||||
}
|
||||
|
||||
func renderList(list *gast.List, source []byte) ([]*Node, error) {
|
||||
if isTaskList(list) {
|
||||
return renderTaskList(list, source)
|
||||
}
|
||||
tag := "ul"
|
||||
if list.IsOrdered() {
|
||||
tag = "ol"
|
||||
}
|
||||
listNode := newElement(tag, nil)
|
||||
for child := list.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != gast.KindListItem {
|
||||
continue
|
||||
}
|
||||
item, err := renderListItem(child.(*gast.ListItem), list.IsTight, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
listNode.addChild(item)
|
||||
}
|
||||
return []*Node{listNode}, nil
|
||||
}
|
||||
|
||||
func isTaskList(list *gast.List) bool {
|
||||
first := list.FirstChild()
|
||||
if first == nil || first.Kind() != gast.KindListItem {
|
||||
return false
|
||||
}
|
||||
return findTaskCheckbox(first.(*gast.ListItem)) != nil
|
||||
}
|
||||
|
||||
func findTaskCheckbox(item *gast.ListItem) *extast.TaskCheckBox {
|
||||
for child := item.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != gast.KindTextBlock && child.Kind() != gast.KindParagraph {
|
||||
continue
|
||||
}
|
||||
if first := child.FirstChild(); first != nil && first.Kind() == extast.KindTaskCheckBox {
|
||||
return first.(*extast.TaskCheckBox)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func renderTaskList(list *gast.List, source []byte) ([]*Node, error) {
|
||||
var out []*Node
|
||||
for child := list.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != gast.KindListItem {
|
||||
continue
|
||||
}
|
||||
item := child.(*gast.ListItem)
|
||||
checkboxAST := findTaskCheckbox(item)
|
||||
if checkboxAST == nil {
|
||||
li, err := renderListItem(item, list.IsTight, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ul := newElement("ul", nil)
|
||||
ul.addChild(li)
|
||||
out = append(out, ul)
|
||||
continue
|
||||
}
|
||||
done := "false"
|
||||
if checkboxAST.IsChecked {
|
||||
done = "true"
|
||||
}
|
||||
checkbox := newElement("checkbox", map[string]string{"done": done})
|
||||
for block := item.FirstChild(); block != nil; block = block.NextSibling() {
|
||||
if block.Kind() == gast.KindTextBlock || block.Kind() == gast.KindParagraph {
|
||||
fragment, err := renderInlineFragment(block, source, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := parseXML(fragment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
checkbox.addChild(node)
|
||||
}
|
||||
continue
|
||||
}
|
||||
nodes, err := renderBlockNode(block, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
checkbox.addChild(node)
|
||||
}
|
||||
}
|
||||
out = append(out, checkbox)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func renderListItem(item *gast.ListItem, tight bool, source []byte) (*Node, error) {
|
||||
li := newElement("li", nil)
|
||||
children, err := renderBlockChildren(item, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
if child.tag == "p" && (tight || paragraphOnlyInline(child)) {
|
||||
for _, grandchild := range child.children {
|
||||
li.addChild(grandchild)
|
||||
}
|
||||
continue
|
||||
}
|
||||
li.addChild(child)
|
||||
}
|
||||
return li, nil
|
||||
}
|
||||
|
||||
func renderInlineChildren(node gast.Node, source []byte) ([]*Node, error) {
|
||||
fragment, err := renderInlineFragment(node, source, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := parseXML(fragment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stripMarkdownEscapesInNodes(nodes, false, false)
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func renderInlineFragment(parent gast.Node, source []byte, skipCheckbox bool) (string, error) {
|
||||
var out strings.Builder
|
||||
for child := parent.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if skipCheckbox && child.Kind() == extast.KindTaskCheckBox {
|
||||
continue
|
||||
}
|
||||
fragment, err := renderInlineNode(child, source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out.WriteString(fragment)
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func renderInlineNode(node gast.Node, source []byte) (string, error) {
|
||||
switch node.Kind() {
|
||||
case gast.KindText:
|
||||
textNode := node.(*gast.Text)
|
||||
value := escapeXMLText(stripBackslashEscapes(string(textNode.Value(source))))
|
||||
if textNode.HardLineBreak() || textNode.SoftLineBreak() {
|
||||
value += "<br/>"
|
||||
}
|
||||
return value, nil
|
||||
case gast.KindString:
|
||||
return escapeXMLText(string(node.(*gast.String).Value)), nil
|
||||
case gast.KindEmphasis:
|
||||
tag := "em"
|
||||
if node.(*gast.Emphasis).Level >= 2 {
|
||||
tag = "b"
|
||||
}
|
||||
return renderInlineContainer(node, tag, nil, source)
|
||||
case gast.KindCodeSpan:
|
||||
return elementXML("code", nil, escapeXMLText(collectMarkdownChildText(node, source))), nil
|
||||
case gast.KindLink:
|
||||
link := node.(*gast.Link)
|
||||
attrs := map[string]string{"href": string(link.Destination)}
|
||||
if len(link.Title) > 0 {
|
||||
attrs["title"] = string(link.Title)
|
||||
}
|
||||
children, err := renderInlineFragment(node, source, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if children == "" {
|
||||
children = escapeXMLText(string(link.Destination))
|
||||
}
|
||||
return elementXML("a", attrs, children), nil
|
||||
case gast.KindImage:
|
||||
image := node.(*gast.Image)
|
||||
destination := string(image.Destination)
|
||||
attrs := map[string]string{}
|
||||
if strings.HasPrefix(destination, "http://") || strings.HasPrefix(destination, "https://") {
|
||||
attrs["href"] = destination
|
||||
} else {
|
||||
attrs["src"] = destination
|
||||
}
|
||||
if len(image.Title) > 0 {
|
||||
attrs["title"] = string(image.Title)
|
||||
}
|
||||
return elementXML("img", attrs, ""), nil
|
||||
case gast.KindRawHTML:
|
||||
return string(node.(*gast.RawHTML).Segments.Value(source)), nil
|
||||
case gast.KindAutoLink:
|
||||
link := node.(*gast.AutoLink)
|
||||
return elementXML("a", map[string]string{"href": string(link.URL(source))}, escapeXMLText(string(link.Label(source)))), nil
|
||||
}
|
||||
|
||||
switch node.Kind() {
|
||||
case extast.KindStrikethrough:
|
||||
return renderInlineContainer(node, "del", nil, source)
|
||||
case kindMathInline:
|
||||
return elementXML("latex", nil, escapeXMLText(stripLatexMarkdownEscapes(string(node.(*mathInline).content)))), nil
|
||||
case kindMathBlock:
|
||||
return elementXML("latex", nil, escapeXMLText(stripLatexMarkdownEscapes(string(node.(*mathBlock).content)))), nil
|
||||
case extast.KindTaskCheckBox:
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if node.Type() == gast.TypeBlock {
|
||||
return escapeXMLText(strings.TrimSpace(extractMarkdownText(node, source))), nil
|
||||
}
|
||||
return escapeXMLText(extractMarkdownText(node, source)), nil
|
||||
}
|
||||
|
||||
func renderInlineContainer(node gast.Node, tag string, attrs map[string]string, source []byte) (string, error) {
|
||||
children, err := renderInlineFragment(node, source, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return elementXML(tag, attrs, children), nil
|
||||
}
|
||||
|
||||
func elementXML(tag string, attrs map[string]string, inner string) string {
|
||||
node := newElement(tag, attrs)
|
||||
rendered := renderNodes([]*Node{node})
|
||||
if inner == "" {
|
||||
return rendered
|
||||
}
|
||||
close := "</" + tag + ">"
|
||||
if strings.HasSuffix(rendered, close) {
|
||||
return strings.TrimSuffix(rendered, close) + inner + close
|
||||
}
|
||||
return rendered
|
||||
}
|
||||
|
||||
func wrapParagraphChildren(children []*Node) []*Node {
|
||||
var out []*Node
|
||||
var inline []*Node
|
||||
flush := func() {
|
||||
if len(inline) == 0 {
|
||||
return
|
||||
}
|
||||
paragraph := newElement("p", nil)
|
||||
for _, child := range inline {
|
||||
paragraph.addChild(child)
|
||||
}
|
||||
out = append(out, paragraph)
|
||||
inline = nil
|
||||
}
|
||||
for _, child := range children {
|
||||
if child != nil && child.typ == nodeElement && layoutOf(child.tag) == layoutBlock {
|
||||
flush()
|
||||
out = append(out, child)
|
||||
continue
|
||||
}
|
||||
inline = append(inline, child)
|
||||
}
|
||||
flush()
|
||||
return out
|
||||
}
|
||||
|
||||
func paragraphOnlyInline(node *Node) bool {
|
||||
if node == nil || node.typ != nodeElement || node.tag != "p" {
|
||||
return false
|
||||
}
|
||||
for _, child := range node.children {
|
||||
if child.typ == nodeElement && layoutOf(child.tag) == layoutBlock {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func renderTable(node gast.Node, source []byte) ([]*Node, error) {
|
||||
table := newElement("table", nil)
|
||||
var body *Node
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
switch child.Kind() {
|
||||
case extast.KindTableHeader:
|
||||
head := newElement("thead", nil)
|
||||
row, err := renderTableRow(child, true, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
head.addChild(row)
|
||||
table.addChild(head)
|
||||
case extast.KindTableRow:
|
||||
if body == nil {
|
||||
body = newElement("tbody", nil)
|
||||
table.addChild(body)
|
||||
}
|
||||
row, err := renderTableRow(child, false, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body.addChild(row)
|
||||
}
|
||||
}
|
||||
return []*Node{table}, nil
|
||||
}
|
||||
|
||||
func renderTableRow(node gast.Node, header bool, source []byte) (*Node, error) {
|
||||
row := newElement("tr", nil)
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != extast.KindTableCell {
|
||||
continue
|
||||
}
|
||||
cellAST := child.(*extast.TableCell)
|
||||
tag := "td"
|
||||
if header {
|
||||
tag = "th"
|
||||
}
|
||||
attrs := map[string]string(nil)
|
||||
switch cellAST.Alignment {
|
||||
case extast.AlignCenter:
|
||||
attrs = map[string]string{"align": "center"}
|
||||
case extast.AlignRight:
|
||||
attrs = map[string]string{"align": "right"}
|
||||
}
|
||||
cell := newElement(tag, attrs)
|
||||
content, err := renderInlineChildren(cellAST, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, inline := range content {
|
||||
cell.addChild(inline)
|
||||
}
|
||||
row.addChild(cell)
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func renderDefinitionList(node gast.Node, source []byte) ([]*Node, error) {
|
||||
var out []*Node
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
switch child.Kind() {
|
||||
case extast.KindDefinitionTerm:
|
||||
fragment, err := renderInlineFragment(child, source, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := parseXML(fragment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paragraph := newElement("p", nil)
|
||||
bold := newElement("b", nil)
|
||||
for _, node := range nodes {
|
||||
bold.addChild(node)
|
||||
}
|
||||
paragraph.addChild(bold)
|
||||
out = append(out, paragraph)
|
||||
case extast.KindDefinitionDescription:
|
||||
quote, err := renderContainer("blockquote", nil, child, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, quote...)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func appendRawTextWithBreaks(parent *Node, content string) {
|
||||
if content == "" {
|
||||
return
|
||||
}
|
||||
start := 0
|
||||
for i := 0; i < len(content); i++ {
|
||||
if content[i] != '\n' && content[i] != '\r' {
|
||||
continue
|
||||
}
|
||||
if i > start {
|
||||
parent.addChild(newText(content[start:i]))
|
||||
}
|
||||
if content[i] == '\r' && i+1 < len(content) && content[i+1] == '\n' {
|
||||
i++
|
||||
}
|
||||
parent.addChild(newElement("br", nil))
|
||||
start = i + 1
|
||||
}
|
||||
if start < len(content) {
|
||||
parent.addChild(newText(content[start:]))
|
||||
}
|
||||
}
|
||||
|
||||
func stripMarkdownEscapesInNodes(nodes []*Node, inCode, inLatex bool) {
|
||||
for _, node := range nodes {
|
||||
if node == nil {
|
||||
continue
|
||||
}
|
||||
if node.typ == nodeText {
|
||||
switch {
|
||||
case inCode:
|
||||
case inLatex:
|
||||
node.text = stripLatexMarkdownEscapes(node.text)
|
||||
default:
|
||||
node.text = stripBackslashEscapes(node.text)
|
||||
}
|
||||
continue
|
||||
}
|
||||
stripMarkdownEscapesInNodes(node.children, inCode || node.tag == "code" || node.tag == "pre", inLatex || node.tag == "latex")
|
||||
}
|
||||
}
|
||||
|
||||
func stripBackslashEscapes(value string) string {
|
||||
if !strings.Contains(value, `\`) {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value))
|
||||
for i := 0; i < len(value); i++ {
|
||||
if value[i] == '\\' && i+1 < len(value) && isASCIIPunctuation(value[i+1]) {
|
||||
out.WriteByte(value[i+1])
|
||||
i++
|
||||
continue
|
||||
}
|
||||
out.WriteByte(value[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func stripLatexMarkdownEscapes(value string) string {
|
||||
if !strings.Contains(value, `\`) {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value))
|
||||
for i := 0; i < len(value); i++ {
|
||||
if value[i] == '\\' && i+1 < len(value) && strings.ContainsRune("_^&*[]$~<>`#+-=:", rune(value[i+1])) {
|
||||
out.WriteByte(value[i+1])
|
||||
i++
|
||||
continue
|
||||
}
|
||||
out.WriteByte(value[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func isASCIIPunctuation(ch byte) bool {
|
||||
return ch >= '!' && ch <= '/' || ch >= ':' && ch <= '@' || ch >= '[' && ch <= '`' || ch >= '{' && ch <= '~'
|
||||
}
|
||||
|
||||
func trimOneTrailingNewline(value string) string {
|
||||
if strings.HasSuffix(value, "\r\n") {
|
||||
return value[:len(value)-2]
|
||||
}
|
||||
return strings.TrimSuffix(value, "\n")
|
||||
}
|
||||
|
||||
func collectMarkdownChildText(node gast.Node, source []byte) string {
|
||||
var out strings.Builder
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
switch child.Kind() {
|
||||
case gast.KindText:
|
||||
out.Write(child.(*gast.Text).Value(source))
|
||||
case gast.KindString:
|
||||
out.Write(child.(*gast.String).Value)
|
||||
default:
|
||||
out.WriteString(collectMarkdownChildText(child, source))
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func extractMarkdownText(node gast.Node, source []byte) string {
|
||||
switch node.Kind() {
|
||||
case gast.KindText:
|
||||
return string(node.(*gast.Text).Value(source))
|
||||
case gast.KindString:
|
||||
return string(node.(*gast.String).Value)
|
||||
case gast.KindCodeSpan:
|
||||
return collectMarkdownChildText(node, source)
|
||||
}
|
||||
if node.Type() == gast.TypeBlock && node.Lines() != nil && node.Lines().Len() > 0 {
|
||||
return string(node.Lines().Value(source))
|
||||
}
|
||||
var out strings.Builder
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
out.WriteString(extractMarkdownText(child, source))
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func headingTag(level int) string {
|
||||
if level < 1 || level > 6 {
|
||||
return "p"
|
||||
}
|
||||
return fmt.Sprintf("h%d", level)
|
||||
}
|
||||
|
||||
func normalizeListIndent(markdown string) string {
|
||||
lines := strings.Split(markdown, "\n")
|
||||
type stackEntry struct{ indent int }
|
||||
var stack []stackEntry
|
||||
inFence := false
|
||||
changed := false
|
||||
lastOriginal, lastNormalized := 0, 0
|
||||
for i, line := range lines {
|
||||
trimmed := strings.TrimLeft(line, " ")
|
||||
if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
|
||||
inFence = !inFence
|
||||
continue
|
||||
}
|
||||
if inFence || trimmed == "" {
|
||||
continue
|
||||
}
|
||||
indent := len(line) - len(trimmed)
|
||||
if markdownListMarkerLength(trimmed) > 0 {
|
||||
for len(stack) > 0 && indent <= stack[len(stack)-1].indent {
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
normalized := len(stack) * 4
|
||||
stack = append(stack, stackEntry{indent: indent})
|
||||
lastOriginal, lastNormalized = indent, normalized
|
||||
if indent != normalized {
|
||||
lines[i] = strings.Repeat(" ", normalized) + trimmed
|
||||
changed = true
|
||||
}
|
||||
} else if len(stack) > 0 && indent > lastOriginal {
|
||||
delta := lastNormalized - lastOriginal
|
||||
if delta != 0 {
|
||||
normalized := indent + delta
|
||||
if normalized < 0 {
|
||||
normalized = 0
|
||||
}
|
||||
lines[i] = strings.Repeat(" ", normalized) + trimmed
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return markdown
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func markdownListMarkerLength(value string) int {
|
||||
if len(value) >= 2 && (value[0] == '-' || value[0] == '*' || value[0] == '+') && value[1] == ' ' {
|
||||
return 2
|
||||
}
|
||||
i := 0
|
||||
for i < len(value) && value[i] >= '0' && value[i] <= '9' {
|
||||
i++
|
||||
}
|
||||
if i > 0 && i+1 < len(value) && (value[i] == '.' || value[i] == ')') && value[i+1] == ' ' {
|
||||
return i + 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
284
shortcuts/doc/internal/docxparse/markdown_cjk.go
Normal file
284
shortcuts/doc/internal/docxparse/markdown_cjk.go
Normal file
@@ -0,0 +1,284 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// preprocessCJKAdjacentMarkup disambiguates a narrow CommonMark pattern common in
|
||||
// Chinese prose: emphasis that ends in punctuation and is immediately followed
|
||||
// by a letter (for example **结论。**下一步). Goldmark correctly follows
|
||||
// CommonMark's delimiter rules, while LarkOpenCLI accepts this authoring form.
|
||||
// Rewriting simple CJK delimiter spans to equivalent DocxXML
|
||||
// before parsing removes the ambiguity while leaving nested Markdown, links,
|
||||
// code, fenced blocks, and source-bearing XML untouched.
|
||||
func preprocessCJKAdjacentMarkup(markdown string) string {
|
||||
if !strings.Contains(markdown, "**") && !strings.Contains(markdown, "~~") {
|
||||
return markdown
|
||||
}
|
||||
lines := strings.SplitAfter(markdown, "\n")
|
||||
var out strings.Builder
|
||||
fenceMarker := rune(0)
|
||||
fenceLength := 0
|
||||
rawSourceTag := ""
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimLeft(line, " \t>")
|
||||
if marker, length, ok := markdownFence(trimmed); ok {
|
||||
if fenceMarker == 0 {
|
||||
fenceMarker, fenceLength = marker, length
|
||||
} else if marker == fenceMarker && length >= fenceLength && strings.TrimSpace(runeTail(trimmed, length)) == "" {
|
||||
fenceMarker, fenceLength = 0, 0
|
||||
}
|
||||
out.WriteString(line)
|
||||
continue
|
||||
}
|
||||
if fenceMarker != 0 || leadingIndent(line) >= 4 {
|
||||
out.WriteString(line)
|
||||
continue
|
||||
}
|
||||
out.WriteString(rewriteCJKMarkupLine(line, &rawSourceTag))
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func markdownFence(line string) (rune, int, bool) {
|
||||
runes := []rune(line)
|
||||
if len(runes) < 3 || runes[0] != '`' && runes[0] != '~' {
|
||||
return 0, 0, false
|
||||
}
|
||||
marker := runes[0]
|
||||
length := 0
|
||||
for length < len(runes) && runes[length] == marker {
|
||||
length++
|
||||
}
|
||||
return marker, length, length >= 3
|
||||
}
|
||||
|
||||
func runeTail(value string, start int) string {
|
||||
runes := []rune(value)
|
||||
if start >= len(runes) {
|
||||
return ""
|
||||
}
|
||||
return string(runes[start:])
|
||||
}
|
||||
|
||||
func leadingIndent(line string) int {
|
||||
count := 0
|
||||
for _, r := range line {
|
||||
switch r {
|
||||
case ' ':
|
||||
count++
|
||||
case '\t':
|
||||
count += 4
|
||||
default:
|
||||
return count
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
type cjkMarkupRule struct {
|
||||
delimiter []rune
|
||||
openXML string
|
||||
closeXML string
|
||||
}
|
||||
|
||||
var cjkMarkupRules = []cjkMarkupRule{
|
||||
{delimiter: []rune("***"), openXML: "<em><b>", closeXML: "</b></em>"},
|
||||
{delimiter: []rune("~~"), openXML: "<del>", closeXML: "</del>"},
|
||||
{delimiter: []rune("**"), openXML: "<b>", closeXML: "</b>"},
|
||||
}
|
||||
|
||||
func rewriteCJKMarkupLine(line string, rawSourceTag *string) string {
|
||||
if *rawSourceTag != "" {
|
||||
runes := []rune(line)
|
||||
closeTag := []rune("</" + *rawSourceTag + ">")
|
||||
closeAt := indexRunesFold(runes, 0, closeTag)
|
||||
if closeAt < 0 {
|
||||
return line
|
||||
}
|
||||
closeEnd := closeAt + len(closeTag)
|
||||
prefix := string(runes[:closeEnd])
|
||||
*rawSourceTag = ""
|
||||
return prefix + rewriteCJKMarkupLine(string(runes[closeEnd:]), rawSourceTag)
|
||||
}
|
||||
|
||||
runes := []rune(line)
|
||||
var out strings.Builder
|
||||
for i := 0; i < len(runes); {
|
||||
if runes[i] == '`' && !runeEscaped(runes, i) {
|
||||
if end := codeSpanEnd(runes, i); end > i {
|
||||
out.WriteString(string(runes[i:end]))
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
if runes[i] == '<' {
|
||||
if tag, end, selfClosing, ok := rawTagAt(runes, i); ok {
|
||||
out.WriteString(string(runes[i:end]))
|
||||
i = end
|
||||
if !selfClosing && (tag == "code" || tag == "pre" || tag == "whiteboard") {
|
||||
close := []rune("</" + tag + ">")
|
||||
if closeAt := indexRunesFold(runes, i, close); closeAt >= 0 {
|
||||
closeEnd := closeAt + len(close)
|
||||
out.WriteString(string(runes[i:closeEnd]))
|
||||
i = closeEnd
|
||||
} else {
|
||||
out.WriteString(string(runes[i:]))
|
||||
*rawSourceTag = tag
|
||||
return out.String()
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
rewritten := false
|
||||
for _, rule := range cjkMarkupRules {
|
||||
if !exactDelimiterAt(runes, i, rule.delimiter) || runeEscaped(runes, i) {
|
||||
continue
|
||||
}
|
||||
closeAt := delimiterCloser(runes, i+len(rule.delimiter), rule.delimiter)
|
||||
if closeAt < 0 {
|
||||
continue
|
||||
}
|
||||
content := runes[i+len(rule.delimiter) : closeAt]
|
||||
if !shouldRewriteCJKMarkup(content) {
|
||||
continue
|
||||
}
|
||||
out.WriteString(rule.openXML)
|
||||
out.WriteString(escapeXMLText(stripBackslashEscapes(string(content))))
|
||||
out.WriteString(rule.closeXML)
|
||||
i = closeAt + len(rule.delimiter)
|
||||
rewritten = true
|
||||
break
|
||||
}
|
||||
if rewritten {
|
||||
continue
|
||||
}
|
||||
out.WriteRune(runes[i])
|
||||
i++
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func rawTagAt(runes []rune, start int) (tag string, end int, selfClosing, ok bool) {
|
||||
if start+1 >= len(runes) || !isASCIILetterRune(runes[start+1]) {
|
||||
return "", 0, false, false
|
||||
}
|
||||
i := start + 1
|
||||
for i < len(runes) && (isASCIILetterRune(runes[i]) || isASCIIDigitRune(runes[i]) || runes[i] == '-' || runes[i] == '_') {
|
||||
i++
|
||||
}
|
||||
tag = strings.ToLower(string(runes[start+1 : i]))
|
||||
quote := rune(0)
|
||||
for ; i < len(runes); i++ {
|
||||
if runes[i] == '\'' || runes[i] == '"' {
|
||||
if quote == 0 {
|
||||
quote = runes[i]
|
||||
} else if quote == runes[i] {
|
||||
quote = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if runes[i] == '>' && quote == 0 {
|
||||
trimmed := strings.TrimSpace(string(runes[start : i+1]))
|
||||
return tag, i + 1, strings.HasSuffix(trimmed, "/>"), true
|
||||
}
|
||||
}
|
||||
return "", 0, false, false
|
||||
}
|
||||
|
||||
func indexRunesFold(haystack []rune, start int, needle []rune) int {
|
||||
for i := start; i+len(needle) <= len(haystack); i++ {
|
||||
if strings.EqualFold(string(haystack[i:i+len(needle)]), string(needle)) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func codeSpanEnd(runes []rune, open int) int {
|
||||
length := 0
|
||||
for open+length < len(runes) && runes[open+length] == '`' {
|
||||
length++
|
||||
}
|
||||
for i := open + length; i < len(runes); i++ {
|
||||
if runes[i] != '`' || runeEscaped(runes, i) {
|
||||
continue
|
||||
}
|
||||
end := i
|
||||
for end < len(runes) && runes[end] == '`' {
|
||||
end++
|
||||
}
|
||||
if end-i == length {
|
||||
return end
|
||||
}
|
||||
i = end - 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func exactDelimiterAt(runes []rune, start int, delimiter []rune) bool {
|
||||
if start+len(delimiter) > len(runes) {
|
||||
return false
|
||||
}
|
||||
for i, want := range delimiter {
|
||||
if runes[start+i] != want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
marker := delimiter[0]
|
||||
return (start == 0 || runes[start-1] != marker) && (start+len(delimiter) == len(runes) || runes[start+len(delimiter)] != marker)
|
||||
}
|
||||
|
||||
func delimiterCloser(runes []rune, start int, delimiter []rune) int {
|
||||
for i := start; i+len(delimiter) <= len(runes); i++ {
|
||||
if runes[i] == '\n' {
|
||||
return -1
|
||||
}
|
||||
if exactDelimiterAt(runes, i, delimiter) && !runeEscaped(runes, i) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func shouldRewriteCJKMarkup(content []rune) bool {
|
||||
if len(content) == 0 || unicode.IsSpace(content[0]) || unicode.IsSpace(content[len(content)-1]) {
|
||||
return false
|
||||
}
|
||||
for _, r := range content {
|
||||
if r == '`' || r == '[' || r == ']' || r == '<' || r == '>' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !containsCJK(content) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func containsCJK(value []rune) bool {
|
||||
for _, r := range value {
|
||||
if isCJKRune(r) || r > unicode.MaxASCII && (unicode.IsPunct(r) || unicode.IsSymbol(r)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isCJKRune(r rune) bool {
|
||||
return unicode.In(r, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
|
||||
}
|
||||
|
||||
func runeEscaped(runes []rune, index int) bool {
|
||||
count := 0
|
||||
for i := index - 1; i >= 0 && runes[i] == '\\'; i-- {
|
||||
count++
|
||||
}
|
||||
return count%2 == 1
|
||||
}
|
||||
334
shortcuts/doc/internal/docxparse/markdown_extensions.go
Normal file
334
shortcuts/doc/internal/docxparse/markdown_extensions.go
Normal file
@@ -0,0 +1,334 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
// This file contains the small Goldmark extensions needed to match the
|
||||
// LarkOpenCLI's Markdown surface: math, DocxXML tag names containing
|
||||
// underscores, and Markdown-aware callout/grid/column containers.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yuin/goldmark"
|
||||
gast "github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
gmutil "github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
// ---------- Math ----------
|
||||
|
||||
var kindMathInline = gast.NewNodeKind("DocxMathInline")
|
||||
var kindMathBlock = gast.NewNodeKind("DocxMathBlock")
|
||||
|
||||
type mathInline struct {
|
||||
gast.BaseInline
|
||||
content []byte
|
||||
}
|
||||
|
||||
func (n *mathInline) Kind() gast.NodeKind { return kindMathInline }
|
||||
func (n *mathInline) Dump(source []byte, level int) {
|
||||
gast.DumpHelper(n, source, level, nil, nil)
|
||||
}
|
||||
|
||||
type mathBlock struct {
|
||||
gast.BaseInline
|
||||
content []byte
|
||||
}
|
||||
|
||||
func (n *mathBlock) Kind() gast.NodeKind { return kindMathBlock }
|
||||
func (n *mathBlock) Dump(source []byte, level int) {
|
||||
gast.DumpHelper(n, source, level, nil, nil)
|
||||
}
|
||||
|
||||
var (
|
||||
mathBlockMultiLine = regexp.MustCompile(`(?s)^\$\$(.+?)\$\$`)
|
||||
mathInlineMultiLine = regexp.MustCompile(`(?s)^\$([^ \t$].*?)\$`)
|
||||
)
|
||||
|
||||
type mathInlineParser struct{}
|
||||
|
||||
func (p *mathInlineParser) Trigger() []byte { return []byte{'$'} }
|
||||
|
||||
func (p *mathInlineParser) Parse(_ gast.Node, reader text.Reader, _ parser.Context) gast.Node {
|
||||
line, _ := reader.PeekLine()
|
||||
if len(line) == 0 || line[0] != '$' {
|
||||
return nil
|
||||
}
|
||||
if len(line) >= 2 && line[1] == '$' {
|
||||
if content, advance := scanMathClose(line[2:], "$$"); advance >= 0 && len(content) > 0 {
|
||||
reader.Advance(2 + advance)
|
||||
return &mathBlock{content: append([]byte(nil), content...)}
|
||||
}
|
||||
match := reader.FindSubMatch(mathBlockMultiLine)
|
||||
if len(match) >= 2 && len(bytes.TrimSpace(match[1])) > 0 && !bytes.Contains(match[1], []byte("<latex")) {
|
||||
return &mathBlock{content: append([]byte(nil), bytes.TrimSpace(match[1])...)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(line) < 2 || line[1] == ' ' || line[1] == '\t' || line[1] == '$' {
|
||||
return nil
|
||||
}
|
||||
if content, advance := scanMathClose(line[1:], "$"); advance >= 0 && len(content) > 0 {
|
||||
if content[len(content)-1] == ' ' || content[len(content)-1] == '\t' {
|
||||
return nil
|
||||
}
|
||||
reader.Advance(1 + advance)
|
||||
return &mathInline{content: append([]byte(nil), content...)}
|
||||
}
|
||||
match := reader.FindSubMatch(mathInlineMultiLine)
|
||||
if len(match) < 2 || bytes.Contains(match[1], []byte("<latex")) {
|
||||
return nil
|
||||
}
|
||||
trimmed := bytes.TrimRight(match[1], "\n\r")
|
||||
if len(trimmed) == 0 || trimmed[len(trimmed)-1] == ' ' || trimmed[len(trimmed)-1] == '\t' {
|
||||
return nil
|
||||
}
|
||||
return &mathInline{content: append([]byte(nil), trimmed...)}
|
||||
}
|
||||
|
||||
func scanMathClose(data []byte, delimiter string) ([]byte, int) {
|
||||
delim := []byte(delimiter)
|
||||
for offset := 0; offset < len(data); {
|
||||
if data[offset] == '\\' && offset+1 < len(data) && data[offset+1] == '$' {
|
||||
offset += 2
|
||||
continue
|
||||
}
|
||||
rel := bytes.Index(data[offset:], delim)
|
||||
if rel < 0 {
|
||||
return nil, -1
|
||||
}
|
||||
end := offset + rel
|
||||
if bytes.Contains(data[:end], []byte("<latex")) {
|
||||
return nil, -1
|
||||
}
|
||||
return data[:end], end + len(delim)
|
||||
}
|
||||
return nil, -1
|
||||
}
|
||||
|
||||
type mathExtension struct{}
|
||||
|
||||
func (e *mathExtension) Extend(markdown goldmark.Markdown) {
|
||||
markdown.Parser().AddOptions(parser.WithInlineParsers(
|
||||
gmutil.Prioritized(&mathInlineParser{}, 100),
|
||||
))
|
||||
}
|
||||
|
||||
// ---------- Underscore-bearing raw XML tags ----------
|
||||
|
||||
type underscoreHTMLExtension struct{}
|
||||
|
||||
func (e *underscoreHTMLExtension) Extend(markdown goldmark.Markdown) {
|
||||
markdown.Parser().AddOptions(
|
||||
parser.WithInlineParsers(gmutil.Prioritized(&underscoreRawHTMLParser{}, 99)),
|
||||
parser.WithBlockParsers(gmutil.Prioritized(&underscoreHTMLBlockParser{}, 99)),
|
||||
)
|
||||
}
|
||||
|
||||
var (
|
||||
extendedTagNamePattern = `([A-Za-z][A-Za-z0-9_-]*)`
|
||||
extendedAttributePattern = `(?:\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\s*=\s*(?:[^"'=<>` + "`" + `\x00-\x20]+|'[^']*'|"[^"]*"))?)`
|
||||
extendedOpenTag = regexp.MustCompile("^<" + extendedTagNamePattern + extendedAttributePattern + `*\s*/?>`)
|
||||
extendedCloseTag = regexp.MustCompile("^</" + extendedTagNamePattern + `\s*>`)
|
||||
peekExtendedOpenTag = regexp.MustCompile(`^<([A-Za-z][A-Za-z0-9_-]*)`)
|
||||
peekExtendedCloseTag = regexp.MustCompile(`^</([A-Za-z][A-Za-z0-9_-]*)`)
|
||||
extendedBlockTag = regexp.MustCompile(`^[ ]{0,3}<(/)?\s*([a-zA-Z0-9_\-]+)(` + extendedAttributePattern + `*)\s*(?:>|/>)\s*\n?$`)
|
||||
)
|
||||
|
||||
type underscoreRawHTMLParser struct{}
|
||||
|
||||
func (p *underscoreRawHTMLParser) Trigger() []byte { return []byte{'<'} }
|
||||
|
||||
func (p *underscoreRawHTMLParser) Parse(_ gast.Node, reader text.Reader, _ parser.Context) gast.Node {
|
||||
line, _ := reader.PeekLine()
|
||||
if len(line) > 1 && gmutil.IsAlphaNumeric(line[1]) {
|
||||
if match := peekExtendedOpenTag.FindSubmatch(line); match != nil && bytes.IndexByte(match[1], '_') >= 0 {
|
||||
return p.parseMultiLine(extendedOpenTag, reader)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(line) > 2 && line[1] == '/' && gmutil.IsAlphaNumeric(line[2]) {
|
||||
if match := peekExtendedCloseTag.FindSubmatch(line); match != nil && bytes.IndexByte(match[1], '_') >= 0 {
|
||||
return p.parseMultiLine(extendedCloseTag, reader)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *underscoreRawHTMLParser) parseMultiLine(re *regexp.Regexp, reader text.Reader) gast.Node {
|
||||
startLine, startSegment := reader.Position()
|
||||
if !reader.Match(re) {
|
||||
return nil
|
||||
}
|
||||
endLine, endSegment := reader.Position()
|
||||
reader.SetPosition(startLine, startSegment)
|
||||
node := gast.NewRawHTML()
|
||||
for {
|
||||
line, segment := reader.PeekLine()
|
||||
if line == nil {
|
||||
break
|
||||
}
|
||||
lineNo, _ := reader.Position()
|
||||
start := segment.Start
|
||||
if lineNo == startLine {
|
||||
start = startSegment.Start
|
||||
}
|
||||
end := segment.Stop
|
||||
if lineNo == endLine {
|
||||
end = endSegment.Start
|
||||
}
|
||||
node.Segments.Append(text.NewSegment(start, end))
|
||||
if lineNo == endLine {
|
||||
reader.Advance(end - start)
|
||||
break
|
||||
}
|
||||
reader.AdvanceLine()
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
type underscoreHTMLBlockParser struct{}
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Trigger() []byte { return []byte{'<'} }
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Open(_ gast.Node, reader text.Reader, pc parser.Context) (gast.Node, parser.State) {
|
||||
line, segment := reader.PeekLine()
|
||||
pos := pc.BlockOffset()
|
||||
if pos < 0 || pos >= len(line) || line[pos] != '<' {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
match := extendedBlockTag.FindSubmatchIndex(line)
|
||||
if match == nil {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
tag := string(line[match[4]:match[5]])
|
||||
if !strings.Contains(tag, "_") {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
isClose := match[2] > -1 && bytes.Equal(line[match[2]:match[3]], []byte("/"))
|
||||
hasAttrs := match[6] != match[7]
|
||||
if isClose && hasAttrs {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
node := gast.NewHTMLBlock(gast.HTMLBlockType7)
|
||||
node.Lines().Append(segment)
|
||||
reader.Advance(segment.Len() - 1)
|
||||
return node, parser.NoChildren
|
||||
}
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Continue(node gast.Node, reader text.Reader, _ parser.Context) parser.State {
|
||||
line, segment := reader.PeekLine()
|
||||
if gmutil.IsBlank(line) {
|
||||
return parser.Close
|
||||
}
|
||||
node.Lines().Append(segment)
|
||||
reader.Advance(segment.Len() - 1)
|
||||
return parser.Continue | parser.NoChildren
|
||||
}
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Close(gast.Node, text.Reader, parser.Context) {}
|
||||
func (p *underscoreHTMLBlockParser) CanInterruptParagraph() bool { return false }
|
||||
func (p *underscoreHTMLBlockParser) CanAcceptIndentedLine() bool { return false }
|
||||
|
||||
// ---------- Markdown-aware DocxXML containers ----------
|
||||
|
||||
type containerSpec struct {
|
||||
tag string
|
||||
}
|
||||
|
||||
var containerSpecs = map[string]*containerSpec{
|
||||
"callout": {tag: "callout"},
|
||||
"grid": {tag: "grid"},
|
||||
"column": {tag: "column"},
|
||||
"div": {tag: "div"},
|
||||
}
|
||||
|
||||
var kindContainerBlock = gast.NewNodeKind("DocxContainerBlock")
|
||||
|
||||
type containerBlock struct {
|
||||
gast.BaseBlock
|
||||
spec *containerSpec
|
||||
attrs map[string]string
|
||||
}
|
||||
|
||||
func (n *containerBlock) Kind() gast.NodeKind { return kindContainerBlock }
|
||||
func (n *containerBlock) Dump(source []byte, level int) {
|
||||
gast.DumpHelper(n, source, level, nil, nil)
|
||||
}
|
||||
|
||||
type containerBlockParser struct{}
|
||||
|
||||
func (p *containerBlockParser) Trigger() []byte { return []byte{'<'} }
|
||||
|
||||
var containerOpenTag = regexp.MustCompile(`^<([A-Za-z][A-Za-z0-9_-]*)`)
|
||||
|
||||
func (p *containerBlockParser) Open(_ gast.Node, reader text.Reader, _ parser.Context) (gast.Node, parser.State) {
|
||||
line, _ := reader.PeekLine()
|
||||
trimmed := bytes.TrimLeft(line, " \t")
|
||||
leading := len(line) - len(trimmed)
|
||||
if len(trimmed) < 2 || trimmed[0] != '<' {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
match := containerOpenTag.FindSubmatch(trimmed)
|
||||
if match == nil {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
spec := containerSpecs[strings.ToLower(string(match[1]))]
|
||||
if spec == nil {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
openEnd := bytes.IndexByte(trimmed, '>')
|
||||
if openEnd < 0 || openEnd >= 1 && trimmed[openEnd-1] == '/' {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
tagEnd := len(match[0])
|
||||
node := &containerBlock{spec: spec, attrs: parseAttributes(string(trimmed[tagEnd:openEnd]))}
|
||||
reader.Advance(leading + openEnd + 1)
|
||||
return node, parser.HasChildren
|
||||
}
|
||||
|
||||
func (p *containerBlockParser) Continue(node gast.Node, reader text.Reader, _ parser.Context) parser.State {
|
||||
container := node.(*containerBlock)
|
||||
line, segment := reader.PeekLine()
|
||||
trimmed := bytes.TrimLeft(line, " \t")
|
||||
if hasCloseTagPrefix(trimmed, container.spec.tag) {
|
||||
reader.Advance(len(line) - len(trimmed) + closeTagLength(container.spec.tag))
|
||||
return parser.Close
|
||||
}
|
||||
if isXMLTagLine(trimmed) {
|
||||
indent := len(line) - len(trimmed)
|
||||
if indent > 0 && segment.Start+indent <= segment.Stop {
|
||||
reader.AdvanceAndSetPadding(indent, 0)
|
||||
}
|
||||
}
|
||||
return parser.Continue | parser.HasChildren
|
||||
}
|
||||
|
||||
func (p *containerBlockParser) Close(gast.Node, text.Reader, parser.Context) {}
|
||||
func (p *containerBlockParser) CanInterruptParagraph() bool { return true }
|
||||
func (p *containerBlockParser) CanAcceptIndentedLine() bool { return true }
|
||||
|
||||
func closeTagLength(tag string) int { return len(tag) + len("</>") }
|
||||
|
||||
func hasCloseTagPrefix(line []byte, tag string) bool {
|
||||
want := []byte("</" + tag + ">")
|
||||
return len(line) >= len(want) && bytes.EqualFold(line[:len(want)], want)
|
||||
}
|
||||
|
||||
func isXMLTagLine(line []byte) bool {
|
||||
if len(line) < 2 || line[0] != '<' {
|
||||
return false
|
||||
}
|
||||
if line[1] == '/' {
|
||||
return len(line) >= 3 && isASCIILetter(line[2])
|
||||
}
|
||||
return isASCIILetter(line[1])
|
||||
}
|
||||
|
||||
func isASCIILetter(ch byte) bool {
|
||||
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'
|
||||
}
|
||||
172
shortcuts/doc/internal/docxparse/model.go
Normal file
172
shortcuts/doc/internal/docxparse/model.go
Normal file
@@ -0,0 +1,172 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package docxparse parses LarkOpenCLI DocxXML and Markdown into a small,
|
||||
// offline DOM for the docs +script shortcut.
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Format is an accepted source document format.
|
||||
type Format string
|
||||
|
||||
const (
|
||||
FormatXML Format = "xml"
|
||||
FormatMarkdown Format = "markdown"
|
||||
)
|
||||
|
||||
// ParseResult is the complete result returned by Parse.
|
||||
type ParseResult struct {
|
||||
Format Format `json:"format"`
|
||||
XML string `json:"xml"`
|
||||
Profile Profile `json:"profile"`
|
||||
}
|
||||
|
||||
type nodeType uint8
|
||||
|
||||
const (
|
||||
nodeText nodeType = iota
|
||||
nodeElement
|
||||
)
|
||||
|
||||
// Node is the internal DocxXML DOM representation.
|
||||
type Node struct {
|
||||
typ nodeType
|
||||
tag string
|
||||
attrs map[string]string
|
||||
children []*Node
|
||||
text string
|
||||
parent *Node
|
||||
}
|
||||
|
||||
func newText(text string) *Node {
|
||||
return &Node{typ: nodeText, text: text}
|
||||
}
|
||||
|
||||
func newElement(tag string, attrs map[string]string) *Node {
|
||||
return &Node{typ: nodeElement, tag: tag, attrs: attrs}
|
||||
}
|
||||
|
||||
func (n *Node) addChild(child *Node) {
|
||||
if n == nil || child == nil {
|
||||
return
|
||||
}
|
||||
child.parent = n
|
||||
n.children = append(n.children, child)
|
||||
}
|
||||
|
||||
func (n *Node) writeXML(out *strings.Builder) {
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
if n.typ == nodeText {
|
||||
out.WriteString(escapeXMLText(n.text))
|
||||
return
|
||||
}
|
||||
|
||||
out.WriteByte('<')
|
||||
out.WriteString(n.tag)
|
||||
keys := make([]string, 0, len(n.attrs))
|
||||
for key := range n.attrs {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
wi, iWeighted := attributeWeight[keys[i]]
|
||||
wj, jWeighted := attributeWeight[keys[j]]
|
||||
switch {
|
||||
case iWeighted && jWeighted && wi != wj:
|
||||
return wi < wj
|
||||
case iWeighted != jWeighted:
|
||||
return iWeighted
|
||||
default:
|
||||
return keys[i] < keys[j]
|
||||
}
|
||||
})
|
||||
for _, key := range keys {
|
||||
out.WriteByte(' ')
|
||||
out.WriteString(key)
|
||||
out.WriteString(`="`)
|
||||
out.WriteString(escapeXMLAttr(n.attrs[key]))
|
||||
out.WriteByte('"')
|
||||
}
|
||||
|
||||
if isVoidTag(n.tag) {
|
||||
out.WriteString("/>")
|
||||
return
|
||||
}
|
||||
out.WriteByte('>')
|
||||
for _, child := range n.children {
|
||||
child.writeXML(out)
|
||||
}
|
||||
out.WriteString("</")
|
||||
out.WriteString(n.tag)
|
||||
out.WriteByte('>')
|
||||
}
|
||||
|
||||
func renderNodes(nodes []*Node) string {
|
||||
var out strings.Builder
|
||||
for _, node := range nodes {
|
||||
node.writeXML(&out)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
var attributeWeight = map[string]int{
|
||||
"id": 0,
|
||||
"name": 1,
|
||||
"top-block-id": 2,
|
||||
"parent-block-path": 3,
|
||||
"mode": 4,
|
||||
"start-block-id": 5,
|
||||
"end-block-id": 6,
|
||||
"hit-block-ids": 7,
|
||||
}
|
||||
|
||||
func escapeXMLText(value string) string {
|
||||
if !strings.ContainsAny(value, "&<>") {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value) + 8)
|
||||
for _, r := range value {
|
||||
switch r {
|
||||
case '&':
|
||||
out.WriteString("&")
|
||||
case '<':
|
||||
out.WriteString("<")
|
||||
case '>':
|
||||
out.WriteString(">")
|
||||
default:
|
||||
out.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func escapeXMLAttr(value string) string {
|
||||
if !strings.ContainsAny(value, "&<>\"'") {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value) + 8)
|
||||
for _, r := range value {
|
||||
switch r {
|
||||
case '&':
|
||||
out.WriteString("&")
|
||||
case '<':
|
||||
out.WriteString("<")
|
||||
case '>':
|
||||
out.WriteString(">")
|
||||
case '"':
|
||||
out.WriteString(""")
|
||||
case '\'':
|
||||
out.WriteString("'")
|
||||
default:
|
||||
out.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
432
shortcuts/doc/internal/docxparse/parse_test.go
Normal file
432
shortcuts/doc/internal/docxparse/parse_test.go
Normal file
@@ -0,0 +1,432 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseXMLBuildsBlockDistribution(t *testing.T) {
|
||||
result, err := Parse(`<title>T</title><p>P</p><ul><li>A</li><li>B</li></ul>`, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<title>T</title><p>P</p><ul><li>A</li><li>B</li></ul>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
if result.Profile.BlockCount != 5 {
|
||||
t.Fatalf("block total = %d, want 5", result.Profile.BlockCount)
|
||||
}
|
||||
shares := map[string]BlockShare{}
|
||||
for _, share := range result.Profile.Blocks {
|
||||
shares[share.Type] = share
|
||||
}
|
||||
if got := shares["li"]; got.Count != 2 || got.Ratio != 0.4 {
|
||||
t.Fatalf("li share = %+v, want count=2 ratio=0.4", got)
|
||||
}
|
||||
for _, typ := range []string{"title", "p", "ul"} {
|
||||
if got := shares[typ]; got.Count != 1 || got.Ratio != 0.2 {
|
||||
t.Errorf("%s share = %+v, want count=1 ratio=0.2", typ, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLRejectsInvalidInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
}{
|
||||
{name: "unsupported tag", source: `<unknown>x</unknown>`},
|
||||
{name: "missing closing tag", source: `<p>one`},
|
||||
{name: "invalid nesting", source: `<span>x<table><tr><td>y</td></tr></table></span>`},
|
||||
{name: "malformed block id", source: `<block_id="8,9"/>`},
|
||||
{name: "unterminated cdata", source: `<code><![CDATA[a < b</code>`},
|
||||
{name: "tag spacing", source: `< p>text< / p>`},
|
||||
{name: "self closing slash spacing", source: `<p/ >`},
|
||||
{name: "unquoted attribute", source: `<p align=center>text</p>`},
|
||||
{name: "invalid entity", source: `<p>one &unknown;</p>`},
|
||||
{name: "missing required ancestor", source: `<td>cell</td>`},
|
||||
{name: "missing required attribute", source: `<img/>`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := Parse(tt.source, FormatXML); err == nil {
|
||||
t.Fatalf("Parse(%q) succeeded, want validation error", tt.source)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAutoDetectsXMLAndMarkdown(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
blocks int
|
||||
}{
|
||||
{name: "xml", source: `<title>T</title><p>P</p>`, blocks: 2},
|
||||
{name: "markdown", source: "# T\n\nP", blocks: 2},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
profile, err := ParseAuto(tt.source)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseAuto() error = %v", err)
|
||||
}
|
||||
if profile.BlockCount != tt.blocks {
|
||||
t.Fatalf("profile = %+v, want %d blocks", profile, tt.blocks)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAutoDoesNotTreatMalformedXMLAsMarkdown(t *testing.T) {
|
||||
if _, err := ParseAuto(`<p>text`); err == nil {
|
||||
t.Fatal("ParseAuto() succeeded, want malformed XML error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLAcceptsPublicTagAliasesWithoutChangingInput(t *testing.T) {
|
||||
source := `<P>one<strong>two</strong><br></P><image href="https://example.com/image.png">`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
if result.Profile.BlockCount != 2 {
|
||||
t.Fatalf("profile = %+v, want p and img blocks", result.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLAcceptsPublicAttributeAliasesWithoutChangingInput(t *testing.T) {
|
||||
source := `<callout color="blue" icon="💡"><p>x</p></callout><at id="ou_legacy"></at><img url="https://example.com/image.png"/>`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
if result.Profile.BlockCount != 3 {
|
||||
t.Fatalf("profile = %+v, want callout, p, and img blocks", result.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLPreservesValidCDATA(t *testing.T) {
|
||||
source := `<code><![CDATA[a < b && c > d]]></code>`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLPreservesUTF8BOM(t *testing.T) {
|
||||
source := "\uFEFF<p>text</p>"
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original input", result.XML)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownConvertsLarkOpenCLIBlocks(t *testing.T) {
|
||||
source := "# 标题\n\nHello **world**.\n\n- [x] Done\n- [ ] Todo\n\n" +
|
||||
"| A | B |\n| --- | --- |\n| 1 | 2 |\n\n" +
|
||||
"```go\nfmt.Println(\"x\")\n```\n\n$E=mc^2$\n"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, fragment := range []string{
|
||||
`<h1>标题</h1>`,
|
||||
`<p>Hello <b>world</b>.</p>`,
|
||||
`<checkbox done="true">Done</checkbox>`,
|
||||
`<checkbox done="false">Todo</checkbox>`,
|
||||
`<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>`,
|
||||
`<pre lang="go"><code>fmt.Println("x")</code></pre>`,
|
||||
`<p><latex>E=mc^2</latex></p>`,
|
||||
} {
|
||||
if !strings.Contains(result.XML, fragment) {
|
||||
t.Errorf("XML missing %q:\n%s", fragment, result.XML)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownContainerKeepsMarkdownChildren(t *testing.T) {
|
||||
source := "<callout emoji=\"💡\">\n\n## Note\n\n- item\n\n</callout>\n"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<callout emoji="💡"><h2>Note</h2><ul><li>item</li></ul></callout>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownMatchesLarkOpenCLIFixtures(t *testing.T) {
|
||||
t.Run("deep nested list", func(t *testing.T) {
|
||||
result, err := Parse("1. 第一层\n - 第二层\n - 第三层\n - 第四层\n", FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if strings.Contains(result.XML, "<pre>") || strings.Contains(result.XML, "<code>") || !strings.Contains(result.XML, "第四层") {
|
||||
t.Fatalf("nested list converted incorrectly: %s", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fenced mermaid", func(t *testing.T) {
|
||||
result, err := Parse("```mermaid\nflowchart LR\nA-->B\n```", FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<whiteboard type="mermaid">flowchart LR<br/>A-->B</whiteboard>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("raw whiteboard source", func(t *testing.T) {
|
||||
source := "<whiteboard type=\"mermaid\">\nflowchart LR\n A --> B\n</whiteboard>"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<whiteboard type="mermaid">flowchart LR<br/> A --> B</whiteboard>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("raw code stays literal", func(t *testing.T) {
|
||||
source := "<code lang=\"go\">\nif a < b && c > d {\n fmt.Println(\"**raw**\")\n}\n</code>"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<code lang="go">if a < b && c > d {<br/> fmt.Println("**raw**")<br/>}</code>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("underscore tags", func(t *testing.T) {
|
||||
result, err := Parse(`text <synced_reference src-block-id="abc" src-token="def"/> more`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(result.XML, `<synced_reference`) || strings.Contains(result.XML, `<synced_reference`) {
|
||||
t.Fatalf("underscore tag was not preserved: %s", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("canonical user cite", func(t *testing.T) {
|
||||
result, err := Parse(`hello <cite type="user" user-id="ou_user"></cite>`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, want := range []string{`<cite`, `type="user"`, `user-id="ou_user"`} {
|
||||
if !strings.Contains(result.XML, want) {
|
||||
t.Errorf("XML missing %q: %s", want, result.XML)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("public tag alias converts to canonical XML", func(t *testing.T) {
|
||||
result, err := Parse(`hello <strong>world</strong>`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<p>hello <b>world</b></p>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("public cite alias converts attributes", func(t *testing.T) {
|
||||
result, err := Parse(`hello <at id="ou_legacy"></at>`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<p>hello <cite type="user" user-id="ou_legacy"></cite></p>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("markdown backslash escapes", func(t *testing.T) {
|
||||
result, err := Parse(`"source\_token": \[abc\] path\\to`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, want := range []string{`source_token`, `[abc]`, `path\to`} {
|
||||
if !strings.Contains(result.XML, want) {
|
||||
t.Errorf("XML missing %q: %s", want, result.XML)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("adjacent CJK emphasis", func(t *testing.T) {
|
||||
source := `***你好。***S 和 ~~再见。~~T。**agent team 做 brownfield 项目,带来的感知会强烈得多**——前提。**这个时刻,才是真正属于 agent team 的"闪光时刻"。**翟霖`
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`<em><b>你好。</b></em>S`,
|
||||
`<del>再见。</del>T`,
|
||||
`<b>agent team 做 brownfield 项目,带来的感知会强烈得多</b>`,
|
||||
`<b>这个时刻,才是真正属于 agent team 的"闪光时刻"。</b>翟霖`,
|
||||
} {
|
||||
if !strings.Contains(result.XML, want) {
|
||||
t.Errorf("XML missing %q: %s", want, result.XML)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("div parses markdown children", func(t *testing.T) {
|
||||
result, err := Parse("<div>\n\n**bold**\n\n</div>", FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<div><p><b>bold</b></p></div>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPreprocessCJKAdjacentMarkupUsesRuneOffsetsAfterRawBlock(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
lineEnding string
|
||||
final string
|
||||
}{
|
||||
{name: "EOF", lineEnding: "\n"},
|
||||
{name: "LF", lineEnding: "\n", final: "\n"},
|
||||
{name: "CRLF", lineEnding: "\r\n", final: "\r\n"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
source := "<code>**raw**" + tt.lineEnding + "Ⱥ</code>**你好。**S" + tt.final
|
||||
want := "<code>**raw**" + tt.lineEnding + "Ⱥ</code><b>你好。</b>S" + tt.final
|
||||
if got := preprocessCJKAdjacentMarkup(source); got != want {
|
||||
t.Fatalf("preprocessCJKAdjacentMarkup() = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextProfileMatchesLarkOpenCLIContract(t *testing.T) {
|
||||
result, err := Parse(`<title>标题</title><p>一个苹果是 an apple。</p>`, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
profile := result.Profile
|
||||
if profile.WordCount != 10 || profile.CharCount != 15 {
|
||||
t.Fatalf("profile = %+v, want word_count=10 char_count=15", profile)
|
||||
}
|
||||
if profile.Breakdown.HanChars != 7 || profile.Breakdown.EnglishWords != 2 || profile.Breakdown.ChinesePunctuations != 1 {
|
||||
t.Fatalf("breakdown = %+v", profile.Breakdown)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextProfileMatchesAuthoringCounterCases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
words int
|
||||
chars int
|
||||
blocks int
|
||||
english int
|
||||
numbers int
|
||||
han int
|
||||
listItems int
|
||||
}{
|
||||
{
|
||||
name: "english number and punctuation",
|
||||
source: `<p>Hello world 123.45。</p>`,
|
||||
words: 4, chars: 17, blocks: 1, english: 2, numbers: 1,
|
||||
},
|
||||
{
|
||||
name: "list and checkbox markers",
|
||||
source: `<ul><li>甲</li><li>two</li></ul><checkbox done="true">完成</checkbox>`,
|
||||
words: 7, chars: 9, blocks: 4, english: 1, han: 3, listItems: 2,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := Parse(tt.source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
profile := result.Profile
|
||||
if profile.WordCount != tt.words || profile.CharCount != tt.chars || profile.BlockCount != tt.blocks {
|
||||
t.Fatalf("profile = %+v, want words=%d chars=%d blocks=%d", profile, tt.words, tt.chars, tt.blocks)
|
||||
}
|
||||
if profile.Breakdown.EnglishWords != tt.english || profile.Breakdown.NumberWords != tt.numbers || profile.Breakdown.HanChars != tt.han {
|
||||
t.Fatalf("breakdown = %+v", profile.Breakdown)
|
||||
}
|
||||
if got := blockCountForTest(profile.Blocks, "li"); got != tt.listItems {
|
||||
t.Fatalf("li count = %d, want %d", got, tt.listItems)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextProfileUsesVisibleAttributeFallbacks(t *testing.T) {
|
||||
result, err := Parse(`<p text="Hello"/><p><span title="world"/></p><img href="https://example.com/image.png" caption="图"/>`, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
profile := result.Profile
|
||||
if profile.WordCount != 3 || profile.CharCount != 11 {
|
||||
t.Fatalf("profile = %+v, want word_count=3 char_count=11", profile)
|
||||
}
|
||||
if profile.Breakdown.EnglishWords != 2 || profile.Breakdown.HanChars != 1 {
|
||||
t.Fatalf("breakdown = %+v", profile.Breakdown)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsUnsafeXMLDeclarations(t *testing.T) {
|
||||
_, err := Parse(`<!DOCTYPE foo [<!ENTITY x "value">]><p>&x;</p>`, FormatXML)
|
||||
if err == nil || !strings.Contains(err.Error(), "DOCTYPE or ENTITY") {
|
||||
t.Fatalf("Parse() error = %v, want unsafe declaration rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsInvalidUTF8(t *testing.T) {
|
||||
_, err := Parse(string([]byte{'<', 'p', '>', 0xff, '<', '/', 'p', '>'}), FormatXML)
|
||||
if err == nil || !strings.Contains(err.Error(), "valid UTF-8") {
|
||||
t.Fatalf("Parse() error = %v, want UTF-8 rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsExcessiveNesting(t *testing.T) {
|
||||
source := strings.Repeat("<span>", MaxNestingDepth+1)
|
||||
_, err := Parse(source, FormatXML)
|
||||
if err == nil || !strings.Contains(err.Error(), "nesting exceeds") {
|
||||
t.Fatalf("Parse() error = %v, want nesting limit rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLRejectsNestedInvalidTagStarts(t *testing.T) {
|
||||
if _, err := Parse(`<<<<p>text</p>`, FormatXML); err == nil {
|
||||
t.Fatal("Parse() succeeded, want invalid XML token error")
|
||||
}
|
||||
}
|
||||
|
||||
func blockCountForTest(blocks []BlockShare, typ string) int {
|
||||
for _, block := range blocks {
|
||||
if block.Type == typ {
|
||||
return block.Count
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
397
shortcuts/doc/internal/docxparse/profile.go
Normal file
397
shortcuts/doc/internal/docxparse/profile.go
Normal file
@@ -0,0 +1,397 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Profile describes LarkOpenCLI document structure and visible text without
|
||||
// requiring callers to inspect the full XML.
|
||||
type Profile struct {
|
||||
WordCount int `json:"word_count"`
|
||||
CharCount int `json:"char_count"`
|
||||
Breakdown TextBreakdown `json:"breakdown"`
|
||||
BlockCount int `json:"block_count"`
|
||||
Blocks []BlockShare `json:"blocks"`
|
||||
}
|
||||
|
||||
// BlockShare reports one LarkOpenCLI block type's count and share. Structural
|
||||
// and inline-only tags are intentionally excluded.
|
||||
type BlockShare struct {
|
||||
Type string `json:"type"`
|
||||
Count int `json:"count"`
|
||||
Ratio float64 `json:"ratio"`
|
||||
}
|
||||
|
||||
// TextProfile is the internal result of the LarkOpenCLI semantic counter.
|
||||
type TextProfile struct {
|
||||
WordCount int `json:"word_count"`
|
||||
CharCount int `json:"char_count"`
|
||||
Breakdown TextBreakdown `json:"breakdown"`
|
||||
}
|
||||
|
||||
type TextBreakdown struct {
|
||||
HanChars int `json:"han_chars"`
|
||||
EnglishWords int `json:"english_words"`
|
||||
NumberWords int `json:"number_words"`
|
||||
ChinesePunctuations int `json:"chinese_punctuations"`
|
||||
EnglishLetters int `json:"english_letters"`
|
||||
Digits int `json:"digits"`
|
||||
EnglishPunctuations int `json:"english_punctuations"`
|
||||
SymbolWords int `json:"symbol_words"`
|
||||
SymbolChars int `json:"symbol_chars"`
|
||||
}
|
||||
|
||||
// Parse validates XML or converts Markdown to DocxXML, then builds its
|
||||
// structure and visible-text profile.
|
||||
func Parse(source string, format Format) (ParseResult, error) {
|
||||
var (
|
||||
nodes []*Node
|
||||
outputXML string
|
||||
err error
|
||||
)
|
||||
switch format {
|
||||
case FormatXML:
|
||||
nodes, err = parseXML(source)
|
||||
outputXML = source
|
||||
case FormatMarkdown:
|
||||
nodes, err = parseMarkdown(source)
|
||||
default:
|
||||
return ParseResult{}, fmt.Errorf("unsupported input format %q", format)
|
||||
}
|
||||
if err != nil {
|
||||
return ParseResult{}, err
|
||||
}
|
||||
if err := validateStructure(nodes); err != nil {
|
||||
return ParseResult{}, err
|
||||
}
|
||||
if format == FormatMarkdown {
|
||||
outputXML = renderNodes(nodes)
|
||||
}
|
||||
|
||||
return ParseResult{
|
||||
Format: format,
|
||||
XML: outputXML,
|
||||
Profile: buildProfile(nodes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ParseAuto detects XML versus Markdown from the content and returns only the
|
||||
// document profile. XML-like input is parsed strictly; all other input is
|
||||
// interpreted as Markdown.
|
||||
func ParseAuto(source string) (Profile, error) {
|
||||
result, err := Parse(source, detectFormat(source))
|
||||
if err != nil {
|
||||
return Profile{}, err
|
||||
}
|
||||
return result.Profile, nil
|
||||
}
|
||||
|
||||
// MarkdownToXML converts Markdown to canonical LarkOpenCLI XML.
|
||||
func MarkdownToXML(source string) (string, error) {
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return result.XML, nil
|
||||
}
|
||||
|
||||
func detectFormat(source string) Format {
|
||||
trimmed := strings.TrimSpace(strings.TrimPrefix(source, "\uFEFF"))
|
||||
if strings.HasPrefix(trimmed, "<") {
|
||||
return FormatXML
|
||||
}
|
||||
return FormatMarkdown
|
||||
}
|
||||
|
||||
func validateStructure(nodes []*Node) error {
|
||||
type frame struct {
|
||||
node *Node
|
||||
exit bool
|
||||
}
|
||||
frames := make([]frame, 0, len(nodes))
|
||||
for i := len(nodes) - 1; i >= 0; i-- {
|
||||
frames = append(frames, frame{node: nodes[i]})
|
||||
}
|
||||
ancestors := map[string]int{}
|
||||
depth := 0
|
||||
for len(frames) > 0 {
|
||||
current := frames[len(frames)-1]
|
||||
frames = frames[:len(frames)-1]
|
||||
node := current.node
|
||||
if node == nil || node.typ != nodeElement {
|
||||
continue
|
||||
}
|
||||
if current.exit {
|
||||
ancestors[node.tag]--
|
||||
depth--
|
||||
continue
|
||||
}
|
||||
if depth >= MaxNestingDepth {
|
||||
return fmt.Errorf("document nesting exceeds limit %d at <%s>", MaxNestingDepth, node.tag)
|
||||
}
|
||||
if err := validateRequiredAttributes(node); err != nil {
|
||||
return err
|
||||
}
|
||||
if required := requiredAncestorTags[node.tag]; len(required) > 0 {
|
||||
matched := false
|
||||
for tag := range required {
|
||||
if ancestors[tag] > 0 {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
allowed := make([]string, 0, len(required))
|
||||
for tag := range required {
|
||||
allowed = append(allowed, tag)
|
||||
}
|
||||
sort.Strings(allowed)
|
||||
return fmt.Errorf("LarkOpenCLI tag <%s> requires an ancestor in [%s]", node.tag, strings.Join(allowed, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
ancestors[node.tag]++
|
||||
depth++
|
||||
frames = append(frames, frame{node: node, exit: true})
|
||||
for i := len(node.children) - 1; i >= 0; i-- {
|
||||
frames = append(frames, frame{node: node.children[i]})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRequiredAttributes(node *Node) error {
|
||||
for _, attr := range requiredAttributes[node.tag] {
|
||||
if strings.TrimSpace(node.attrs[attr]) == "" {
|
||||
return fmt.Errorf("LarkOpenCLI tag <%s> requires attribute %q", node.tag, attr)
|
||||
}
|
||||
}
|
||||
for _, alternatives := range requiredAnyAttributes[node.tag] {
|
||||
matched := false
|
||||
for _, attr := range alternatives {
|
||||
if strings.TrimSpace(node.attrs[attr]) != "" {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return fmt.Errorf("LarkOpenCLI tag <%s> requires one of attributes [%s]", node.tag, strings.Join(alternatives, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildProfile(nodes []*Node) Profile {
|
||||
counts := map[string]int{}
|
||||
total := 0
|
||||
var walk func(*Node)
|
||||
walk = func(node *Node) {
|
||||
if node == nil || node.typ != nodeElement {
|
||||
return
|
||||
}
|
||||
layout := layoutOf(node.tag)
|
||||
isBlock := layout == layoutBlock || layout == layoutDual && node.parent == nil
|
||||
if isBlock {
|
||||
counts[node.tag]++
|
||||
total++
|
||||
}
|
||||
for _, child := range node.children {
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
for _, node := range nodes {
|
||||
walk(node)
|
||||
}
|
||||
|
||||
distribution := make([]BlockShare, 0, len(counts))
|
||||
for typ, count := range counts {
|
||||
ratio := 0.0
|
||||
if total > 0 {
|
||||
ratio = math.Round(float64(count)/float64(total)*1_000_000) / 1_000_000
|
||||
}
|
||||
distribution = append(distribution, BlockShare{Type: typ, Count: count, Ratio: ratio})
|
||||
}
|
||||
sort.Slice(distribution, func(i, j int) bool {
|
||||
if distribution[i].Count != distribution[j].Count {
|
||||
return distribution[i].Count > distribution[j].Count
|
||||
}
|
||||
return distribution[i].Type < distribution[j].Type
|
||||
})
|
||||
segments := extractSegments(nodes)
|
||||
stats := newTextCounter().countSegments(segments)
|
||||
return Profile{
|
||||
WordCount: stats.WordCount,
|
||||
CharCount: stats.CharCount,
|
||||
Breakdown: stats.Breakdown,
|
||||
BlockCount: total,
|
||||
Blocks: distribution,
|
||||
}
|
||||
}
|
||||
|
||||
type segmentKind uint8
|
||||
|
||||
const (
|
||||
segmentText segmentKind = iota
|
||||
segmentMarker
|
||||
segmentCode
|
||||
)
|
||||
|
||||
type textSegment struct {
|
||||
text string
|
||||
kind segmentKind
|
||||
}
|
||||
|
||||
var ignoredResourceTags = map[string]bool{
|
||||
"whiteboard": true, "sheet": true, "source": true, "chat_card": true,
|
||||
"base_refer": true, "bitable": true, "synced_reference": true,
|
||||
"poll": true, "isv": true, "mindnote": true, "sub-page-list": true,
|
||||
"okr": true, "html5-block": true,
|
||||
}
|
||||
|
||||
var ignoredInlineTags = map[string]bool{
|
||||
"button": true, "cite": true, "latex": true, "bookmark": true,
|
||||
}
|
||||
|
||||
func extractSegments(nodes []*Node) []textSegment {
|
||||
var segments []textSegment
|
||||
for _, node := range nodes {
|
||||
extractNodeSegments(node, &segments)
|
||||
}
|
||||
return segments
|
||||
}
|
||||
|
||||
func extractNodeSegments(node *Node, segments *[]textSegment) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
if node.typ == nodeText {
|
||||
if strings.TrimSpace(node.text) != "" {
|
||||
*segments = append(*segments, textSegment{text: node.text})
|
||||
}
|
||||
return
|
||||
}
|
||||
if ignoredInlineTags[node.tag] || ignoredResourceTags[node.tag] {
|
||||
return
|
||||
}
|
||||
if node.tag == "task" {
|
||||
return
|
||||
}
|
||||
if node.tag == "synced-source" && len(node.children) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
switch node.tag {
|
||||
case "ul", "ol":
|
||||
sequence := 1
|
||||
for _, child := range node.children {
|
||||
if child.typ == nodeElement && child.tag == "li" {
|
||||
if node.tag == "ul" {
|
||||
*segments = append(*segments, textSegment{text: "•", kind: segmentMarker})
|
||||
} else {
|
||||
marker := sequence
|
||||
if raw := child.attrs["seq"]; raw != "" {
|
||||
if _, err := fmt.Sscanf(raw, "%d", &marker); err == nil {
|
||||
sequence = marker
|
||||
}
|
||||
}
|
||||
*segments = append(*segments, textSegment{text: fmt.Sprintf("%d.", marker)})
|
||||
sequence++
|
||||
}
|
||||
}
|
||||
extractNodeSegments(child, segments)
|
||||
}
|
||||
return
|
||||
case "checkbox":
|
||||
marker := "☐"
|
||||
if node.attrs["done"] == "true" {
|
||||
marker = "☑"
|
||||
}
|
||||
*segments = append(*segments, textSegment{text: marker, kind: segmentMarker})
|
||||
}
|
||||
|
||||
kind := segmentText
|
||||
if node.tag == "pre" || node.tag == "code" && (node.parent == nil || node.parent.tag != "p") {
|
||||
kind = segmentCode
|
||||
}
|
||||
text := visibleInlineText(node)
|
||||
if strings.TrimSpace(text) == "" && !hasBlockChildren(node) {
|
||||
if node.tag == "img" {
|
||||
text = node.attrs["caption"]
|
||||
} else {
|
||||
text = firstNonEmpty(node.attrs["text"], node.attrs["name"], node.attrs["title"], node.attrs["alt"], node.attrs["caption"])
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(text) != "" {
|
||||
*segments = append(*segments, textSegment{text: text, kind: kind})
|
||||
}
|
||||
|
||||
for _, child := range node.children {
|
||||
if child.typ != nodeElement || isInlineForExtraction(child.tag) {
|
||||
continue
|
||||
}
|
||||
extractNodeSegments(child, segments)
|
||||
}
|
||||
}
|
||||
|
||||
func visibleInlineText(node *Node) string {
|
||||
var out strings.Builder
|
||||
var walk func(*Node)
|
||||
walk = func(current *Node) {
|
||||
if current.typ == nodeText {
|
||||
out.WriteString(current.text)
|
||||
return
|
||||
}
|
||||
if current != node && !isInlineForExtraction(current.tag) {
|
||||
return
|
||||
}
|
||||
if ignoredInlineTags[current.tag] {
|
||||
return
|
||||
}
|
||||
if current.tag == "br" {
|
||||
out.WriteByte('\n')
|
||||
return
|
||||
}
|
||||
if current != node {
|
||||
if display := firstNonEmpty(current.attrs["text"], current.attrs["name"], current.attrs["title"], current.attrs["alt"]); display != "" {
|
||||
out.WriteString(display)
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, child := range current.children {
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
for _, child := range node.children {
|
||||
walk(child)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func hasBlockChildren(node *Node) bool {
|
||||
for _, child := range node.children {
|
||||
if child.typ == nodeElement && !isInlineForExtraction(child.tag) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isInlineForExtraction(tag string) bool {
|
||||
layout := layoutOf(tag)
|
||||
return layout == layoutInline || layout == layoutDual
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
268
shortcuts/doc/internal/docxparse/schema.go
Normal file
268
shortcuts/doc/internal/docxparse/schema.go
Normal file
@@ -0,0 +1,268 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type tagLayout string
|
||||
|
||||
const (
|
||||
layoutBlock tagLayout = "block"
|
||||
layoutInline tagLayout = "inline"
|
||||
layoutDual tagLayout = "dual"
|
||||
layoutStructural tagLayout = "structural"
|
||||
layoutCommand tagLayout = "command"
|
||||
)
|
||||
|
||||
type tagSpec struct {
|
||||
canonical string
|
||||
layout tagLayout
|
||||
}
|
||||
|
||||
var tagSpecs = map[string]tagSpec{}
|
||||
|
||||
// tagAliases mirrors the public compatibility aliases declared by the
|
||||
// LarkOpenCLI SDK. Parsing keeps the caller's XML unchanged; aliases are only
|
||||
// canonicalized in the in-memory tree used for profiling and Markdown output.
|
||||
var tagAliases = map[string]string{
|
||||
"strong": "b",
|
||||
"text": "span",
|
||||
"equation": "latex",
|
||||
"lark-table": "table",
|
||||
"lark-tr": "tr",
|
||||
"lark-td": "td",
|
||||
"image": "img",
|
||||
"reference-synced": "synced_reference",
|
||||
"source-synced": "synced-source",
|
||||
"at": "cite",
|
||||
"chat-card": "chat_card",
|
||||
"folder_manager": "folder-manager",
|
||||
}
|
||||
|
||||
type attributeAliasRule struct {
|
||||
canonical string
|
||||
transform func(string) (string, bool)
|
||||
}
|
||||
|
||||
var commonAttributeAliases = map[string]attributeAliasRule{
|
||||
"color": {canonical: "text-color"},
|
||||
"textcolor": {canonical: "text-color"},
|
||||
"text_color": {canonical: "text-color"},
|
||||
"bgcolor": {canonical: "background-color"},
|
||||
"background_color": {canonical: "background-color"},
|
||||
}
|
||||
|
||||
var tagAttributeAliases = map[string]map[string]attributeAliasRule{
|
||||
"img": {
|
||||
"url": {canonical: "href"},
|
||||
"file_key": {canonical: "img_key"},
|
||||
},
|
||||
"callout": {
|
||||
"color": {canonical: "background-color"},
|
||||
"icon": {canonical: "emoji"},
|
||||
},
|
||||
"column": {
|
||||
"width": {canonical: "width-ratio", transform: normalizeWidthRatio},
|
||||
},
|
||||
"chat_card": {
|
||||
"id": {canonical: "chat-id", transform: requireChatID},
|
||||
},
|
||||
"cite": {
|
||||
"user_id": {canonical: "user-id"},
|
||||
},
|
||||
}
|
||||
|
||||
var rawTagAttributeAliases = map[string]map[string]attributeAliasRule{
|
||||
"at": {
|
||||
"id": {canonical: "user-id"},
|
||||
"user_id": {canonical: "user-id"},
|
||||
},
|
||||
}
|
||||
|
||||
var requiredAttributes = map[string][]string{
|
||||
"task": {"task-id"},
|
||||
}
|
||||
|
||||
var requiredAnyAttributes = map[string][][]string{
|
||||
"img": {{"src", "img_key", "href"}},
|
||||
"whiteboard": {{"token", "type"}},
|
||||
"chat_card": {{"token", "chat-id"}},
|
||||
"bookmark": {{"href", "name"}},
|
||||
}
|
||||
|
||||
func init() {
|
||||
registerTags(layoutBlock,
|
||||
"title", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "p",
|
||||
"div", "ul", "ol", "li", "blockquote", "grid", "column", "table", "thead",
|
||||
"tbody", "tfoot", "tr", "hr", "pre", "img", "source", "bitable", "sheet",
|
||||
"mindnote", "whiteboard", "base_refer", "synced_reference", "isv", "html5-block",
|
||||
"view", "synced-source", "readonly-block", "figure", "callout", "checkbox",
|
||||
"chat_card", "okr", "okr-objective", "okr-key-result", "okr-progress", "poll",
|
||||
"agenda", "folder-manager", "sub-page-list", "wiki_catalog", "wiki_recent_update",
|
||||
"chart-embedded", "chart-refer-host-perm", "chart_embedded", "chart_refer_host_perm",
|
||||
"bookmark", "task", "vc-tabs", "vc-summary-tab", "vc-transcribe-tab", "append",
|
||||
)
|
||||
registerTags(layoutInline, "b", "em", "u", "del", "i", "span", "br", "inline-file", "mention-date", "cite", "button", "time", "a")
|
||||
registerTags(layoutDual, "latex", "code")
|
||||
registerTags(layoutStructural, "th", "td", "colgroup", "col", "sub-page")
|
||||
registerTags(layoutCommand,
|
||||
"comment", "block_delete", "str_delete", "str_replace", "block_replace", "block_insert",
|
||||
"block_move", "block_copy_insert_after", "src_block_ids", "create", "answer", "response",
|
||||
"identifier", "genre", "anchor", "type", "revision", "pattern", "replacement",
|
||||
"replace_content", "action", "content", "parameter", "generation", "block_id",
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
func registerTags(layout tagLayout, tags ...string) {
|
||||
for _, tag := range tags {
|
||||
tagSpecs[tag] = tagSpec{canonical: tag, layout: layout}
|
||||
}
|
||||
}
|
||||
|
||||
func lookupTag(raw string) (tagSpec, bool) {
|
||||
key := strings.ToLower(strings.TrimSpace(raw))
|
||||
if canonical, ok := tagAliases[key]; ok {
|
||||
key = canonical
|
||||
}
|
||||
spec, ok := tagSpecs[key]
|
||||
if !ok {
|
||||
return tagSpec{}, false
|
||||
}
|
||||
return spec, true
|
||||
}
|
||||
|
||||
func layoutOf(tag string) tagLayout {
|
||||
spec, ok := lookupTag(tag)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return spec.layout
|
||||
}
|
||||
|
||||
var voidTags = map[string]bool{
|
||||
"br": true,
|
||||
"col": true,
|
||||
"hr": true,
|
||||
"img": true,
|
||||
"source": true,
|
||||
"sub-page": true,
|
||||
}
|
||||
|
||||
func isVoidTag(tag string) bool { return voidTags[tag] }
|
||||
|
||||
var preserveSpaceTags = map[string]bool{
|
||||
"title": true, "h1": true, "h2": true, "h3": true, "h4": true,
|
||||
"h5": true, "h6": true, "h7": true, "h8": true, "h9": true,
|
||||
"p": true, "i": true, "b": true, "em": true, "u": true, "del": true,
|
||||
"code": true, "li": true, "a": true, "span": true,
|
||||
}
|
||||
|
||||
var strictPhrasingTags = map[string]bool{
|
||||
"title": true, "span": true, "b": true, "em": true,
|
||||
"u": true, "del": true, "a": true,
|
||||
}
|
||||
|
||||
var autoCloseTags = map[string]map[string]bool{
|
||||
"li": {"li": true},
|
||||
"tr": {"tr": true},
|
||||
"td": {"td": true, "th": true, "tr": true, "tbody": true, "tfoot": true},
|
||||
"th": {"th": true, "td": true, "tr": true, "tbody": true, "tfoot": true},
|
||||
"tbody": {"tbody": true, "tfoot": true},
|
||||
"thead": {"tbody": true, "tfoot": true},
|
||||
"column": {"column": true},
|
||||
}
|
||||
|
||||
var requiredAncestorTags = map[string]map[string]bool{
|
||||
"column": {"grid": true},
|
||||
"thead": {"table": true},
|
||||
"tbody": {"table": true},
|
||||
"tfoot": {"table": true},
|
||||
"tr": {"table": true, "thead": true, "tbody": true, "tfoot": true},
|
||||
"th": {"tr": true},
|
||||
"td": {"tr": true},
|
||||
"colgroup": {"table": true},
|
||||
"col": {"table": true, "colgroup": true},
|
||||
"okr-objective": {"okr": true},
|
||||
"okr-key-result": {"okr": true, "okr-objective": true},
|
||||
"okr-progress": {"okr-objective": true, "okr-key-result": true},
|
||||
"sub-page": {"sub-page-list": true},
|
||||
}
|
||||
|
||||
func shouldAutoClose(openTag, nextTag string) bool {
|
||||
if strictPhrasingTags[openTag] && layoutOf(nextTag) == layoutBlock {
|
||||
return true
|
||||
}
|
||||
return autoCloseTags[openTag] != nil && autoCloseTags[openTag][nextTag]
|
||||
}
|
||||
|
||||
func normalizeAttributes(rawTag, canonical string, attrs map[string]string) map[string]string {
|
||||
rules := make(map[string]attributeAliasRule, len(commonAttributeAliases)+4)
|
||||
for alias, rule := range commonAttributeAliases {
|
||||
rules[alias] = rule
|
||||
}
|
||||
for alias, rule := range tagAttributeAliases[canonical] {
|
||||
rules[alias] = rule
|
||||
}
|
||||
rawKey := strings.ToLower(strings.TrimSpace(rawTag))
|
||||
for alias, rule := range rawTagAttributeAliases[rawKey] {
|
||||
rules[alias] = rule
|
||||
}
|
||||
|
||||
aliases := make([]string, 0, len(rules))
|
||||
for alias := range rules {
|
||||
aliases = append(aliases, alias)
|
||||
}
|
||||
sort.Strings(aliases)
|
||||
for _, alias := range aliases {
|
||||
value, exists := attrs[alias]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
rule := rules[alias]
|
||||
if rule.transform != nil {
|
||||
var ok bool
|
||||
value, ok = rule.transform(value)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if canonicalValue, exists := attrs[rule.canonical]; !exists || strings.TrimSpace(canonicalValue) == "" {
|
||||
if attrs == nil {
|
||||
attrs = map[string]string{}
|
||||
}
|
||||
attrs[rule.canonical] = value
|
||||
}
|
||||
delete(attrs, alias)
|
||||
}
|
||||
|
||||
if rawKey == "at" {
|
||||
if attrs == nil {
|
||||
attrs = map[string]string{}
|
||||
}
|
||||
attrs["type"] = "user"
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
func normalizeWidthRatio(value string) (string, bool) {
|
||||
trimmed := strings.TrimSuffix(strings.TrimSpace(value), "%")
|
||||
if trimmed == "" {
|
||||
return value, false
|
||||
}
|
||||
width, err := strconv.ParseFloat(trimmed, 64)
|
||||
if err != nil {
|
||||
return value, false
|
||||
}
|
||||
return strconv.FormatFloat(width/100, 'f', 6, 64), true
|
||||
}
|
||||
|
||||
func requireChatID(value string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
return trimmed, strings.HasPrefix(trimmed, "oc_")
|
||||
}
|
||||
342
shortcuts/doc/internal/docxparse/wordcount.go
Normal file
342
shortcuts/doc/internal/docxparse/wordcount.go
Normal file
@@ -0,0 +1,342 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
// This file implements the LarkOpenCLI document text-counting contract.
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/width"
|
||||
)
|
||||
|
||||
const chinesePunctuation = ",。!?;:、()《》〈〉“”‘’【】「」『』〔〕…—~·¥"
|
||||
const englishPunctuation = `!"#$%&'()*+,-./:;<=>?@[\]^_` + "`" + `{|}~`
|
||||
|
||||
var (
|
||||
urlToken = regexp.MustCompile(`^https?://[!-~]+`)
|
||||
asciiCompoundToken = regexp.MustCompile(`^[A-Za-z0-9]+(?:[._/@:-][A-Za-z0-9]+)+`)
|
||||
)
|
||||
|
||||
type lexemeKind uint8
|
||||
|
||||
const (
|
||||
lexemeNone lexemeKind = iota
|
||||
lexemeEnglish
|
||||
lexemeNumber
|
||||
)
|
||||
|
||||
type textCounter struct {
|
||||
stats TextProfile
|
||||
lexeme lexemeKind
|
||||
lexemeHasDigit bool
|
||||
symbolRunLength int
|
||||
atBoundary bool
|
||||
}
|
||||
|
||||
func newTextCounter() *textCounter {
|
||||
return &textCounter{atBoundary: true}
|
||||
}
|
||||
|
||||
func (c *textCounter) countSegments(segments []textSegment) TextProfile {
|
||||
for _, segment := range segments {
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
switch segment.kind {
|
||||
case segmentMarker:
|
||||
c.writeMarker(segment.text)
|
||||
case segmentCode:
|
||||
c.writeCode(segment.text)
|
||||
default:
|
||||
c.write(segment.text)
|
||||
}
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
}
|
||||
c.endUnit()
|
||||
return c.stats
|
||||
}
|
||||
|
||||
func (c *textCounter) write(value string) {
|
||||
for offset := 0; offset < len(value); {
|
||||
if token := matchASCIICompound(value[offset:]); token != "" {
|
||||
c.writeASCIICompound(token)
|
||||
offset += len(token)
|
||||
continue
|
||||
}
|
||||
r, size := utf8.DecodeRuneInString(value[offset:])
|
||||
if r == '/' && isVisibleHanSeparator(value, offset, size) {
|
||||
c.endUnit()
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.Breakdown.SymbolWords++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
offset += size
|
||||
continue
|
||||
}
|
||||
c.writeRune(r)
|
||||
offset += size
|
||||
}
|
||||
}
|
||||
|
||||
func (c *textCounter) writeMarker(value string) {
|
||||
for _, r := range value {
|
||||
if unicode.IsSpace(r) {
|
||||
continue
|
||||
}
|
||||
c.endUnit()
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *textCounter) writeCode(value string) {
|
||||
for _, r := range value {
|
||||
c.writeCodeRune(r)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *textCounter) writeCodeRune(r rune) {
|
||||
if unicode.IsSpace(r) {
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.HanChars++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIILetterRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.EnglishLetters++
|
||||
c.stats.CharCount++
|
||||
if c.lexeme == lexemeNone || c.lexeme == lexemeNumber {
|
||||
c.lexeme = lexemeEnglish
|
||||
}
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIIDigitRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.Digits++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isChinesePunctuation(r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.ChinesePunctuations++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isEnglishPunctuation(r) {
|
||||
keepsLexeme := c.lexeme == lexemeEnglish && (r == '\'' || r == '-')
|
||||
if !keepsLexeme {
|
||||
hadLexeme := c.lexeme != lexemeNone
|
||||
c.endLexeme()
|
||||
if !hadLexeme && (c.symbolRunLength > 0 || c.atBoundary) {
|
||||
c.symbolRunLength++
|
||||
}
|
||||
}
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.CharCount++
|
||||
if keepsLexeme {
|
||||
c.atBoundary = false
|
||||
}
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Symbol, r) {
|
||||
c.writeSymbol(r)
|
||||
return
|
||||
}
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func (c *textCounter) writeRune(r rune) {
|
||||
if unicode.IsSpace(r) {
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.HanChars++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIILetterRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.EnglishLetters++
|
||||
c.stats.CharCount++
|
||||
if c.lexeme == lexemeNone || c.lexeme == lexemeNumber {
|
||||
c.lexeme = lexemeEnglish
|
||||
}
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIIDigitRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.Digits++
|
||||
c.stats.CharCount++
|
||||
c.lexemeHasDigit = true
|
||||
if c.lexeme == lexemeNone {
|
||||
c.lexeme = lexemeNumber
|
||||
}
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isChinesePunctuation(r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.ChinesePunctuations++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isEnglishPunctuation(r) {
|
||||
keepsLexeme := c.lexeme == lexemeEnglish && (r == '\'' || r == '-' || c.lexemeHasDigit && r == '.') ||
|
||||
c.lexeme == lexemeNumber && (r == '.' || r == ',' || r == '-')
|
||||
if !keepsLexeme {
|
||||
hadLexeme := c.lexeme != lexemeNone
|
||||
c.endLexeme()
|
||||
if !hadLexeme && (c.symbolRunLength > 0 || c.atBoundary) {
|
||||
c.symbolRunLength++
|
||||
}
|
||||
}
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.CharCount++
|
||||
if keepsLexeme {
|
||||
c.atBoundary = false
|
||||
}
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Symbol, r) {
|
||||
c.writeSymbol(r)
|
||||
return
|
||||
}
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func matchASCIICompound(value string) string {
|
||||
if match := urlToken.FindString(value); match != "" {
|
||||
return match
|
||||
}
|
||||
match := asciiCompoundToken.FindString(value)
|
||||
if match == "" || !strings.ContainsAny(match, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
|
||||
return ""
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
func (c *textCounter) writeASCIICompound(token string) {
|
||||
c.endUnit()
|
||||
c.stats.Breakdown.EnglishWords++
|
||||
c.stats.WordCount++
|
||||
for _, r := range token {
|
||||
switch {
|
||||
case isASCIILetterRune(r):
|
||||
c.stats.Breakdown.EnglishLetters++
|
||||
c.stats.CharCount++
|
||||
case isASCIIDigitRune(r):
|
||||
c.stats.Breakdown.Digits++
|
||||
c.stats.CharCount++
|
||||
case isEnglishPunctuation(r):
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.CharCount++
|
||||
}
|
||||
}
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func (c *textCounter) writeSymbol(r rune) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
units := utf16Units(r)
|
||||
c.stats.Breakdown.SymbolWords++
|
||||
c.stats.Breakdown.SymbolChars += units
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount += units
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func (c *textCounter) endUnit() {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(true)
|
||||
}
|
||||
|
||||
func (c *textCounter) endLexeme() {
|
||||
switch c.lexeme {
|
||||
case lexemeEnglish:
|
||||
c.stats.Breakdown.EnglishWords++
|
||||
c.stats.WordCount++
|
||||
case lexemeNumber:
|
||||
c.stats.Breakdown.NumberWords++
|
||||
c.stats.WordCount++
|
||||
}
|
||||
c.lexeme = lexemeNone
|
||||
c.lexemeHasDigit = false
|
||||
}
|
||||
|
||||
func (c *textCounter) endSymbolRun(countWord bool) {
|
||||
if c.symbolRunLength > 0 && countWord {
|
||||
c.stats.Breakdown.SymbolWords++
|
||||
c.stats.WordCount++
|
||||
}
|
||||
if c.symbolRunLength > 0 {
|
||||
c.atBoundary = false
|
||||
}
|
||||
c.symbolRunLength = 0
|
||||
}
|
||||
|
||||
func isVisibleHanSeparator(value string, offset, size int) bool {
|
||||
if offset == 0 || offset+size >= len(value) {
|
||||
return false
|
||||
}
|
||||
previous, _ := utf8.DecodeLastRuneInString(value[:offset])
|
||||
next, _ := utf8.DecodeRuneInString(value[offset+size:])
|
||||
return unicode.Is(unicode.Han, previous) && unicode.Is(unicode.Han, next)
|
||||
}
|
||||
|
||||
func isASCIILetterRune(r rune) bool { return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' }
|
||||
func isASCIIDigitRune(r rune) bool { return r >= '0' && r <= '9' }
|
||||
|
||||
func isChinesePunctuation(r rune) bool {
|
||||
if strings.ContainsRune(chinesePunctuation, r) {
|
||||
return true
|
||||
}
|
||||
kind := width.LookupRune(r).Kind()
|
||||
return unicode.Is(unicode.Punct, r) && (kind == width.EastAsianWide || kind == width.EastAsianFullwidth)
|
||||
}
|
||||
|
||||
func isEnglishPunctuation(r rune) bool {
|
||||
return r < utf8.RuneSelf && strings.ContainsRune(englishPunctuation, r)
|
||||
}
|
||||
|
||||
func utf16Units(r rune) int {
|
||||
if r > 0xffff {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
572
shortcuts/doc/internal/docxparse/xml.go
Normal file
572
shortcuts/doc/internal/docxparse/xml.go
Normal file
@@ -0,0 +1,572 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxInputBytes = 20_000_000
|
||||
MaxNestingDepth = 1024
|
||||
)
|
||||
|
||||
var forbiddenXMLDeclaration = regexp.MustCompile(`(?i)<!\s*(?:DOCTYPE|ENTITY)\b`)
|
||||
|
||||
func validateSource(source string) error {
|
||||
if len(source) > MaxInputBytes {
|
||||
return fmt.Errorf("input is too large (%d bytes, limit %d)", len(source), MaxInputBytes)
|
||||
}
|
||||
if forbiddenXMLDeclaration.MatchString(source) {
|
||||
return fmt.Errorf("XML input must not contain DOCTYPE or ENTITY declarations")
|
||||
}
|
||||
if !utf8.ValidString(source) {
|
||||
return fmt.Errorf("input must be valid UTF-8")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseXML(source string) ([]*Node, error) {
|
||||
if err := validateSource(source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source = strings.TrimPrefix(source, "\uFEFF")
|
||||
|
||||
root := newElement("__fragment__", nil)
|
||||
stack := []*Node{root}
|
||||
for i := 0; i < len(source); {
|
||||
lt := strings.IndexByte(source[i:], '<')
|
||||
if lt < 0 {
|
||||
if err := validateXMLText(source[i:], i); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
appendText(stack[len(stack)-1], source[i:])
|
||||
break
|
||||
}
|
||||
lt += i
|
||||
if err := validateXMLText(source[i:lt], i); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
appendText(stack[len(stack)-1], source[i:lt])
|
||||
|
||||
token, end, state := scanXMLToken(source, lt)
|
||||
switch state {
|
||||
case tokenComment, tokenProcessingInstruction:
|
||||
i = end
|
||||
continue
|
||||
case tokenCDATA:
|
||||
appendTextValue(stack[len(stack)-1], token.text)
|
||||
i = end
|
||||
continue
|
||||
case tokenInvalid:
|
||||
return nil, fmt.Errorf("invalid XML token at byte %d", lt)
|
||||
case tokenIncomplete:
|
||||
return nil, fmt.Errorf("unterminated XML tag at byte %d", lt)
|
||||
}
|
||||
|
||||
spec, allowed := lookupTag(token.name)
|
||||
if !allowed {
|
||||
return nil, fmt.Errorf("unsupported LarkOpenCLI tag <%s> at byte %d", token.name, lt)
|
||||
}
|
||||
canonical := spec.canonical
|
||||
if token.spacingNormalized {
|
||||
return nil, fmt.Errorf("invalid whitespace in XML tag <%s> at byte %d", token.name, lt)
|
||||
}
|
||||
|
||||
if token.closing {
|
||||
if isVoidTag(canonical) {
|
||||
return nil, fmt.Errorf("void tag <%s/> must not have a closing tag", canonical)
|
||||
}
|
||||
if len(stack) == 1 {
|
||||
return nil, fmt.Errorf("unexpected closing tag </%s> at byte %d", canonical, lt)
|
||||
}
|
||||
open := stack[len(stack)-1].tag
|
||||
if open != canonical {
|
||||
return nil, fmt.Errorf("mismatched closing tag </%s> at byte %d; expected </%s>", canonical, lt, open)
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
if len(stack) > 1 && shouldAutoClose(stack[len(stack)-1].tag, canonical) {
|
||||
return nil, fmt.Errorf("invalid <%s> inside <%s> at byte %d", canonical, stack[len(stack)-1].tag, lt)
|
||||
}
|
||||
attrs := normalizeAttributes(token.name, canonical, token.attrs)
|
||||
node := newElement(canonical, attrs)
|
||||
stack[len(stack)-1].addChild(node)
|
||||
if !token.selfClosing && !isVoidTag(canonical) {
|
||||
if len(stack) > MaxNestingDepth {
|
||||
return nil, fmt.Errorf("XML nesting exceeds limit %d at byte %d", MaxNestingDepth, lt)
|
||||
}
|
||||
stack = append(stack, node)
|
||||
}
|
||||
i = end
|
||||
}
|
||||
|
||||
if len(stack) > 1 {
|
||||
return nil, fmt.Errorf("missing closing tag </%s> at end of input", stack[len(stack)-1].tag)
|
||||
}
|
||||
normalizeParsedLineBreaks(root.children, false, false)
|
||||
for _, child := range root.children {
|
||||
child.parent = nil
|
||||
}
|
||||
return root.children, nil
|
||||
}
|
||||
|
||||
// normalizeParsedLineBreaks removes formatting newlines from ordinary XML,
|
||||
// while source-bearing code/whiteboard blocks keep semantic
|
||||
// line breaks as explicit <br/> nodes. str_replace pattern/replacement payloads
|
||||
// retain raw newlines because their string matching semantics depend on them.
|
||||
func normalizeParsedLineBreaks(nodes []*Node, sourceBlock, stringMutation bool) {
|
||||
for _, node := range nodes {
|
||||
if node == nil || node.typ != nodeElement {
|
||||
continue
|
||||
}
|
||||
nextSourceBlock := sourceBlock || node.tag == "code" || node.tag == "whiteboard"
|
||||
nextStringMutation := stringMutation || node.tag == "str_replace"
|
||||
preserveRaw := nextStringMutation && (node.tag == "pattern" || node.tag == "replacement")
|
||||
if node.tag == "code" || node.tag == "whiteboard" {
|
||||
trimSourceBlockBoundaryNewlines(node.children)
|
||||
}
|
||||
children := make([]*Node, 0, len(node.children))
|
||||
for _, child := range node.children {
|
||||
if child.typ != nodeText || !strings.ContainsAny(child.text, "\r\n") {
|
||||
children = append(children, child)
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case preserveRaw:
|
||||
children = append(children, child)
|
||||
case nextSourceBlock:
|
||||
for _, replacement := range rawTextWithBreakNodes(child.text) {
|
||||
replacement.parent = node
|
||||
children = append(children, replacement)
|
||||
}
|
||||
default:
|
||||
child.text = strings.NewReplacer("\r", "", "\n", "").Replace(child.text)
|
||||
if child.text != "" {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
}
|
||||
node.children = children
|
||||
normalizeParsedLineBreaks(node.children, nextSourceBlock, nextStringMutation)
|
||||
}
|
||||
}
|
||||
|
||||
func trimSourceBlockBoundaryNewlines(children []*Node) {
|
||||
for _, child := range children {
|
||||
if child.typ == nodeText {
|
||||
child.text = strings.TrimLeft(child.text, "\r\n")
|
||||
break
|
||||
}
|
||||
if child.typ == nodeElement {
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := len(children) - 1; i >= 0; i-- {
|
||||
child := children[i]
|
||||
if child.typ == nodeText {
|
||||
child.text = strings.TrimRight(child.text, "\r\n")
|
||||
break
|
||||
}
|
||||
if child.typ == nodeElement {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rawTextWithBreakNodes(content string) []*Node {
|
||||
if content == "" {
|
||||
return nil
|
||||
}
|
||||
var nodes []*Node
|
||||
start := 0
|
||||
for i := 0; i < len(content); i++ {
|
||||
if content[i] != '\n' && content[i] != '\r' {
|
||||
continue
|
||||
}
|
||||
if i > start {
|
||||
nodes = append(nodes, newText(content[start:i]))
|
||||
}
|
||||
if content[i] == '\r' && i+1 < len(content) && content[i+1] == '\n' {
|
||||
i++
|
||||
}
|
||||
nodes = append(nodes, newElement("br", nil))
|
||||
start = i + 1
|
||||
}
|
||||
if start < len(content) {
|
||||
nodes = append(nodes, newText(content[start:]))
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
type tokenState uint8
|
||||
|
||||
const (
|
||||
tokenOK tokenState = iota
|
||||
tokenInvalid
|
||||
tokenIncomplete
|
||||
tokenComment
|
||||
tokenProcessingInstruction
|
||||
tokenCDATA
|
||||
)
|
||||
|
||||
type xmlToken struct {
|
||||
name string
|
||||
attrs map[string]string
|
||||
text string
|
||||
closing bool
|
||||
selfClosing bool
|
||||
spacingNormalized bool
|
||||
}
|
||||
|
||||
func scanXMLToken(source string, start int) (xmlToken, int, tokenState) {
|
||||
if strings.HasPrefix(source[start:], "<![CDATA[") {
|
||||
const marker = "<![CDATA["
|
||||
contentStart := start + len(marker)
|
||||
if closeAt := strings.Index(source[contentStart:], "]]>"); closeAt >= 0 {
|
||||
contentEnd := contentStart + closeAt
|
||||
return xmlToken{text: source[contentStart:contentEnd]}, contentEnd + len("]]>"), tokenCDATA
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
if strings.HasPrefix(source[start:], "<!--") {
|
||||
if closeAt := strings.Index(source[start+4:], "-->"); closeAt >= 0 {
|
||||
if strings.Contains(source[start+4:start+4+closeAt], "--") {
|
||||
return xmlToken{}, start + 1, tokenInvalid
|
||||
}
|
||||
return xmlToken{}, start + 4 + closeAt + 3, tokenComment
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
if strings.HasPrefix(source[start:], "<?") {
|
||||
if closeAt := strings.Index(source[start+2:], "?>"); closeAt >= 0 {
|
||||
return xmlToken{}, start + 2 + closeAt + 2, tokenProcessingInstruction
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
|
||||
quote := byte(0)
|
||||
end := -1
|
||||
for i := start + 1; i < len(source); i++ {
|
||||
switch source[i] {
|
||||
case '\'', '"':
|
||||
if quote == 0 {
|
||||
quote = source[i]
|
||||
} else if quote == source[i] {
|
||||
quote = 0
|
||||
}
|
||||
case '>':
|
||||
if quote == 0 {
|
||||
end = i + 1
|
||||
i = len(source)
|
||||
}
|
||||
case '<':
|
||||
// A second unquoted '<' cannot belong to the current XML tag.
|
||||
// Stop here so a long sequence of invalid tag starts is scanned
|
||||
// once instead of repeatedly searching to a distant '>'.
|
||||
if quote == 0 {
|
||||
return xmlToken{}, start + 1, tokenInvalid
|
||||
}
|
||||
}
|
||||
}
|
||||
if end < 0 {
|
||||
candidate := strings.TrimSpace(source[start+1:])
|
||||
if candidate == "" || !isTagNameStart(candidate[0]) && candidate[0] != '/' {
|
||||
return xmlToken{}, start + 1, tokenInvalid
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
|
||||
body := source[start+1 : end-1]
|
||||
if body == "" {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
token := xmlToken{}
|
||||
position := 0
|
||||
for position < len(body) && isXMLSpace(body[position]) {
|
||||
position++
|
||||
}
|
||||
if position > 0 {
|
||||
token.spacingNormalized = true
|
||||
}
|
||||
if position >= len(body) || body[position] == '!' {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
if body[position] == '/' {
|
||||
token.closing = true
|
||||
position++
|
||||
spaceStart := position
|
||||
for position < len(body) && isXMLSpace(body[position]) {
|
||||
position++
|
||||
}
|
||||
if position > spaceStart {
|
||||
token.spacingNormalized = true
|
||||
}
|
||||
}
|
||||
if position >= len(body) || !isTagNameStart(body[position]) {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
nameStart := position
|
||||
position++
|
||||
for position < len(body) && isTagNamePart(body[position]) {
|
||||
position++
|
||||
}
|
||||
token.name = body[nameStart:position]
|
||||
rawRemainder := body[position:]
|
||||
remainder := strings.TrimRightFunc(rawRemainder, unicode.IsSpace)
|
||||
if token.closing {
|
||||
if strings.TrimSpace(remainder) != "" {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
return token, end, tokenOK
|
||||
}
|
||||
if strings.HasSuffix(remainder, "/") {
|
||||
if len(remainder) != len(rawRemainder) {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
token.selfClosing = true
|
||||
remainder = strings.TrimRightFunc(strings.TrimSuffix(remainder, "/"), unicode.IsSpace)
|
||||
}
|
||||
trimmedAttrs := strings.TrimLeftFunc(remainder, unicode.IsSpace)
|
||||
if trimmedAttrs != "" && !isAttributeNameStart(trimmedAttrs[0]) {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
var ok bool
|
||||
token.attrs, ok = parseStrictAttributes(remainder)
|
||||
if !ok {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
return token, end, tokenOK
|
||||
}
|
||||
|
||||
func isXMLSpace(ch byte) bool {
|
||||
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'
|
||||
}
|
||||
|
||||
func isTagNameStart(ch byte) bool {
|
||||
return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z'
|
||||
}
|
||||
|
||||
func isTagNamePart(ch byte) bool {
|
||||
return isTagNameStart(ch) || ch >= '0' && ch <= '9' || ch == '_' || ch == '-' || ch == '.' || ch == ':'
|
||||
}
|
||||
|
||||
func isAttributeNameStart(ch byte) bool {
|
||||
return isTagNameStart(ch) || ch == '_' || ch == ':'
|
||||
}
|
||||
|
||||
func parseAttributes(source string) map[string]string {
|
||||
attrs := map[string]string{}
|
||||
for i := 0; i < len(source); {
|
||||
for i < len(source) && unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) {
|
||||
break
|
||||
}
|
||||
start := i
|
||||
for i < len(source) && isAttributeNameByte(source[i]) {
|
||||
i++
|
||||
}
|
||||
if start == i {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
name := source[start:i]
|
||||
for i < len(source) && unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
value := ""
|
||||
if i < len(source) && source[i] == '=' {
|
||||
i++
|
||||
for i < len(source) && unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
if i < len(source) && (source[i] == '\'' || source[i] == '"') {
|
||||
quote := source[i]
|
||||
i++
|
||||
start = i
|
||||
for i < len(source) && source[i] != quote {
|
||||
i++
|
||||
}
|
||||
value = source[start:i]
|
||||
if i < len(source) {
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
start = i
|
||||
for i < len(source) && !unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
value = source[start:i]
|
||||
}
|
||||
}
|
||||
attrs[name] = html.UnescapeString(value)
|
||||
}
|
||||
if len(attrs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
// parseStrictAttributes implements the quoted attribute grammar accepted by
|
||||
// XML. parseAttributes remains intentionally permissive for the Markdown
|
||||
// container extension, whose input is Markdown rather than an XML document.
|
||||
func parseStrictAttributes(source string) (map[string]string, bool) {
|
||||
attrs := map[string]string{}
|
||||
for i := 0; i < len(source); {
|
||||
spaceStart := i
|
||||
for i < len(source) && isXMLSpace(source[i]) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) {
|
||||
break
|
||||
}
|
||||
if i == spaceStart || !isAttributeNameStart(source[i]) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
nameStart := i
|
||||
i++
|
||||
for i < len(source) && isTagNamePart(source[i]) {
|
||||
i++
|
||||
}
|
||||
name := source[nameStart:i]
|
||||
if _, exists := attrs[name]; exists {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
for i < len(source) && isXMLSpace(source[i]) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) || source[i] != '=' {
|
||||
return nil, false
|
||||
}
|
||||
i++
|
||||
for i < len(source) && isXMLSpace(source[i]) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) || (source[i] != '\'' && source[i] != '"') {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
quote := source[i]
|
||||
i++
|
||||
valueStart := i
|
||||
for i < len(source) && source[i] != quote {
|
||||
if source[i] == '<' {
|
||||
return nil, false
|
||||
}
|
||||
i++
|
||||
}
|
||||
if i >= len(source) {
|
||||
return nil, false
|
||||
}
|
||||
rawValue := source[valueStart:i]
|
||||
if invalidXMLEntityAt(rawValue) >= 0 {
|
||||
return nil, false
|
||||
}
|
||||
attrs[name] = html.UnescapeString(rawValue)
|
||||
i++
|
||||
}
|
||||
if len(attrs) == 0 {
|
||||
return nil, true
|
||||
}
|
||||
return attrs, true
|
||||
}
|
||||
|
||||
func isAttributeNameByte(ch byte) bool {
|
||||
return ch > ' ' && ch != '=' && ch != '/' && ch != '>'
|
||||
}
|
||||
|
||||
func appendText(parent *Node, raw string) {
|
||||
if parent == nil || raw == "" {
|
||||
return
|
||||
}
|
||||
appendTextValue(parent, html.UnescapeString(raw))
|
||||
}
|
||||
|
||||
func appendTextValue(parent *Node, text string) {
|
||||
if parent == nil || text == "" {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(text) == "" && !preserveSpaceTags[parent.tag] && parent.tag != "whiteboard" {
|
||||
return
|
||||
}
|
||||
if count := len(parent.children); count > 0 && parent.children[count-1].typ == nodeText {
|
||||
parent.children[count-1].text += text
|
||||
return
|
||||
}
|
||||
parent.addChild(newText(text))
|
||||
}
|
||||
|
||||
func validateXMLText(value string, absoluteOffset int) error {
|
||||
if offset := strings.Index(value, "]]>"); offset >= 0 {
|
||||
return fmt.Errorf("invalid ]]> sequence in XML text at byte %d", absoluteOffset+offset)
|
||||
}
|
||||
if offset := invalidXMLEntityAt(value); offset >= 0 {
|
||||
return fmt.Errorf("invalid XML entity at byte %d", absoluteOffset+offset)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidXMLEntityAt(value string) int {
|
||||
for cursor := 0; cursor < len(value); {
|
||||
relative := strings.IndexByte(value[cursor:], '&')
|
||||
if relative < 0 {
|
||||
return -1
|
||||
}
|
||||
start := cursor + relative
|
||||
endRelative := strings.IndexByte(value[start+1:], ';')
|
||||
if endRelative < 0 {
|
||||
return start
|
||||
}
|
||||
end := start + 1 + endRelative
|
||||
if !isValidXMLEntity(value[start+1 : end]) {
|
||||
return start
|
||||
}
|
||||
cursor = end + 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func isValidXMLEntity(entity string) bool {
|
||||
switch entity {
|
||||
case "amp", "lt", "gt", "quot", "apos":
|
||||
return true
|
||||
}
|
||||
|
||||
base := 10
|
||||
digits := ""
|
||||
switch {
|
||||
case strings.HasPrefix(entity, "#x"):
|
||||
base = 16
|
||||
digits = entity[2:]
|
||||
case strings.HasPrefix(entity, "#"):
|
||||
digits = entity[1:]
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if digits == "" {
|
||||
return false
|
||||
}
|
||||
value, err := strconv.ParseUint(digits, base, 32)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
r := rune(value)
|
||||
return r == '\t' || r == '\n' || r == '\r' ||
|
||||
r >= 0x20 && r <= 0xD7FF ||
|
||||
r >= 0xE000 && r <= 0xFFFD ||
|
||||
r >= 0x10000 && r <= utf8.MaxRune
|
||||
}
|
||||
@@ -33,6 +33,8 @@ func docsSkillReadCommandForShortcut(shortcut string) string {
|
||||
return docsSkillReadCommand + " references/lark-doc-update.md"
|
||||
case "history-list", "history-revert", "history-revert-status":
|
||||
return docsSkillReadCommand + " references/lark-doc-history.md"
|
||||
case "script":
|
||||
return docsSkillReadCommand + " references/lark-doc-script.md"
|
||||
default:
|
||||
return docsSkillReadCommand
|
||||
}
|
||||
@@ -52,6 +54,8 @@ func docsHelpCommandForShortcut(shortcut string) string {
|
||||
return "lark-cli docs +history-revert --help"
|
||||
case "history-revert-status":
|
||||
return "lark-cli docs +history-revert-status --help"
|
||||
case "script":
|
||||
return "lark-cli docs +script --help"
|
||||
default:
|
||||
return "lark-cli docs --help"
|
||||
}
|
||||
@@ -64,6 +68,7 @@ func Shortcuts() []common.Shortcut {
|
||||
DocsCreate,
|
||||
DocsFetch,
|
||||
DocsUpdate,
|
||||
DocsScript,
|
||||
DocsHistoryList,
|
||||
DocsHistoryRevert,
|
||||
DocsHistoryRevertStatus,
|
||||
|
||||
@@ -45,16 +45,6 @@ func decodeJSONMap(t *testing.T, raw string) map[string]interface{} {
|
||||
return data
|
||||
}
|
||||
|
||||
func dryRunDataMap(t *testing.T, raw string) map[string]interface{} {
|
||||
t.Helper()
|
||||
out := decodeJSONMap(t, raw)
|
||||
data, ok := out["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("dry-run data is %T, want map[string]interface{}\nstdout:\n%s", out["data"], raw)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func mustMapValue(t *testing.T, value interface{}, path string) map[string]interface{} {
|
||||
t.Helper()
|
||||
|
||||
@@ -1638,8 +1628,8 @@ func TestDryRunSlidesDirectURL(t *testing.T) {
|
||||
if !strings.Contains(stdout.String(), "slide block comment") {
|
||||
t.Fatalf("dry-run output missing slide block comment: %s", stdout.String())
|
||||
}
|
||||
out := dryRunDataMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "data.api")
|
||||
out := decodeJSONMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "api")
|
||||
call := mustMapValue(t, api[0], "api[0]")
|
||||
body := mustMapValue(t, call["body"], "api[0].body")
|
||||
anchor := mustMapValue(t, body["anchor"], "api[0].body.anchor")
|
||||
@@ -1666,8 +1656,8 @@ func TestDryRunBaseDirectURL(t *testing.T) {
|
||||
if !strings.Contains(stdout.String(), "record-local comment") {
|
||||
t.Fatalf("dry-run output missing record-local comment: %s", stdout.String())
|
||||
}
|
||||
out := dryRunDataMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "data.api")
|
||||
out := decodeJSONMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "api")
|
||||
call := mustMapValue(t, api[0], "api[0]")
|
||||
body := mustMapValue(t, call["body"], "api[0].body")
|
||||
anchor := mustMapValue(t, body["anchor"], "api[0].body.anchor")
|
||||
@@ -1709,8 +1699,8 @@ func TestDryRunWikiResolvesToSlides(t *testing.T) {
|
||||
if !strings.Contains(stdout.String(), "slide block comment") {
|
||||
t.Fatalf("dry-run output missing slide block comment: %s", stdout.String())
|
||||
}
|
||||
out := dryRunDataMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "data.api")
|
||||
out := decodeJSONMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "api")
|
||||
call := mustMapValue(t, api[0], "api[0]")
|
||||
body := mustMapValue(t, call["body"], "api[0].body")
|
||||
anchor := mustMapValue(t, body["anchor"], "api[0].body.anchor")
|
||||
@@ -1746,8 +1736,8 @@ func TestDryRunWikiSlidesInvalidBlockIDSurfaces(t *testing.T) {
|
||||
if !strings.Contains(stdout.String(), "slide --block-id must be") || !strings.Contains(stdout.String(), "shape_2") {
|
||||
t.Fatalf("dry-run output missing block-id format error: %s", stdout.String())
|
||||
}
|
||||
out := dryRunDataMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "data.api")
|
||||
out := decodeJSONMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "api")
|
||||
if len(api) != 0 {
|
||||
t.Fatalf("dry-run should not preview API calls with malformed block-id: %s", stdout.String())
|
||||
}
|
||||
@@ -1831,8 +1821,8 @@ func TestDryRunFileDirectURL(t *testing.T) {
|
||||
if !strings.Contains(stdout.String(), "verify supported file metadata") {
|
||||
t.Fatalf("dry-run output missing supported file metadata verification step: %s", stdout.String())
|
||||
}
|
||||
out := dryRunDataMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "data.api")
|
||||
out := decodeJSONMap(t, stdout.String())
|
||||
api := mustSliceValue(t, out["api"], "api")
|
||||
if len(api) != 2 {
|
||||
t.Fatalf("expected 2 dry-run api calls, got %d\nstdout:\n%s", len(api), stdout.String())
|
||||
}
|
||||
|
||||
@@ -54,21 +54,15 @@ type ImportParams struct {
|
||||
FolderToken string
|
||||
Name string
|
||||
TargetToken string
|
||||
// FileExtension optionally overrides the extension inferred from File's
|
||||
// name. Leave empty to infer from File (the default). Callers that have
|
||||
// sniffed the file's real container use this to correct a mislabeled name
|
||||
// so the backend receives the true format.
|
||||
FileExtension string
|
||||
}
|
||||
|
||||
func (p ImportParams) spec() driveImportSpec {
|
||||
return driveImportSpec{
|
||||
FilePath: p.File,
|
||||
DocType: strings.ToLower(p.DocType),
|
||||
FolderToken: p.FolderToken,
|
||||
Name: p.Name,
|
||||
TargetToken: p.TargetToken,
|
||||
EffectiveExt: strings.TrimPrefix(strings.ToLower(p.FileExtension), "."),
|
||||
FilePath: p.File,
|
||||
DocType: strings.ToLower(p.DocType),
|
||||
FolderToken: p.FolderToken,
|
||||
Name: p.Name,
|
||||
TargetToken: p.TargetToken,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +127,7 @@ func RunImport(ctx context.Context, runtime *common.RuntimeContext, p ImportPara
|
||||
}
|
||||
|
||||
// Step 1: Upload file as media
|
||||
fileToken, uploadErr := uploadMediaForImport(ctx, runtime, spec)
|
||||
fileToken, uploadErr := uploadMediaForImport(ctx, runtime, spec.FilePath, spec.SourceFileName(), spec.DocType)
|
||||
if uploadErr != nil {
|
||||
return uploadErr
|
||||
}
|
||||
@@ -209,14 +203,14 @@ func preflightDriveImportFile(fio fileio.FileIO, spec *driveImportSpec) (int64,
|
||||
if !info.Mode().IsRegular() {
|
||||
return 0, errs.NewValidationError(errs.SubtypeInvalidArgument, "file must be a regular file: %s", spec.FilePath).WithParam("--file")
|
||||
}
|
||||
if err = validateDriveImportFileSize(spec.FileExtension(), spec.DocType, info.Size()); err != nil {
|
||||
if err = validateDriveImportFileSize(spec.FilePath, spec.DocType, info.Size()); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return info.Size(), nil
|
||||
}
|
||||
|
||||
func appendDriveImportUploadDryRun(dry *common.DryRunAPI, spec driveImportSpec, fileSize int64) {
|
||||
extra, err := buildImportMediaExtra(spec.FileExtension(), spec.DocType)
|
||||
extra, err := buildImportMediaExtra(spec.FilePath, spec.DocType)
|
||||
if err != nil {
|
||||
extra = fmt.Sprintf(`{"obj_type":"%s","file_extension":"%s"}`, spec.DocType, spec.FileExtension())
|
||||
}
|
||||
|
||||
@@ -59,39 +59,14 @@ type driveImportSpec struct {
|
||||
FolderToken string
|
||||
Name string
|
||||
TargetToken string // existing bitable token to import data into (only for type=bitable)
|
||||
|
||||
// EffectiveExt is a caller-supplied override for the extension otherwise
|
||||
// derived from FilePath (see ImportParams.FileExtension). It lets a caller
|
||||
// that has detected the file's real container correct a mislabeled name
|
||||
// (e.g. an OOXML workbook saved as .xls). Empty means "trust the filename".
|
||||
EffectiveExt string
|
||||
}
|
||||
|
||||
// rawExtension is the lowercased extension taken verbatim from the file name.
|
||||
func (s driveImportSpec) rawExtension() string {
|
||||
func (s driveImportSpec) FileExtension() string {
|
||||
return strings.TrimPrefix(strings.ToLower(filepath.Ext(s.FilePath)), ".")
|
||||
}
|
||||
|
||||
// FileExtension is the extension the import pipeline treats as authoritative:
|
||||
// the content-sniffed override when set, otherwise the file name's extension.
|
||||
func (s driveImportSpec) FileExtension() string {
|
||||
if s.EffectiveExt != "" {
|
||||
return s.EffectiveExt
|
||||
}
|
||||
return s.rawExtension()
|
||||
}
|
||||
|
||||
// SourceFileName is the name used when staging the upload media. When content
|
||||
// sniffing corrected the extension, the staged name must carry the corrected
|
||||
// suffix too: the import backend cross-checks the media file name's extension
|
||||
// against the file_extension in the import task and rejects a mismatch with
|
||||
// "import file extension not match" (code 1069910).
|
||||
func (s driveImportSpec) SourceFileName() string {
|
||||
base := filepath.Base(s.FilePath)
|
||||
if s.EffectiveExt != "" && s.EffectiveExt != s.rawExtension() {
|
||||
base = strings.TrimSuffix(base, filepath.Ext(base)) + "." + s.EffectiveExt
|
||||
}
|
||||
return base
|
||||
return filepath.Base(s.FilePath)
|
||||
}
|
||||
|
||||
func (s driveImportSpec) TargetFileName() string {
|
||||
@@ -122,20 +97,18 @@ func (s driveImportSpec) CreateTaskBody(fileToken string) map[string]interface{}
|
||||
|
||||
// uploadMediaForImport uploads the source file to the temporary import media
|
||||
// endpoint and returns the file token consumed by import_tasks.
|
||||
func uploadMediaForImport(ctx context.Context, runtime *common.RuntimeContext, spec driveImportSpec) (string, error) {
|
||||
filePath := spec.FilePath
|
||||
fileName := spec.SourceFileName()
|
||||
func uploadMediaForImport(ctx context.Context, runtime *common.RuntimeContext, filePath, fileName, docType string) (string, error) {
|
||||
importInfo, err := runtime.FileIO().Stat(filePath)
|
||||
if err != nil {
|
||||
return "", driveInputStatError(err)
|
||||
}
|
||||
|
||||
fileSize := importInfo.Size()
|
||||
if err = validateDriveImportFileSize(spec.FileExtension(), spec.DocType, fileSize); err != nil {
|
||||
if err = validateDriveImportFileSize(filePath, docType, fileSize); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
extra, err := buildImportMediaExtra(spec.FileExtension(), spec.DocType)
|
||||
extra, err := buildImportMediaExtra(filePath, docType)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -166,12 +139,12 @@ func uploadMediaForImport(ctx context.Context, runtime *common.RuntimeContext, s
|
||||
})
|
||||
}
|
||||
|
||||
func buildImportMediaExtra(ext, docType string) (string, error) {
|
||||
func buildImportMediaExtra(filePath, docType string) (string, error) {
|
||||
// The import media endpoint uses extra to decide both the target native type
|
||||
// and how to interpret the uploaded source file.
|
||||
extraBytes, err := json.Marshal(map[string]string{
|
||||
"obj_type": docType,
|
||||
"file_extension": ext,
|
||||
"file_extension": strings.TrimPrefix(strings.ToLower(filepath.Ext(filePath)), "."),
|
||||
})
|
||||
if err != nil {
|
||||
return "", errs.NewInternalError(errs.SubtypeUnknown, "build upload extra failed: %v", err).WithCause(err)
|
||||
@@ -179,10 +152,10 @@ func buildImportMediaExtra(ext, docType string) (string, error) {
|
||||
return string(extraBytes), nil
|
||||
}
|
||||
|
||||
func driveImportFileSizeLimit(ext, docType string) (int64, bool) {
|
||||
func driveImportFileSizeLimit(filePath, docType string) (int64, bool) {
|
||||
// Keep the limit mapping local to import flows so we do not widen behavior
|
||||
// changes beyond drive +import.
|
||||
switch ext {
|
||||
switch strings.TrimPrefix(strings.ToLower(filepath.Ext(filePath)), ".") {
|
||||
case "docx", "doc":
|
||||
return driveImport600MBFileSizeLimit, true
|
||||
case "pptx":
|
||||
@@ -201,12 +174,13 @@ func driveImportFileSizeLimit(ext, docType string) (int64, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func validateDriveImportFileSize(ext, docType string, fileSize int64) error {
|
||||
limit, ok := driveImportFileSizeLimit(ext, docType)
|
||||
func validateDriveImportFileSize(filePath, docType string, fileSize int64) error {
|
||||
limit, ok := driveImportFileSizeLimit(filePath, docType)
|
||||
if !ok || fileSize <= limit {
|
||||
return nil
|
||||
}
|
||||
|
||||
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(filePath)), ".")
|
||||
if ext == "csv" {
|
||||
// CSV is the only source format whose limit depends on the target type.
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
|
||||
@@ -94,61 +94,61 @@ func TestValidateDriveImportFileSize(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
ext string
|
||||
filePath string
|
||||
docType string
|
||||
fileSize int64
|
||||
wantText string
|
||||
}{
|
||||
{
|
||||
name: "docx exceeds 600mb limit",
|
||||
ext: "docx",
|
||||
filePath: "./report.docx",
|
||||
docType: "docx",
|
||||
fileSize: driveImport600MBFileSizeLimit + 1,
|
||||
wantText: "exceeds 600.0 MB import limit for .docx",
|
||||
},
|
||||
{
|
||||
name: "csv sheet exceeds 20mb limit",
|
||||
ext: "csv",
|
||||
filePath: "./data.csv",
|
||||
docType: "sheet",
|
||||
fileSize: driveImport20MBFileSizeLimit + 1,
|
||||
wantText: "exceeds 20.0 MB import limit for .csv when importing as sheet",
|
||||
},
|
||||
{
|
||||
name: "csv bitable exceeds 100mb limit",
|
||||
ext: "csv",
|
||||
filePath: "./data.csv",
|
||||
docType: "bitable",
|
||||
fileSize: driveImport100MBFileSizeLimit + 1,
|
||||
wantText: "exceeds 100.0 MB import limit for .csv when importing as bitable",
|
||||
},
|
||||
{
|
||||
name: "xlsx within 800mb limit",
|
||||
ext: "xlsx",
|
||||
filePath: "./data.xlsx",
|
||||
docType: "sheet",
|
||||
fileSize: driveImport800MBFileSizeLimit,
|
||||
},
|
||||
{
|
||||
name: "pptx exceeds 500mb limit",
|
||||
ext: "pptx",
|
||||
filePath: "./deck.pptx",
|
||||
docType: "slides",
|
||||
fileSize: driveImport500MBFileSizeLimit + 1,
|
||||
wantText: "exceeds 500.0 MB import limit for .pptx",
|
||||
},
|
||||
{
|
||||
name: "pptx within 500mb limit",
|
||||
ext: "pptx",
|
||||
filePath: "./deck.pptx",
|
||||
docType: "slides",
|
||||
fileSize: driveImport500MBFileSizeLimit,
|
||||
},
|
||||
{
|
||||
name: "base exceeds 20mb limit",
|
||||
ext: "base",
|
||||
filePath: "./snapshot.base",
|
||||
docType: "bitable",
|
||||
fileSize: driveImport20MBFileSizeLimit + 1,
|
||||
wantText: "exceeds 20.0 MB import limit for .base",
|
||||
},
|
||||
{
|
||||
name: "base within 20mb limit",
|
||||
ext: "base",
|
||||
filePath: "./snapshot.base",
|
||||
docType: "bitable",
|
||||
fileSize: driveImport20MBFileSizeLimit,
|
||||
},
|
||||
@@ -158,7 +158,7 @@ func TestValidateDriveImportFileSize(t *testing.T) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := validateDriveImportFileSize(tt.ext, tt.docType, tt.fileSize)
|
||||
err := validateDriveImportFileSize(tt.filePath, tt.docType, tt.fileSize)
|
||||
if tt.wantText == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
|
||||
@@ -6,7 +6,6 @@ package drive
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
@@ -20,7 +19,7 @@ const (
|
||||
driveListCommentsDefaultScope = "all"
|
||||
)
|
||||
|
||||
var driveListCommentsTypes = []string{"doc", "docx", "sheet", "file", "slides", "bitable", "base", "apps", "wiki"}
|
||||
var driveListCommentsTypes = []string{"doc", "docx", "sheet", "file", "slides", "bitable", "base", "wiki"}
|
||||
|
||||
type driveListCommentsRef struct {
|
||||
Token string
|
||||
@@ -44,17 +43,17 @@ type driveListCommentsSpec struct {
|
||||
}
|
||||
|
||||
// DriveListComments lists document comments through the Drive comments API,
|
||||
// while accepting Wiki URLs/tokens and Miaoda /page/<token> apps URLs.
|
||||
// while accepting Wiki URLs/tokens and resolving them to the underlying object.
|
||||
var DriveListComments = common.Shortcut{
|
||||
Service: "drive",
|
||||
Command: "+list-comments",
|
||||
Description: "List comments for doc/docx/sheet/file/slides/base(bitable)/apps, with URL parsing and Wiki token unwrapping",
|
||||
Description: "List comments for doc/docx/sheet/file/slides/base(bitable), with URL parsing and Wiki token unwrapping",
|
||||
Risk: "read",
|
||||
Scopes: []string{"docs:document.comment:read"},
|
||||
ConditionalScopes: []string{"wiki:node:retrieve"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "url", Desc: "recommended: Lark/Feishu document URL (doc/docx/sheet/file/slides/base/bitable/apps/wiki); apps Miaoda URLs use /page/<token>; Wiki URLs are unwrapped automatically"},
|
||||
{Name: "url", Desc: "recommended: Lark/Feishu document URL (doc/docx/sheet/file/slides/base/bitable/wiki); Wiki URLs are unwrapped automatically"},
|
||||
{Name: "token", Desc: "document token, Wiki token, or document URL; bare tokens require --type"},
|
||||
{Name: "type", Desc: "document type for bare --token; optional for URLs but must match the URL type when provided", Enum: driveListCommentsTypes},
|
||||
{Name: "solved-status", Default: driveListCommentsDefaultSolvedStatus, Desc: "comment solved filter: false=unresolved, true=solved, all=all comments", Enum: []string{"false", "true", "all"}},
|
||||
@@ -166,60 +165,29 @@ func resolveDriveListCommentsInput(urlInput, tokenInput, explicitType string) (d
|
||||
if !driveListCommentsTypeSupported(refType) {
|
||||
return driveListCommentsRef{}, errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"unsupported %s resource type %q; comments list supports doc, docx, sheet, file, slides, bitable/base, apps, and wiki",
|
||||
"unsupported %s resource type %q; comments list supports doc, docx, sheet, file, slides, bitable/base, and wiki",
|
||||
sourceFlag,
|
||||
refType,
|
||||
).WithParam(sourceFlag)
|
||||
}
|
||||
return driveListCommentsRef{Token: ref.Token, Type: refType, SourceFlag: sourceFlag}, nil
|
||||
}
|
||||
if token, ok := parseDriveListCommentsAppsURL(raw); ok {
|
||||
const refType = "apps"
|
||||
if inputType != "" && inputType != refType {
|
||||
return driveListCommentsRef{}, errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"--type %q conflicts with URL path type %q; remove --type or use a matching value",
|
||||
inputType,
|
||||
refType,
|
||||
).WithParam("--type")
|
||||
}
|
||||
return driveListCommentsRef{Token: token, Type: refType, SourceFlag: sourceFlag}, nil
|
||||
}
|
||||
|
||||
if strings.Contains(raw, "://") {
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "unsupported %s URL %q: use a recognized Lark document URL, a Miaoda /page/<token> URL, or pass a bare token with --type", sourceFlag, raw).WithParam(sourceFlag)
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "unsupported %s URL %q: use a recognized Lark document URL or pass a bare token with --type", sourceFlag, raw).WithParam(sourceFlag)
|
||||
}
|
||||
if strings.ContainsAny(raw, "/?#") {
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid bare token %q: remove path/query fragments or pass a recognized Lark document URL", raw).WithParam(sourceFlag)
|
||||
}
|
||||
if inputType == "" {
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "--type is required when %s is a bare token (allowed: doc, docx, sheet, file, slides, bitable, base, apps, wiki)", sourceFlag).WithParam("--type")
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "--type is required when %s is a bare token (allowed: doc, docx, sheet, file, slides, bitable, base, wiki)", sourceFlag).WithParam("--type")
|
||||
}
|
||||
if !driveListCommentsTypeSupported(inputType) {
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid --type %q; allowed: doc, docx, sheet, file, slides, bitable, base, apps, wiki", inputType).WithParam("--type")
|
||||
return driveListCommentsRef{}, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid --type %q; allowed: doc, docx, sheet, file, slides, bitable, base, wiki", inputType).WithParam("--type")
|
||||
}
|
||||
return driveListCommentsRef{Token: raw, Type: inputType, SourceFlag: sourceFlag}, nil
|
||||
}
|
||||
|
||||
func parseDriveListCommentsAppsURL(rawURL string) (string, bool) {
|
||||
u, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
path := strings.Trim(u.Path, "/")
|
||||
parts := strings.Split(path, "/")
|
||||
if len(parts) < 2 || parts[0] != "page" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
token := strings.TrimSpace(parts[1])
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func normalizeDriveListCommentsType(docType string) string {
|
||||
switch strings.TrimSpace(docType) {
|
||||
case "base":
|
||||
@@ -231,7 +199,7 @@ func normalizeDriveListCommentsType(docType string) string {
|
||||
|
||||
func driveListCommentsTypeSupported(docType string) bool {
|
||||
switch normalizeDriveListCommentsType(docType) {
|
||||
case "doc", "docx", "sheet", "file", "slides", "bitable", "apps", "wiki":
|
||||
case "doc", "docx", "sheet", "file", "slides", "bitable", "wiki":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -263,7 +231,7 @@ func resolveDriveListCommentsTarget(ctx context.Context, runtime *common.Runtime
|
||||
if !driveListCommentsTypeSupported(objType) || objType == "wiki" {
|
||||
return driveListCommentsTarget{}, errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"wiki resolved to %q, but comments list only supports doc, docx, sheet, file, slides, bitable, and apps",
|
||||
"wiki resolved to %q, but comments list only supports doc, docx, sheet, file, slides, and bitable",
|
||||
objType,
|
||||
).WithParam(ref.SourceFlag)
|
||||
}
|
||||
|
||||
@@ -46,32 +46,6 @@ func TestResolveDriveListCommentsInput(t *testing.T) {
|
||||
wantResource: "wikiResource",
|
||||
wantType: "wiki",
|
||||
},
|
||||
{
|
||||
name: "bare apps token",
|
||||
rawInput: "appsResource",
|
||||
docType: "apps",
|
||||
wantResource: "appsResource",
|
||||
wantType: "apps",
|
||||
},
|
||||
{
|
||||
name: "miaoda page url",
|
||||
urlInput: "https://bytedance.feishu.cn/page/appsResource/?from=home",
|
||||
wantResource: "appsResource",
|
||||
wantType: "apps",
|
||||
},
|
||||
{
|
||||
name: "token flag also accepts miaoda page url",
|
||||
rawInput: "https://bytedance.feishu.cn/page/appsResource/",
|
||||
wantResource: "appsResource",
|
||||
wantType: "apps",
|
||||
},
|
||||
{
|
||||
name: "miaoda page url type conflict",
|
||||
urlInput: "https://bytedance.feishu.cn/page/appsResource/",
|
||||
docType: "docx",
|
||||
wantErr: "conflicts",
|
||||
wantParam: "--type",
|
||||
},
|
||||
{
|
||||
name: "url and token mutually exclusive",
|
||||
urlInput: "https://example.larksuite.com/docx/docxResource",
|
||||
@@ -98,19 +72,6 @@ func TestResolveDriveListCommentsInput(t *testing.T) {
|
||||
wantErr: "unsupported",
|
||||
wantParam: "--url",
|
||||
},
|
||||
{
|
||||
name: "unsupported miaoda url path",
|
||||
urlInput: "https://bytedance.feishu.cn/app/appsResource",
|
||||
wantErr: "Miaoda /page/<token>",
|
||||
wantParam: "--url",
|
||||
},
|
||||
{
|
||||
name: "invalid bare token type",
|
||||
rawInput: "appsResource",
|
||||
docType: "folder",
|
||||
wantErr: "invalid --type",
|
||||
wantParam: "--type",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -135,50 +96,6 @@ func TestResolveDriveListCommentsInput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDriveListCommentsAppsURL(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
rawURL string
|
||||
wantToken string
|
||||
wantOK bool
|
||||
}{
|
||||
{
|
||||
name: "page url",
|
||||
rawURL: "https://bytedance.feishu.cn/page/appsResource?from=home",
|
||||
wantToken: "appsResource",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "bare token is not url",
|
||||
rawURL: "appsResource",
|
||||
},
|
||||
{
|
||||
name: "non page path",
|
||||
rawURL: "https://bytedance.feishu.cn/app/appsResource",
|
||||
},
|
||||
{
|
||||
name: "empty page token",
|
||||
rawURL: "https://bytedance.feishu.cn/page/%20",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
gotToken, gotOK := parseDriveListCommentsAppsURL(tt.rawURL)
|
||||
if gotOK != tt.wantOK {
|
||||
t.Fatalf("ok = %v, want %v", gotOK, tt.wantOK)
|
||||
}
|
||||
if gotToken != tt.wantToken {
|
||||
t.Fatalf("token = %q, want %q", gotToken, tt.wantToken)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDriveListCommentsSpec(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -311,14 +228,6 @@ func TestBuildDriveListCommentsParams(t *testing.T) {
|
||||
if _, ok := sheetParams["need_relation"]; ok {
|
||||
t.Fatalf("need_relation should be ignored for non-docx: %#v", sheetParams)
|
||||
}
|
||||
|
||||
appsParams := buildDriveListCommentsParams(allPartialSpec, "apps")
|
||||
if got := appsParams["file_type"]; got != "apps" {
|
||||
t.Fatalf("apps file_type = %#v, want apps", got)
|
||||
}
|
||||
if _, ok := appsParams["need_relation"]; ok {
|
||||
t.Fatalf("need_relation should be ignored for apps: %#v", appsParams)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveListCommentsExecuteDocx(t *testing.T) {
|
||||
@@ -444,84 +353,3 @@ func TestDriveListCommentsExecuteWikiResolvesToDocx(t *testing.T) {
|
||||
t.Fatalf("file_type = %q, want docx", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveListCommentsExecuteWikiRejectsUnsupportedResolvedType(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, driveTestConfig())
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/wiki/v2/spaces/get_node",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"node": map[string]interface{}{
|
||||
"obj_type": "folder",
|
||||
"obj_token": "folderResource",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRunDrive(t, DriveListComments, []string{
|
||||
"+list-comments",
|
||||
"--token", "wikiResource",
|
||||
"--type", "wiki",
|
||||
"--as", "user",
|
||||
}, f, stdout)
|
||||
if err == nil || !strings.Contains(err.Error(), "supports doc, docx, sheet, file, slides, bitable, and apps") {
|
||||
t.Fatalf("expected unsupported resolved type error, got %v", err)
|
||||
}
|
||||
assertDriveListCommentsValidationError(t, err, "--token")
|
||||
}
|
||||
|
||||
func TestDriveListCommentsExecuteAppsPageURL(t *testing.T) {
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, driveTestConfig())
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/drive/v1/files/appsResource/comments",
|
||||
OnMatch: func(req *http.Request) {
|
||||
query := req.URL.Query()
|
||||
if got := query.Get("file_type"); got != "apps" {
|
||||
t.Errorf("file_type = %q, want apps", got)
|
||||
}
|
||||
if got := query.Get("is_solved"); got != "false" {
|
||||
t.Errorf("is_solved = %q, want false", got)
|
||||
}
|
||||
if got := query.Get("need_relation"); got != "" {
|
||||
t.Errorf("need_relation = %q, want omitted for apps", got)
|
||||
}
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"items": []map[string]interface{}{
|
||||
{"comment_id": "comment_apps_1", "is_solved": false},
|
||||
},
|
||||
"has_more": false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRunDrive(t, DriveListComments, []string{
|
||||
"+list-comments",
|
||||
"--url", "https://bytedance.feishu.cn/page/appsResource/",
|
||||
"--need-relation",
|
||||
"--as", "user",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
out := decodeJSONMap(t, stdout.String())
|
||||
data := mustMapValue(t, out["data"], "data")
|
||||
if got := mustStringField(t, data, "file_token", "data.file_token"); got != "appsResource" {
|
||||
t.Fatalf("file_token = %q, want appsResource", got)
|
||||
}
|
||||
if got := mustStringField(t, data, "file_type", "data.file_type"); got != "apps" {
|
||||
t.Fatalf("file_type = %q, want apps", got)
|
||||
}
|
||||
if got := data["count"]; got != float64(1) {
|
||||
t.Fatalf("count = %#v, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user