zinkee 0.1.40 → 0.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ import { mkdtempSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { Command } from "commander";
6
+ import { afterEach, describe, expect, it, vi } from "vitest";
7
+
8
+ import { registerFormulasCommands } from "./formulas.js";
9
+
10
+ function createConfig(): string {
11
+ const dir = mkdtempSync(join(tmpdir(), "zinkee-formulas-"));
12
+ const filePath = join(dir, "config.toml");
13
+ writeFileSync(
14
+ filePath,
15
+ `default_profile = "test"\n\n[profiles.test]\napi_key = "token"\nbase_url = "https://api.zinkee.test"\n`,
16
+ "utf8",
17
+ );
18
+ return filePath;
19
+ }
20
+
21
+ function createStdoutBuffer() {
22
+ let output = "";
23
+ return {
24
+ stdout: {
25
+ write(chunk: string) {
26
+ output += chunk;
27
+ return true;
28
+ },
29
+ },
30
+ read: () => output,
31
+ };
32
+ }
33
+
34
+ function buildProgram(options: { configPath: string; stdout: { write(chunk: string): unknown } }): Command {
35
+ const program = new Command();
36
+ program
37
+ .name("zinkee")
38
+ .enablePositionalOptions()
39
+ .option("--read-only")
40
+ .option("--json");
41
+ registerFormulasCommands(program, options);
42
+ return program;
43
+ }
44
+
45
+ function queuedResponse(scope: "FIELD" | "SCHEMA" | "WORKSPACE", eventsQueued = 1): Response {
46
+ return new Response(
47
+ JSON.stringify({
48
+ requestId: "request-1",
49
+ scope,
50
+ formulaCount: eventsQueued,
51
+ skippedFormulaCount: 0,
52
+ eventsQueued,
53
+ status: "QUEUED",
54
+ }),
55
+ { status: 202, headers: { "content-type": "application/json" } },
56
+ );
57
+ }
58
+
59
+ afterEach(() => {
60
+ vi.unstubAllGlobals();
61
+ vi.restoreAllMocks();
62
+ });
63
+
64
+ describe("formulas commands", () => {
65
+ it("registers the formulas command group", () => {
66
+ const output = createStdoutBuffer();
67
+ const program = buildProgram({ configPath: createConfig(), stdout: output.stdout });
68
+
69
+ expect(program.commands.some((command) => command.name() === "formulas")).toBe(true);
70
+ });
71
+
72
+ it("queues one field by slug and emits the JSON envelope", async () => {
73
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(queuedResponse("FIELD"));
74
+ vi.stubGlobal("fetch", fetchMock);
75
+ const configPath = createConfig();
76
+ const output = createStdoutBuffer();
77
+ const program = buildProgram({ configPath, stdout: output.stdout });
78
+
79
+ await program.parseAsync([
80
+ "node",
81
+ "zinkee",
82
+ "--json",
83
+ "formulas",
84
+ "recompute",
85
+ "field",
86
+ "invoices",
87
+ "total",
88
+ ]);
89
+
90
+ const [, init] = fetchMock.mock.calls[0]!;
91
+ expect(JSON.parse(String(init?.body))).toEqual({
92
+ scope: "FIELD",
93
+ schema: "invoices",
94
+ field: "total",
95
+ });
96
+ expect(JSON.parse(output.read())).toEqual({
97
+ data: {
98
+ requestId: "request-1",
99
+ scope: "FIELD",
100
+ formulaCount: 1,
101
+ skippedFormulaCount: 0,
102
+ eventsQueued: 1,
103
+ status: "QUEUED",
104
+ },
105
+ meta: { command: "formulas recompute field", configPath },
106
+ });
107
+ });
108
+
109
+ it.each([
110
+ ["schema", ["invoices"]],
111
+ ["workspace", []],
112
+ ])("requires --yes before the %s request", async (scope, args) => {
113
+ const fetchMock = vi.fn<typeof fetch>();
114
+ vi.stubGlobal("fetch", fetchMock);
115
+ const output = createStdoutBuffer();
116
+ const program = buildProgram({ configPath: createConfig(), stdout: output.stdout });
117
+
118
+ await expect(
119
+ program.parseAsync([
120
+ "node",
121
+ "zinkee",
122
+ "formulas",
123
+ "recompute",
124
+ scope,
125
+ ...args,
126
+ ]),
127
+ ).rejects.toThrow("requires --yes");
128
+ expect(fetchMock).not.toHaveBeenCalled();
129
+ });
130
+
131
+ it("queues every schema formula after confirmation", async () => {
132
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(queuedResponse("SCHEMA", 3));
133
+ vi.stubGlobal("fetch", fetchMock);
134
+ const output = createStdoutBuffer();
135
+ const program = buildProgram({ configPath: createConfig(), stdout: output.stdout });
136
+
137
+ await program.parseAsync([
138
+ "node",
139
+ "zinkee",
140
+ "formulas",
141
+ "recompute",
142
+ "schema",
143
+ "invoices",
144
+ "--yes",
145
+ ]);
146
+
147
+ expect(output.read()).toContain("Queued 3 formula recalculation event(s)");
148
+ expect(output.read()).not.toContain("completed");
149
+ });
150
+
151
+ it("queues the workspace payload after confirmation", async () => {
152
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(queuedResponse("WORKSPACE", 5));
153
+ vi.stubGlobal("fetch", fetchMock);
154
+ const output = createStdoutBuffer();
155
+ const program = buildProgram({ configPath: createConfig(), stdout: output.stdout });
156
+
157
+ await program.parseAsync([
158
+ "node",
159
+ "zinkee",
160
+ "--json",
161
+ "formulas",
162
+ "recompute",
163
+ "workspace",
164
+ "--yes",
165
+ ]);
166
+
167
+ const [, init] = fetchMock.mock.calls[0]!;
168
+ expect(JSON.parse(String(init?.body))).toEqual({ scope: "WORKSPACE" });
169
+ });
170
+
171
+ it.each([
172
+ ["field", ["invoices", "total"]],
173
+ ["schema", ["invoices", "--yes"]],
174
+ ["workspace", ["--yes"]],
175
+ ])("blocks %s in read-only mode before any network request", async (scope, args) => {
176
+ const fetchMock = vi.fn<typeof fetch>();
177
+ vi.stubGlobal("fetch", fetchMock);
178
+ const output = createStdoutBuffer();
179
+ const program = buildProgram({ configPath: createConfig(), stdout: output.stdout });
180
+
181
+ await expect(
182
+ program.parseAsync([
183
+ "node",
184
+ "zinkee",
185
+ "--read-only",
186
+ "formulas",
187
+ "recompute",
188
+ scope,
189
+ ...args,
190
+ ]),
191
+ ).rejects.toThrow("not allowed in read-only mode");
192
+ expect(fetchMock).not.toHaveBeenCalled();
193
+ });
194
+ });
@@ -0,0 +1,243 @@
1
+ import type { Writable } from "node:stream";
2
+
3
+ import { Command, InvalidArgumentError } from "commander";
4
+
5
+ import {
6
+ FormulasApi,
7
+ type FormulaRecomputeInput,
8
+ type FormulaRecomputeResponse,
9
+ } from "../api/formulas.js";
10
+ import { ApiClient } from "../client.js";
11
+ import { defaultConfigPath, readRuntimeConfig } from "../config.js";
12
+ import {
13
+ normalizeUuidOrSlug,
14
+ type NormalizedUuidOrSlug,
15
+ } from "../parsers/selectors.js";
16
+ import { resolveRuntimeContext } from "../runtime-context.js";
17
+ import type { RuntimeOverrides } from "../types.js";
18
+ import { CliError } from "../utils/errors.js";
19
+ import { buildJsonSuccess } from "../utils/output.js";
20
+
21
+ interface CommandIo {
22
+ write(chunk: string): unknown;
23
+ }
24
+
25
+ export interface RegisterFormulasCommandsOptions {
26
+ configPath?: string;
27
+ stdout?: CommandIo;
28
+ }
29
+
30
+ interface GlobalOptions extends RuntimeOverrides {}
31
+
32
+ interface ConfirmedCommandOptions {
33
+ yes?: boolean;
34
+ }
35
+
36
+ function getCommandIo(stdout: CommandIo | undefined): CommandIo {
37
+ return stdout ?? (process.stdout as Writable);
38
+ }
39
+
40
+ function writeLine(stdout: CommandIo, value: string): void {
41
+ stdout.write(`${value}\n`);
42
+ }
43
+
44
+ function getGlobalOptions(command: Command): GlobalOptions {
45
+ return command.optsWithGlobals<GlobalOptions>();
46
+ }
47
+
48
+ function toConfigurationError(filePath: string, error: unknown): never {
49
+ if (error instanceof CliError) {
50
+ throw error;
51
+ }
52
+
53
+ if (
54
+ typeof error === "object" &&
55
+ error !== null &&
56
+ "code" in error &&
57
+ error.code === "ENOENT"
58
+ ) {
59
+ throw new CliError("configuration_error", `Config file not found at ${filePath}.`);
60
+ }
61
+
62
+ if (error instanceof Error) {
63
+ throw new CliError("configuration_error", error.message);
64
+ }
65
+
66
+ throw error;
67
+ }
68
+
69
+ function createFormulasApi(
70
+ command: Command,
71
+ filePath: string,
72
+ ): { api: FormulasApi; json: boolean; readOnly: boolean } {
73
+ try {
74
+ const config = readRuntimeConfig(filePath);
75
+ const runtime = resolveRuntimeContext(config, getGlobalOptions(command));
76
+
77
+ if (!runtime.baseUrl) {
78
+ throw new CliError(
79
+ "configuration_error",
80
+ `Resolved profile "${runtime.profile}" is missing a base URL.`,
81
+ );
82
+ }
83
+
84
+ return {
85
+ api: new FormulasApi(
86
+ new ApiClient({
87
+ baseUrl: runtime.baseUrl,
88
+ apiKey: runtime.apiKey,
89
+ }),
90
+ ),
91
+ json: runtime.json,
92
+ readOnly: runtime.readOnly,
93
+ };
94
+ } catch (error) {
95
+ toConfigurationError(filePath, error);
96
+ }
97
+ }
98
+
99
+ function ensureWritable(commandName: string, readOnly: boolean): void {
100
+ if (readOnly) {
101
+ throw new CliError(
102
+ "command_not_allowed_in_read_only_mode",
103
+ `Command "${commandName}" is not allowed in read-only mode.`,
104
+ {
105
+ commandMode: "write",
106
+ executionMode: "read-only",
107
+ },
108
+ );
109
+ }
110
+ }
111
+
112
+ function ensureConfirmed(commandName: string, confirmed: boolean | undefined): void {
113
+ if (!confirmed) {
114
+ throw new CliError(
115
+ "invalid_cli_usage",
116
+ `Command "${commandName}" requires --yes because it may enqueue a large recalculation.`,
117
+ );
118
+ }
119
+ }
120
+
121
+ function parseUuidOrSlugSelector(input: string): NormalizedUuidOrSlug {
122
+ try {
123
+ return normalizeUuidOrSlug(input);
124
+ } catch (error) {
125
+ const message = error instanceof Error ? error.message : "Invalid selector.";
126
+ throw new InvalidArgumentError(message);
127
+ }
128
+ }
129
+
130
+ function emitResult(
131
+ stdout: CommandIo,
132
+ commandName: string,
133
+ result: FormulaRecomputeResponse,
134
+ configPath: string,
135
+ json: boolean,
136
+ ): void {
137
+ if (json) {
138
+ writeLine(
139
+ stdout,
140
+ JSON.stringify(buildJsonSuccess(result, { command: commandName, configPath })),
141
+ );
142
+ return;
143
+ }
144
+
145
+ writeLine(
146
+ stdout,
147
+ `Queued ${result.eventsQueued} formula recalculation event(s) for ${result.scope.toLowerCase()} scope (request ${result.requestId}).`,
148
+ );
149
+ }
150
+
151
+ async function recompute(
152
+ command: Command,
153
+ commandName: string,
154
+ input: FormulaRecomputeInput,
155
+ options: RegisterFormulasCommandsOptions,
156
+ requireConfirmation: boolean,
157
+ confirmed?: boolean,
158
+ ): Promise<void> {
159
+ const configPath = options.configPath ?? defaultConfigPath;
160
+ const stdout = getCommandIo(options.stdout);
161
+ const { api, json, readOnly } = createFormulasApi(command, configPath);
162
+
163
+ ensureWritable(commandName, readOnly);
164
+ if (requireConfirmation) {
165
+ ensureConfirmed(commandName, confirmed);
166
+ }
167
+
168
+ const result = await api.recompute(input);
169
+ emitResult(stdout, commandName, result, configPath, json);
170
+ }
171
+
172
+ export function registerFormulasCommands(
173
+ program: Command,
174
+ options: RegisterFormulasCommandsOptions = {},
175
+ ): void {
176
+ const formulas = program
177
+ .command("formulas")
178
+ .description("Recalculate formula values");
179
+ const recomputeCommand = formulas
180
+ .command("recompute")
181
+ .description("Queue a full formula recalculation");
182
+
183
+ recomputeCommand
184
+ .command("field")
185
+ .description("Queue recalculation of one formula column")
186
+ .argument("<schema>", "schema UUID or slug", parseUuidOrSlugSelector)
187
+ .argument("<field>", "formula field UUID or slug", parseUuidOrSlugSelector)
188
+ .action(
189
+ async function action(
190
+ this: Command,
191
+ schema: NormalizedUuidOrSlug,
192
+ field: NormalizedUuidOrSlug,
193
+ ) {
194
+ await recompute(
195
+ this,
196
+ "formulas recompute field",
197
+ { scope: "FIELD", schema, field },
198
+ options,
199
+ false,
200
+ );
201
+ },
202
+ );
203
+
204
+ recomputeCommand
205
+ .command("schema")
206
+ .description("Queue recalculation of all active formulas in one schema")
207
+ .argument("<schema>", "schema UUID or slug", parseUuidOrSlugSelector)
208
+ .option("--yes", "confirm the potentially expensive recalculation")
209
+ .action(
210
+ async function action(
211
+ this: Command,
212
+ schema: NormalizedUuidOrSlug,
213
+ commandOptions: ConfirmedCommandOptions,
214
+ ) {
215
+ await recompute(
216
+ this,
217
+ "formulas recompute schema",
218
+ { scope: "SCHEMA", schema },
219
+ options,
220
+ true,
221
+ commandOptions.yes,
222
+ );
223
+ },
224
+ );
225
+
226
+ recomputeCommand
227
+ .command("workspace")
228
+ .description("Queue recalculation of all active formulas in the workspace")
229
+ .option("--yes", "confirm the potentially expensive recalculation")
230
+ .action(async function action(
231
+ this: Command,
232
+ commandOptions: ConfirmedCommandOptions,
233
+ ) {
234
+ await recompute(
235
+ this,
236
+ "formulas recompute workspace",
237
+ { scope: "WORKSPACE" },
238
+ options,
239
+ true,
240
+ commandOptions.yes,
241
+ );
242
+ });
243
+ }
package/src/program.ts CHANGED
@@ -8,6 +8,7 @@ import { registerCommentsCommands } from "./commands/comments.js";
8
8
  import { registerDisplaysCommands } from "./commands/displays.js";
9
9
  import { registerDocumentTemplatesCommands } from "./commands/document-templates.js";
10
10
  import { registerFilesCommands } from "./commands/files.js";
11
+ import { registerFormulasCommands } from "./commands/formulas.js";
11
12
  import { registerLogsCommands } from "./commands/logs.js";
12
13
  import { registerNavigationCommands } from "./commands/navigation.js";
13
14
  import { registerProfilesCommands } from "./commands/profiles.js";
@@ -51,6 +52,7 @@ export function buildProgram(options: BuildProgramOptions = {}): Command {
51
52
  registerDisplaysCommands(program, options);
52
53
  registerDocumentTemplatesCommands(program, options);
53
54
  registerFilesCommands(program, options);
55
+ registerFormulasCommands(program, options);
54
56
  registerNavigationCommands(program, options);
55
57
  registerSchemasCommands(program, options);
56
58
  registerRecordsCommands(program, options);
@@ -27,6 +27,60 @@ export function buildCommandExamples(examples: readonly CommandExample[]): reado
27
27
  const SAMPLE_UUID = "550e8400-e29b-41d4-a716-446655440001";
28
28
 
29
29
  const specificExamples: Record<string, readonly CommandExample[]> = {
30
+ "formulas recompute field": buildCommandExamples([
31
+ {
32
+ description: "Queue a full recalculation of one formula column.",
33
+ command: "zinkee --json formulas recompute field invoices total",
34
+ raw: `{
35
+ "scope": "FIELD",
36
+ "schema": "invoices",
37
+ "field": "total"
38
+ }`,
39
+ response: `{
40
+ "requestId": "02ab5d47-cb5f-4eb2-afb8-e9a3a9eb34d4",
41
+ "scope": "FIELD",
42
+ "formulaCount": 1,
43
+ "skippedFormulaCount": 0,
44
+ "eventsQueued": 1,
45
+ "status": "QUEUED"
46
+ }`,
47
+ },
48
+ ]),
49
+ "formulas recompute schema": buildCommandExamples([
50
+ {
51
+ description: "Queue recalculation of every active formula in one schema.",
52
+ command: "zinkee --json formulas recompute schema invoices --yes",
53
+ raw: `{
54
+ "scope": "SCHEMA",
55
+ "schema": "invoices"
56
+ }`,
57
+ response: `{
58
+ "requestId": "02ab5d47-cb5f-4eb2-afb8-e9a3a9eb34d4",
59
+ "scope": "SCHEMA",
60
+ "formulaCount": 8,
61
+ "skippedFormulaCount": 1,
62
+ "eventsQueued": 8,
63
+ "status": "QUEUED"
64
+ }`,
65
+ },
66
+ ]),
67
+ "formulas recompute workspace": buildCommandExamples([
68
+ {
69
+ description: "Queue recalculation of every active formula in the workspace.",
70
+ command: "zinkee --json formulas recompute workspace --yes",
71
+ raw: `{
72
+ "scope": "WORKSPACE"
73
+ }`,
74
+ response: `{
75
+ "requestId": "02ab5d47-cb5f-4eb2-afb8-e9a3a9eb34d4",
76
+ "scope": "WORKSPACE",
77
+ "formulaCount": 24,
78
+ "skippedFormulaCount": 2,
79
+ "eventsQueued": 24,
80
+ "status": "QUEUED"
81
+ }`,
82
+ },
83
+ ]),
30
84
  "profiles list": buildCommandExamples([
31
85
  {
32
86
  description:
@@ -1,70 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Bash(npm test *)",
5
- "Bash(npm run *)",
6
- "Bash(pnpm typecheck *)",
7
- "Bash(pnpm test *)",
8
- "Bash(npx tsc *)",
9
- "Read(//home/guillermo/dev/z2-backend/api/src/main/java/com/zinkee/api/domain/model/v2/log/**)",
10
- "Read(//home/guillermo/dev/z2-backend/**)",
11
- "Bash(grep *)",
12
- "Bash(npx vitest *)",
13
- "Bash(npx tsx *)",
14
- "Bash(node dist/index.js --help)",
15
- "Bash(gh repo *)",
16
- "WebFetch(domain:github.com)",
17
- "Bash(git config *)",
18
- "Read(//home/guillermo/.config/**)",
19
- "Read(//home/guillermo/**)",
20
- "Bash(curl *)",
21
- "Bash(node dist/index.js --show-completion zsh)",
22
- "Bash(node *)",
23
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee\" COMP_CWORD=1 node *)",
24
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee schemas\" COMP_CWORD=2 node *)",
25
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee schemas fields\" COMP_CWORD=3 node dist/index.js)",
26
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee schemas fields cr\" COMP_CWORD=3 node dist/index.js)",
27
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee schemas list --j\" COMP_CWORD=3 node dist/index.js)",
28
- "Bash(rm -rf /tmp/zinkee-install)",
29
- "Bash(mkdir -p /tmp/zinkee-install)",
30
- "Bash(HOME=/tmp/zinkee-install SHELL=/bin/zsh node dist/index.js --install-completion)",
31
- "Read(//tmp/**)",
32
- "Read(//tmp/zinkee-install/**)",
33
- "Bash(rm -rf /tmp/zinkee-install-bash)",
34
- "Bash(mkdir -p /tmp/zinkee-install-bash)",
35
- "Bash(HOME=/tmp/zinkee-install-bash SHELL=/bin/bash node dist/index.js --install-completion)",
36
- "Bash(rm -rf /tmp/zinkee-install-fish)",
37
- "Bash(mkdir -p /tmp/zinkee-install-fish)",
38
- "Bash(_ZINKEE_COMPLETE=zsh_complete node dist/index.js)",
39
- "Bash(echo \"exit: $?\")",
40
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee schemas\" COMP_CWORD=abc node dist/index.js)",
41
- "Bash(_ZINKEE_COMPLETE=zsh_complete COMP_WORDS=\"zinkee config show --foo --bar baz quux ?\" COMP_CWORD=10 node dist/index.js)",
42
- "Bash(git -C /home/guillermo/dev/cli status)",
43
- "Bash(git -C /home/guillermo/dev/cli branch --show-current)",
44
- "Bash(git -C /home/guillermo/dev/cli diff --stat)",
45
- "Bash(git fetch *)",
46
- "Bash(pnpm exec *)",
47
- "Bash(echo \"=== exit $? \\(grep\\) ===\")",
48
- "Bash(grep -rn \"resourceType\" src/)",
49
- "Bash(grep -rn \"automation-folders/\\\\${\\\\|/automations:move\\\\|{folderId}/automations\" src/)",
50
- "Bash(grep -rn \"navigation resources move.*--type\\\\|resourceType\" docs/ README.md)",
51
- "Bash(zinkee --version)",
52
- "Bash(zinkee --json profiles list)",
53
- "Bash(zinkee displays *)",
54
- "Bash(chmod +x /tmp/audit_search.sh)",
55
- "Bash(/tmp/audit_search.sh)",
56
- "Bash(head -60 CLAUDE.md)",
57
- "Bash(head -40 AGENTS.md)",
58
- "Bash(xargs cat)",
59
- "Bash(./gradlew :api:test --tests \"com.zinkee.api.service.v2.data.DataV2TranslatorTest\" --tests \"com.zinkee.api.service.v2.data.DataV2ServiceTest\" --tests \"com.zinkee.api.domain.model.v2.data.DataV2PatchRecordRequestTest\")",
60
- "Bash(./gradlew :api:test --tests \"com.zinkee.api.service.v2.data.DataV2ServiceTest\" --tests \"com.zinkee.api.domain.model.v2.data.DataV2PatchRecordRequestTest\")",
61
- "Bash(./gradlew :api:spotlessApply)",
62
- "Bash(./gradlew :api:test :api:spotbugsMain spotlessCheck)",
63
- "Bash(./gradlew :api:spotbugsMain)",
64
- "Bash(./gradlew spotlessCheck)",
65
- "Bash(git --no-pager diff --stat)",
66
- "Bash(git --no-pager diff -- src/commands/records.ts src/api/records.ts)",
67
- "Bash(echo \"===EXIT: $?===\")"
68
- ]
69
- }
70
- }