@wafflebase/cli 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { createProgram } from './commands/root.js';
3
+ import { registerDocumentCommand } from './commands/document.js';
4
+ import { registerTabCommand } from './commands/tab.js';
5
+ import { registerCellCommand } from './commands/cell.js';
6
+ import { registerApiKeyCommand } from './commands/api-key.js';
7
+ import { registerSchemaCommand } from './commands/schema.js';
8
+ const program = createProgram();
9
+ registerDocumentCommand(program);
10
+ registerTabCommand(program);
11
+ registerCellCommand(program);
12
+ registerApiKeyCommand(program);
13
+ registerSchemaCommand(program);
14
+ program.parse();
@@ -0,0 +1,5 @@
1
+ import type { CliConfig } from '../config/config.js';
2
+ /**
3
+ * Print the request that would be sent without executing it.
4
+ */
5
+ export declare function printDryRun(config: CliConfig, method: string, path: string, body?: unknown): void;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Print the request that would be sent without executing it.
3
+ */
4
+ export function printDryRun(config, method, path, body) {
5
+ const server = config.server.replace(/\/$/, '');
6
+ const url = `${server}/api/v1/workspaces/${config.workspace}${path}`;
7
+ const output = {
8
+ dry_run: true,
9
+ method,
10
+ url,
11
+ };
12
+ if (body !== undefined) {
13
+ output.body = body;
14
+ }
15
+ console.log(JSON.stringify(output, null, 2));
16
+ }
@@ -0,0 +1,49 @@
1
+ import type { CliConfig } from '../config/config.js';
2
+ export interface ApiResponse<T = unknown> {
3
+ ok: boolean;
4
+ status: number;
5
+ data: T;
6
+ }
7
+ export interface ApiError {
8
+ error: {
9
+ code: string;
10
+ message: string;
11
+ command?: string;
12
+ };
13
+ }
14
+ export declare class HttpClient {
15
+ private config;
16
+ constructor(config: CliConfig);
17
+ private get headers();
18
+ private get base();
19
+ request<T>(method: string, path: string, body?: unknown): Promise<ApiResponse<T>>;
20
+ listDocuments(): Promise<ApiResponse<unknown[]>>;
21
+ createDocument(title: string): Promise<ApiResponse<unknown>>;
22
+ getDocument(id: string): Promise<ApiResponse<unknown>>;
23
+ updateDocument(id: string, title: string): Promise<ApiResponse<unknown>>;
24
+ deleteDocument(id: string): Promise<ApiResponse<unknown>>;
25
+ listTabs(docId: string): Promise<ApiResponse<unknown[]>>;
26
+ getCells(docId: string, tabId: string, range?: string): Promise<ApiResponse<unknown>>;
27
+ getCell(docId: string, tabId: string, sref: string): Promise<ApiResponse<unknown>>;
28
+ setCell(docId: string, tabId: string, sref: string, value?: string, formula?: string): Promise<ApiResponse<unknown>>;
29
+ deleteCell(docId: string, tabId: string, sref: string): Promise<ApiResponse<unknown>>;
30
+ batchCells(docId: string, tabId: string, cells: Record<string, {
31
+ value?: string;
32
+ formula?: string;
33
+ } | null>): Promise<ApiResponse<unknown>>;
34
+ listApiKeys(): Promise<{
35
+ ok: boolean;
36
+ status: number;
37
+ data: unknown;
38
+ }>;
39
+ createApiKey(name: string): Promise<{
40
+ ok: boolean;
41
+ status: number;
42
+ data: unknown;
43
+ }>;
44
+ revokeApiKey(id: string): Promise<{
45
+ ok: boolean;
46
+ status: number;
47
+ data: unknown;
48
+ }>;
49
+ }
@@ -0,0 +1,92 @@
1
+ export class HttpClient {
2
+ config;
3
+ constructor(config) {
4
+ this.config = config;
5
+ }
6
+ get headers() {
7
+ return {
8
+ 'Content-Type': 'application/json',
9
+ Authorization: `Bearer ${this.config.apiKey}`,
10
+ };
11
+ }
12
+ get base() {
13
+ const server = this.config.server.replace(/\/$/, '');
14
+ return `${server}/api/v1/workspaces/${this.config.workspace}`;
15
+ }
16
+ async request(method, path, body) {
17
+ const url = `${this.base}${path}`;
18
+ const res = await fetch(url, {
19
+ method,
20
+ headers: this.headers,
21
+ body: body ? JSON.stringify(body) : undefined,
22
+ });
23
+ const data = (await res.json().catch(() => null));
24
+ return { ok: res.ok, status: res.status, data };
25
+ }
26
+ // Documents
27
+ listDocuments() {
28
+ return this.request('GET', '/documents');
29
+ }
30
+ createDocument(title) {
31
+ return this.request('POST', '/documents', { title });
32
+ }
33
+ getDocument(id) {
34
+ return this.request('GET', `/documents/${id}`);
35
+ }
36
+ updateDocument(id, title) {
37
+ return this.request('PATCH', `/documents/${id}`, { title });
38
+ }
39
+ deleteDocument(id) {
40
+ return this.request('DELETE', `/documents/${id}`);
41
+ }
42
+ // Tabs
43
+ listTabs(docId) {
44
+ return this.request('GET', `/documents/${docId}/tabs`);
45
+ }
46
+ // Cells
47
+ getCells(docId, tabId, range) {
48
+ const query = range ? `?range=${encodeURIComponent(range)}` : '';
49
+ return this.request('GET', `/documents/${docId}/tabs/${tabId}/cells${query}`);
50
+ }
51
+ getCell(docId, tabId, sref) {
52
+ return this.request('GET', `/documents/${docId}/tabs/${tabId}/cells/${sref}`);
53
+ }
54
+ setCell(docId, tabId, sref, value, formula) {
55
+ return this.request('PUT', `/documents/${docId}/tabs/${tabId}/cells/${sref}`, {
56
+ value,
57
+ formula,
58
+ });
59
+ }
60
+ deleteCell(docId, tabId, sref) {
61
+ return this.request('DELETE', `/documents/${docId}/tabs/${tabId}/cells/${sref}`);
62
+ }
63
+ batchCells(docId, tabId, cells) {
64
+ return this.request('PATCH', `/documents/${docId}/tabs/${tabId}/cells`, { cells });
65
+ }
66
+ // API Keys (management endpoints use different base)
67
+ async listApiKeys() {
68
+ const server = this.config.server.replace(/\/$/, '');
69
+ const url = `${server}/workspaces/${this.config.workspace}/api-keys`;
70
+ const res = await fetch(url, { headers: this.headers });
71
+ const data = await res.json().catch(() => null);
72
+ return { ok: res.ok, status: res.status, data };
73
+ }
74
+ async createApiKey(name) {
75
+ const server = this.config.server.replace(/\/$/, '');
76
+ const url = `${server}/workspaces/${this.config.workspace}/api-keys`;
77
+ const res = await fetch(url, {
78
+ method: 'POST',
79
+ headers: this.headers,
80
+ body: JSON.stringify({ name }),
81
+ });
82
+ const data = await res.json().catch(() => null);
83
+ return { ok: res.ok, status: res.status, data };
84
+ }
85
+ async revokeApiKey(id) {
86
+ const server = this.config.server.replace(/\/$/, '');
87
+ const url = `${server}/workspaces/${this.config.workspace}/api-keys/${id}`;
88
+ const res = await fetch(url, { method: 'DELETE', headers: this.headers });
89
+ const data = await res.json().catch(() => null);
90
+ return { ok: res.ok, status: res.status, data };
91
+ }
92
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function registerApiKeyCommand(program: Command): void;
@@ -0,0 +1,51 @@
1
+ import { getGlobalOpts, getClient } from './root.js';
2
+ import { output, outputError } from '../output/formatter.js';
3
+ export function registerApiKeyCommand(program) {
4
+ const apiKey = program.command('api-key').description('Manage API keys');
5
+ apiKey
6
+ .command('create <name>')
7
+ .description('Create a new API key')
8
+ .action(async function (name) {
9
+ const opts = getGlobalOpts(this);
10
+ try {
11
+ const res = await getClient(opts).createApiKey(name);
12
+ if (!res.ok)
13
+ throw new Error(`HTTP ${res.status}`);
14
+ // Never suppress output — the raw key is shown only once
15
+ output(res.data, opts.format, false);
16
+ }
17
+ catch (e) {
18
+ outputError(e, opts.quiet);
19
+ }
20
+ });
21
+ apiKey
22
+ .command('list')
23
+ .description('List API keys in workspace')
24
+ .action(async function () {
25
+ const opts = getGlobalOpts(this);
26
+ try {
27
+ const res = await getClient(opts).listApiKeys();
28
+ if (!res.ok)
29
+ throw new Error(`HTTP ${res.status}`);
30
+ output(res.data, opts.format, opts.quiet);
31
+ }
32
+ catch (e) {
33
+ outputError(e, opts.quiet);
34
+ }
35
+ });
36
+ apiKey
37
+ .command('revoke <key-id>')
38
+ .description('Revoke an API key')
39
+ .action(async function (keyId) {
40
+ const opts = getGlobalOpts(this);
41
+ try {
42
+ const res = await getClient(opts).revokeApiKey(keyId);
43
+ if (!res.ok)
44
+ throw new Error(`HTTP ${res.status}`);
45
+ output(res.data, opts.format, opts.quiet);
46
+ }
47
+ catch (e) {
48
+ outputError(e, opts.quiet);
49
+ }
50
+ });
51
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function registerCellCommand(program: Command): void;
@@ -0,0 +1,105 @@
1
+ import { getGlobalOpts, getClient, getConfig } from './root.js';
2
+ import { output, outputError } from '../output/formatter.js';
3
+ import { printDryRun } from '../client/dry-run.js';
4
+ export function registerCellCommand(program) {
5
+ const cell = program.command('cell').description('Read and write cells');
6
+ cell
7
+ .command('get <doc-id> [range]')
8
+ .description('Get cells (default: all, or A1, or A1:C10)')
9
+ .option('--tab <tab-id>', 'Tab ID', 'tab-1')
10
+ .action(async function (docId, range) {
11
+ const opts = getGlobalOpts(this);
12
+ const { tab } = this.opts();
13
+ try {
14
+ const res = range?.includes(':')
15
+ ? await getClient(opts).getCells(docId, tab, range)
16
+ : range
17
+ ? await getClient(opts).getCell(docId, tab, range)
18
+ : await getClient(opts).getCells(docId, tab);
19
+ if (!res.ok)
20
+ throw new Error(`HTTP ${res.status}`);
21
+ output(res.data, opts.format, opts.quiet);
22
+ }
23
+ catch (e) {
24
+ outputError(e, opts.quiet);
25
+ }
26
+ });
27
+ cell
28
+ .command('set <doc-id> <ref> <value>')
29
+ .description('Set a single cell value')
30
+ .option('--tab <tab-id>', 'Tab ID', 'tab-1')
31
+ .option('--formula', 'Treat value as a formula')
32
+ .action(async function (docId, ref, value) {
33
+ const opts = getGlobalOpts(this);
34
+ const { tab, formula } = this.opts();
35
+ const body = formula ? { formula: value } : { value };
36
+ if (opts.dryRun) {
37
+ printDryRun(getConfig(opts), 'PUT', `/documents/${docId}/tabs/${tab}/cells/${ref}`, body);
38
+ return;
39
+ }
40
+ try {
41
+ const res = await getClient(opts).setCell(docId, tab, ref, formula ? undefined : value, formula ? value : undefined);
42
+ if (!res.ok)
43
+ throw new Error(`HTTP ${res.status}`);
44
+ output(res.data, opts.format, opts.quiet);
45
+ }
46
+ catch (e) {
47
+ outputError(e, opts.quiet);
48
+ }
49
+ });
50
+ cell
51
+ .command('delete <doc-id> <ref>')
52
+ .description('Delete a single cell')
53
+ .option('--tab <tab-id>', 'Tab ID', 'tab-1')
54
+ .action(async function (docId, ref) {
55
+ const opts = getGlobalOpts(this);
56
+ const { tab } = this.opts();
57
+ if (opts.dryRun) {
58
+ printDryRun(getConfig(opts), 'DELETE', `/documents/${docId}/tabs/${tab}/cells/${ref}`);
59
+ return;
60
+ }
61
+ try {
62
+ const res = await getClient(opts).deleteCell(docId, tab, ref);
63
+ if (!res.ok)
64
+ throw new Error(`HTTP ${res.status}`);
65
+ output(res.data, opts.format, opts.quiet);
66
+ }
67
+ catch (e) {
68
+ outputError(e, opts.quiet);
69
+ }
70
+ });
71
+ cell
72
+ .command('batch <doc-id>')
73
+ .description('Batch update cells (JSON from stdin or --data)')
74
+ .option('--tab <tab-id>', 'Tab ID', 'tab-1')
75
+ .option('--data <json>', 'Cell data as JSON string')
76
+ .action(async function (docId) {
77
+ const opts = getGlobalOpts(this);
78
+ const { tab, data: dataStr } = this.opts();
79
+ let cells;
80
+ if (dataStr) {
81
+ cells = JSON.parse(dataStr);
82
+ }
83
+ else {
84
+ // Read from stdin
85
+ const chunks = [];
86
+ for await (const chunk of process.stdin) {
87
+ chunks.push(chunk);
88
+ }
89
+ cells = JSON.parse(Buffer.concat(chunks).toString('utf-8'));
90
+ }
91
+ if (opts.dryRun) {
92
+ printDryRun(getConfig(opts), 'PATCH', `/documents/${docId}/tabs/${tab}/cells`, { cells });
93
+ return;
94
+ }
95
+ try {
96
+ const res = await getClient(opts).batchCells(docId, tab, cells);
97
+ if (!res.ok)
98
+ throw new Error(`HTTP ${res.status}`);
99
+ output(res.data, opts.format, opts.quiet);
100
+ }
101
+ catch (e) {
102
+ outputError(e, opts.quiet);
103
+ }
104
+ });
105
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function registerDocumentCommand(program: Command): void;
@@ -0,0 +1,93 @@
1
+ import { getGlobalOpts, getClient, getConfig } from './root.js';
2
+ import { output, outputError } from '../output/formatter.js';
3
+ import { printDryRun } from '../client/dry-run.js';
4
+ export function registerDocumentCommand(program) {
5
+ const doc = program.command('document').alias('doc').description('Manage documents');
6
+ doc
7
+ .command('list')
8
+ .description('List documents in workspace')
9
+ .action(async function () {
10
+ const opts = getGlobalOpts(this);
11
+ try {
12
+ const res = await getClient(opts).listDocuments();
13
+ if (!res.ok)
14
+ throw new Error(`HTTP ${res.status}`);
15
+ output(res.data, opts.format, opts.quiet);
16
+ }
17
+ catch (e) {
18
+ outputError(e, opts.quiet);
19
+ }
20
+ });
21
+ doc
22
+ .command('create <title>')
23
+ .description('Create a new document')
24
+ .action(async function (title) {
25
+ const opts = getGlobalOpts(this);
26
+ if (opts.dryRun) {
27
+ printDryRun(getConfig(opts), 'POST', '/documents', { title });
28
+ return;
29
+ }
30
+ try {
31
+ const res = await getClient(opts).createDocument(title);
32
+ if (!res.ok)
33
+ throw new Error(`HTTP ${res.status}`);
34
+ output(res.data, opts.format, opts.quiet);
35
+ }
36
+ catch (e) {
37
+ outputError(e, opts.quiet);
38
+ }
39
+ });
40
+ doc
41
+ .command('get <doc-id>')
42
+ .description('Show document metadata')
43
+ .action(async function (docId) {
44
+ const opts = getGlobalOpts(this);
45
+ try {
46
+ const res = await getClient(opts).getDocument(docId);
47
+ if (!res.ok)
48
+ throw new Error(`HTTP ${res.status}`);
49
+ output(res.data, opts.format, opts.quiet);
50
+ }
51
+ catch (e) {
52
+ outputError(e, opts.quiet);
53
+ }
54
+ });
55
+ doc
56
+ .command('rename <doc-id> <title>')
57
+ .description('Rename a document')
58
+ .action(async function (docId, title) {
59
+ const opts = getGlobalOpts(this);
60
+ if (opts.dryRun) {
61
+ printDryRun(getConfig(opts), 'PATCH', `/documents/${docId}`, { title });
62
+ return;
63
+ }
64
+ try {
65
+ const res = await getClient(opts).updateDocument(docId, title);
66
+ if (!res.ok)
67
+ throw new Error(`HTTP ${res.status}`);
68
+ output(res.data, opts.format, opts.quiet);
69
+ }
70
+ catch (e) {
71
+ outputError(e, opts.quiet);
72
+ }
73
+ });
74
+ doc
75
+ .command('delete <doc-id>')
76
+ .description('Delete a document')
77
+ .action(async function (docId) {
78
+ const opts = getGlobalOpts(this);
79
+ if (opts.dryRun) {
80
+ printDryRun(getConfig(opts), 'DELETE', `/documents/${docId}`);
81
+ return;
82
+ }
83
+ try {
84
+ const res = await getClient(opts).deleteDocument(docId);
85
+ if (!res.ok)
86
+ throw new Error(`HTTP ${res.status}`);
87
+ output(res.data, opts.format, opts.quiet);
88
+ }
89
+ catch (e) {
90
+ outputError(e, opts.quiet);
91
+ }
92
+ });
93
+ }
@@ -0,0 +1,18 @@
1
+ import { Command } from 'commander';
2
+ import { type CliConfig } from '../config/config.js';
3
+ import { HttpClient } from '../client/http-client.js';
4
+ import type { OutputFormat } from '../output/formatter.js';
5
+ export interface GlobalOpts {
6
+ server?: string;
7
+ apiKey?: string;
8
+ workspace?: string;
9
+ profile?: string;
10
+ format: OutputFormat;
11
+ quiet: boolean;
12
+ verbose: boolean;
13
+ dryRun: boolean;
14
+ }
15
+ export declare function getGlobalOpts(cmd: Command): GlobalOpts;
16
+ export declare function getConfig(opts: GlobalOpts): CliConfig;
17
+ export declare function getClient(opts: GlobalOpts): HttpClient;
18
+ export declare function createProgram(): Command;
@@ -0,0 +1,34 @@
1
+ import { Command } from 'commander';
2
+ import { resolveConfig } from '../config/config.js';
3
+ import { HttpClient } from '../client/http-client.js';
4
+ export function getGlobalOpts(cmd) {
5
+ const root = cmd.optsWithGlobals();
6
+ return root;
7
+ }
8
+ export function getConfig(opts) {
9
+ return resolveConfig({
10
+ server: opts.server,
11
+ apiKey: opts.apiKey,
12
+ workspace: opts.workspace,
13
+ profile: opts.profile,
14
+ });
15
+ }
16
+ export function getClient(opts) {
17
+ return new HttpClient(getConfig(opts));
18
+ }
19
+ export function createProgram() {
20
+ const program = new Command();
21
+ program
22
+ .name('wafflebase')
23
+ .description('CLI for Wafflebase spreadsheet API')
24
+ .version('0.1.0')
25
+ .option('--server <url>', 'Server URL')
26
+ .option('--api-key <key>', 'API key')
27
+ .option('--workspace <id>', 'Workspace ID')
28
+ .option('--profile <name>', 'Config profile', 'default')
29
+ .option('--format <fmt>', 'Output format (json, table, csv)', 'json')
30
+ .option('--quiet', 'Suppress output', false)
31
+ .option('--verbose', 'Verbose output', false)
32
+ .option('--dry-run', 'Show request without executing', false);
33
+ return program;
34
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function registerSchemaCommand(program: Command): void;
@@ -0,0 +1,28 @@
1
+ import { getGlobalOpts } from './root.js';
2
+ import { output } from '../output/formatter.js';
3
+ import { getCommandSchema, getAllCommandSchemas } from '../schema/registry.js';
4
+ export function registerSchemaCommand(program) {
5
+ program
6
+ .command('schema [command]')
7
+ .description('Describe command parameters and response shape')
8
+ .action(function (commandName) {
9
+ const opts = getGlobalOpts(this);
10
+ if (commandName) {
11
+ const schema = getCommandSchema(commandName);
12
+ if (!schema) {
13
+ console.error(JSON.stringify({ error: { code: 'NOT_FOUND', message: `Unknown command: ${commandName}` } }, null, 2));
14
+ process.exitCode = 1;
15
+ return;
16
+ }
17
+ output(schema, opts.format, opts.quiet);
18
+ }
19
+ else {
20
+ const commands = getAllCommandSchemas().map((c) => ({
21
+ name: c.name,
22
+ description: c.description,
23
+ safety: c.safety,
24
+ }));
25
+ output({ commands }, opts.format, opts.quiet);
26
+ }
27
+ });
28
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function registerTabCommand(program: Command): void;
@@ -0,0 +1,20 @@
1
+ import { getGlobalOpts, getClient } from './root.js';
2
+ import { output, outputError } from '../output/formatter.js';
3
+ export function registerTabCommand(program) {
4
+ const tab = program.command('tab').description('Manage tabs');
5
+ tab
6
+ .command('list <doc-id>')
7
+ .description('List tabs in a document')
8
+ .action(async function (docId) {
9
+ const opts = getGlobalOpts(this);
10
+ try {
11
+ const res = await getClient(opts).listTabs(docId);
12
+ if (!res.ok)
13
+ throw new Error(`HTTP ${res.status}`);
14
+ output(res.data, opts.format, opts.quiet);
15
+ }
16
+ catch (e) {
17
+ outputError(e, opts.quiet);
18
+ }
19
+ });
20
+ }
@@ -0,0 +1,14 @@
1
+ export interface CliConfig {
2
+ server: string;
3
+ apiKey: string;
4
+ workspace: string;
5
+ }
6
+ /**
7
+ * Resolve CLI configuration from flags > env > config file.
8
+ */
9
+ export declare function resolveConfig(flags: {
10
+ server?: string;
11
+ apiKey?: string;
12
+ workspace?: string;
13
+ profile?: string;
14
+ }): CliConfig;
@@ -0,0 +1,41 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { parse as parseYaml } from 'yaml';
5
+ /**
6
+ * Resolve CLI configuration from flags > env > config file.
7
+ */
8
+ export function resolveConfig(flags) {
9
+ const profile = loadProfile(flags.profile ?? 'default');
10
+ return {
11
+ server: flags.server ??
12
+ process.env.WAFFLEBASE_SERVER ??
13
+ profile.server ??
14
+ 'http://localhost:3000',
15
+ apiKey: flags.apiKey ??
16
+ process.env.WAFFLEBASE_API_KEY ??
17
+ profile['api-key'] ??
18
+ '',
19
+ workspace: flags.workspace ??
20
+ process.env.WAFFLEBASE_WORKSPACE ??
21
+ profile.workspace ??
22
+ '',
23
+ };
24
+ }
25
+ function getConfigPath() {
26
+ return (process.env.WAFFLEBASE_CONFIG ??
27
+ join(homedir(), '.config', 'wafflebase', 'config.yaml'));
28
+ }
29
+ function loadProfile(name) {
30
+ const configPath = getConfigPath();
31
+ if (!existsSync(configPath))
32
+ return {};
33
+ try {
34
+ const raw = readFileSync(configPath, 'utf-8');
35
+ const config = parseYaml(raw);
36
+ return config?.profiles?.[name] ?? {};
37
+ }
38
+ catch {
39
+ return {};
40
+ }
41
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Format data as CSV. Accepts arrays or single objects.
3
+ */
4
+ export declare function formatCsv(data: unknown): string;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Format data as CSV. Accepts arrays or single objects.
3
+ */
4
+ export function formatCsv(data) {
5
+ const rows = Array.isArray(data)
6
+ ? data
7
+ : data !== null && typeof data === 'object'
8
+ ? [data]
9
+ : [];
10
+ if (rows.length === 0)
11
+ return '';
12
+ const keys = Object.keys(rows[0]);
13
+ const csvEscape = (val) => {
14
+ const s = val !== null && typeof val === 'object'
15
+ ? JSON.stringify(val)
16
+ : String(val ?? '');
17
+ if (s.includes(',') || s.includes('"') || s.includes('\n')) {
18
+ return `"${s.replace(/"/g, '""')}"`;
19
+ }
20
+ return s;
21
+ };
22
+ const header = keys.map(csvEscape).join(',');
23
+ const lines = rows.map((row) => keys.map((k) => csvEscape(row[k])).join(','));
24
+ return [header, ...lines].join('\n');
25
+ }
@@ -0,0 +1,4 @@
1
+ export type OutputFormat = 'json' | 'table' | 'csv';
2
+ export declare function format(data: unknown, fmt: OutputFormat): string;
3
+ export declare function output(data: unknown, fmt: OutputFormat, quiet: boolean): void;
4
+ export declare function outputError(error: unknown, quiet: boolean): void;
@@ -0,0 +1,27 @@
1
+ import { formatJson } from './json.js';
2
+ import { formatTable } from './table.js';
3
+ import { formatCsv } from './csv.js';
4
+ export function format(data, fmt) {
5
+ switch (fmt) {
6
+ case 'json':
7
+ return formatJson(data);
8
+ case 'table':
9
+ return formatTable(data);
10
+ case 'csv':
11
+ return formatCsv(data);
12
+ }
13
+ }
14
+ export function output(data, fmt, quiet) {
15
+ if (quiet)
16
+ return;
17
+ console.log(format(data, fmt));
18
+ }
19
+ export function outputError(error, quiet) {
20
+ if (quiet) {
21
+ process.exitCode = 1;
22
+ return;
23
+ }
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ console.error(JSON.stringify({ error: { code: 'ERROR', message } }, null, 2));
26
+ process.exitCode = 1;
27
+ }
@@ -0,0 +1 @@
1
+ export declare function formatJson(data: unknown): string;
@@ -0,0 +1,3 @@
1
+ export function formatJson(data) {
2
+ return JSON.stringify(data, null, 2);
3
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Format an array of objects as an aligned text table.
3
+ */
4
+ export declare function formatTable(data: unknown): string;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Format an array of objects as an aligned text table.
3
+ */
4
+ export function formatTable(data) {
5
+ if (!Array.isArray(data) || data.length === 0)
6
+ return '(no results)';
7
+ const rows = data;
8
+ const keys = Object.keys(rows[0]);
9
+ const widths = keys.map((key) => Math.max(key.length, ...rows.map((row) => String(row[key] ?? '').length)));
10
+ const header = keys.map((k, i) => k.padEnd(widths[i])).join(' ');
11
+ const separator = widths.map((w) => '-'.repeat(w)).join(' ');
12
+ const lines = rows.map((row) => keys.map((k, i) => String(row[k] ?? '').padEnd(widths[i])).join(' '));
13
+ return [header, separator, ...lines].join('\n');
14
+ }
@@ -0,0 +1,15 @@
1
+ export type SafetyLevel = 'read-only' | 'write' | 'destructive';
2
+ export interface CommandSchema {
3
+ name: string;
4
+ description: string;
5
+ safety: SafetyLevel;
6
+ parameters: Record<string, {
7
+ type: string;
8
+ required: boolean;
9
+ description: string;
10
+ default?: string;
11
+ }>;
12
+ response: Record<string, unknown>;
13
+ }
14
+ export declare function getCommandSchema(name: string): CommandSchema | undefined;
15
+ export declare function getAllCommandSchemas(): CommandSchema[];
@@ -0,0 +1,134 @@
1
+ const registry = [
2
+ {
3
+ name: 'doc.list',
4
+ description: 'List documents in workspace',
5
+ safety: 'read-only',
6
+ parameters: {},
7
+ response: { type: 'array', items: { id: 'string', title: 'string', createdAt: 'string' } },
8
+ },
9
+ {
10
+ name: 'doc.create',
11
+ description: 'Create a new document',
12
+ safety: 'write',
13
+ parameters: {
14
+ title: { type: 'string', required: true, description: 'Document title' },
15
+ },
16
+ response: { id: 'string', title: 'string' },
17
+ },
18
+ {
19
+ name: 'doc.get',
20
+ description: 'Show document metadata',
21
+ safety: 'read-only',
22
+ parameters: {
23
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
24
+ },
25
+ response: { id: 'string', title: 'string', createdAt: 'string' },
26
+ },
27
+ {
28
+ name: 'doc.rename',
29
+ description: 'Rename a document',
30
+ safety: 'write',
31
+ parameters: {
32
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
33
+ title: { type: 'string', required: true, description: 'New title' },
34
+ },
35
+ response: { id: 'string', title: 'string' },
36
+ },
37
+ {
38
+ name: 'doc.delete',
39
+ description: 'Delete a document',
40
+ safety: 'destructive',
41
+ parameters: {
42
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
43
+ },
44
+ response: { id: 'string' },
45
+ },
46
+ {
47
+ name: 'tab.list',
48
+ description: 'List tabs in a document',
49
+ safety: 'read-only',
50
+ parameters: {
51
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
52
+ },
53
+ response: { type: 'array', items: { id: 'string', name: 'string', type: 'string' } },
54
+ },
55
+ {
56
+ name: 'cell.get',
57
+ description: 'Get cells from a spreadsheet tab',
58
+ safety: 'read-only',
59
+ parameters: {
60
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
61
+ range: { type: 'string', required: false, description: 'Cell range (e.g. A1:C10)', default: 'all' },
62
+ '--tab': { type: 'string', required: false, description: 'Tab ID', default: 'tab-1' },
63
+ },
64
+ response: {
65
+ type: 'array',
66
+ items: { ref: 'string', value: 'string | null', formula: 'string | null', style: 'object | null' },
67
+ },
68
+ },
69
+ {
70
+ name: 'cell.set',
71
+ description: 'Set a single cell value',
72
+ safety: 'write',
73
+ parameters: {
74
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
75
+ ref: { type: 'string', required: true, description: 'Cell reference (e.g. A1)' },
76
+ value: { type: 'string', required: true, description: 'Cell value or formula' },
77
+ '--tab': { type: 'string', required: false, description: 'Tab ID', default: 'tab-1' },
78
+ },
79
+ response: { ref: 'string', value: 'string', formula: 'string | null' },
80
+ },
81
+ {
82
+ name: 'cell.batch',
83
+ description: 'Batch update cells',
84
+ safety: 'write',
85
+ parameters: {
86
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
87
+ '--tab': { type: 'string', required: false, description: 'Tab ID', default: 'tab-1' },
88
+ '--data': { type: 'string', required: false, description: 'JSON data (or pipe from stdin)' },
89
+ },
90
+ response: { updated: 'number' },
91
+ },
92
+ {
93
+ name: 'cell.delete',
94
+ description: 'Delete a single cell',
95
+ safety: 'destructive',
96
+ parameters: {
97
+ 'doc-id': { type: 'string', required: true, description: 'Document ID' },
98
+ ref: { type: 'string', required: true, description: 'Cell reference' },
99
+ '--tab': { type: 'string', required: false, description: 'Tab ID', default: 'tab-1' },
100
+ },
101
+ response: { ref: 'string', deleted: 'boolean' },
102
+ },
103
+ {
104
+ name: 'api-key.create',
105
+ description: 'Create a new API key',
106
+ safety: 'write',
107
+ parameters: {
108
+ name: { type: 'string', required: true, description: 'Key name' },
109
+ },
110
+ response: { id: 'string', name: 'string', prefix: 'string', key: 'string' },
111
+ },
112
+ {
113
+ name: 'api-key.list',
114
+ description: 'List API keys in workspace',
115
+ safety: 'read-only',
116
+ parameters: {},
117
+ response: { type: 'array', items: { id: 'string', name: 'string', prefix: 'string' } },
118
+ },
119
+ {
120
+ name: 'api-key.revoke',
121
+ description: 'Revoke an API key',
122
+ safety: 'destructive',
123
+ parameters: {
124
+ 'key-id': { type: 'string', required: true, description: 'API key ID' },
125
+ },
126
+ response: { id: 'string' },
127
+ },
128
+ ];
129
+ export function getCommandSchema(name) {
130
+ return registry.find((c) => c.name === name);
131
+ }
132
+ export function getAllCommandSchemas() {
133
+ return registry;
134
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@wafflebase/cli",
3
+ "version": "0.1.0",
4
+ "description": "CLI for Wafflebase spreadsheet API",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "wafflebase": "./dist/bin.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "dependencies": {
14
+ "commander": "^13.0.0",
15
+ "yaml": "^2.0.0"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^25.4.0",
19
+ "eslint": "^9.18.0",
20
+ "tsx": "^4.19.0",
21
+ "typescript": "^5.7.3",
22
+ "vitest": "^3.1.0"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "dev": "tsx src/bin.ts",
27
+ "test": "vitest --run",
28
+ "test:watch": "vitest",
29
+ "lint:check": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
30
+ "typecheck": "tsc --noEmit"
31
+ }
32
+ }