@finopsbricks/fob-snap 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 +201 -0
- package/README.md +70 -0
- package/bin/cli.js +4 -0
- package/package.json +58 -0
- package/src/cli/_helpers.js +62 -0
- package/src/cli/_output.js +31 -0
- package/src/cli/config/index.js +83 -0
- package/src/cli/config-store.js +109 -0
- package/src/cli/dashboards/index.js +98 -0
- package/src/cli/getting-started.js +26 -0
- package/src/cli/index.js +55 -0
- package/src/cli/snapshots/index.js +71 -0
- package/src/cli/widgets/index.js +83 -0
- package/src/http.js +130 -0
- package/src/index.js +33 -0
- package/src/resources/dashboards.js +36 -0
- package/src/resources/snapshots.js +27 -0
- package/src/resources/widgets.js +21 -0
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 Derivative
|
|
95
|
+
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 2026 FinOpsBricks
|
|
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/README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# fob-snap
|
|
2
|
+
|
|
3
|
+
CLI + importable client for [Snapshots](https://snapshots.finopsbricks.com) — push versioned
|
|
4
|
+
snapshots and manage widgets/dashboards from the terminal or a script.
|
|
5
|
+
|
|
6
|
+
Snapshots is push-first: you POST a full, typed payload to a widget and it's stored as a new
|
|
7
|
+
immutable version. `fob-snap` makes that the one-liner it should be.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install -g @finopsbricks/fob-snap
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# 1. Save credentials (prompts for the secret if you omit --api-secret)
|
|
19
|
+
fob-snap config profiles add default --api-key fob_app_xxx
|
|
20
|
+
|
|
21
|
+
# 2. Create a widget
|
|
22
|
+
fob-snap widgets create --title "MRR" --type kpi
|
|
23
|
+
|
|
24
|
+
# 3. Push a snapshot — the whole point
|
|
25
|
+
fob-snap snapshots push <widget-id> --data '{"value":145000,"label":"MRR","unit":"$"}'
|
|
26
|
+
fob-snap snapshots push <widget-id> --data @payload.json --as-of 2026-01-31T00:00:00Z
|
|
27
|
+
|
|
28
|
+
# 4. Scrub the history
|
|
29
|
+
fob-snap snapshots list <widget-id>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Use a **Push Only** API key for push scripts. `--as-of` is the business time the data describes
|
|
33
|
+
(defaults to now); every push is a new version, never an overwrite.
|
|
34
|
+
|
|
35
|
+
## Commands
|
|
36
|
+
|
|
37
|
+
| Command | Description |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `config profiles add\|list\|use\|remove\|current` | Manage credential profiles (`~/.fob/fob-snap/config.yml`) |
|
|
40
|
+
| `snapshots push <widget> --data <json>` | Push a snapshot (full typed payload) |
|
|
41
|
+
| `snapshots list <widget>` | List a widget's versions, newest first |
|
|
42
|
+
| `widgets list\|show\|create\|delete` | Manage widgets |
|
|
43
|
+
| `dashboards list\|show\|create\|delete` | Manage dashboards |
|
|
44
|
+
| `dashboards add-widget\|remove-widget <dashboard> …` | Place / unplace widgets |
|
|
45
|
+
| `dashboards share\|unshare <dashboard>` | Create / revoke the public link |
|
|
46
|
+
|
|
47
|
+
`--profile <name>` selects a profile per-command; `--json` prints raw JSON on any read command.
|
|
48
|
+
`FOB_DEBUG=1` prints stack traces.
|
|
49
|
+
|
|
50
|
+
## As a library
|
|
51
|
+
|
|
52
|
+
The same client the CLI uses is importable — inject credentials, never read from env:
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
import { fobSnap } from '@finopsbricks/fob-snap';
|
|
56
|
+
|
|
57
|
+
const snap = fobSnap({ api_key, api_secret }); // api_url optional (hosted origin)
|
|
58
|
+
await snap.snapshots.push(widgetId, { data: { value: 145000 }, as_of: '2026-01-31T00:00:00Z' });
|
|
59
|
+
const { data: widgets } = await snap.widgets.list();
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Auth
|
|
63
|
+
|
|
64
|
+
Requests send `api-key` / `api-secret` headers. Create a key in the Snapshots app under
|
|
65
|
+
**Settings → API keys**; the **Push Only** preset grants exactly `snapshot:create` (+ read).
|
|
66
|
+
Widget/dashboard management needs a key with the matching `widget:*` / `dashboard:*` scopes.
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
Apache-2.0
|
package/bin/cli.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@finopsbricks/fob-snap",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Snapshots app client + fob-snap CLI (2-in-1). Import the client in workers, or use the CLI to push snapshots and manage widgets/dashboards.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js",
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"fob-snap": "./bin/cli.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"bin",
|
|
16
|
+
"src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"start": "node bin/cli.js",
|
|
22
|
+
"test": "node --experimental-vm-modules node_modules/.bin/jest",
|
|
23
|
+
"typecheck": "tsc -p jsconfig.json"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"snapshots",
|
|
27
|
+
"dashboards",
|
|
28
|
+
"push-metrics",
|
|
29
|
+
"api-client",
|
|
30
|
+
"cli",
|
|
31
|
+
"finops",
|
|
32
|
+
"finopsbricks"
|
|
33
|
+
],
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/finopsbricks/fob-snap.git"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/finopsbricks/fob-snap#readme",
|
|
43
|
+
"bugs": "https://github.com/finopsbricks/fob-snap/issues",
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@inquirer/prompts": "^7.10.1",
|
|
46
|
+
"commander": "^15.0.0",
|
|
47
|
+
"js-yaml": "^4.1.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@jest/globals": "^29.7.0",
|
|
51
|
+
"@types/node": "^22.20.1",
|
|
52
|
+
"jest": "^29.7.0",
|
|
53
|
+
"typescript": "^5.8.3"
|
|
54
|
+
},
|
|
55
|
+
"engines": {
|
|
56
|
+
"node": ">=18.0.0"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared CLI helpers: the `safe` handler adapter, `clientFor` (builds the authed
|
|
3
|
+
* client from the resolved profile), and small option builders.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { resolveCredentials } from './config-store.js';
|
|
7
|
+
import { fobSnap } from '../index.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Adapt a handler taking one merged `argv` to commander's `(…positionals, opts, cmd)`
|
|
11
|
+
* signature, with clean-exit behaviour on an unexpected throw (`FOB_DEBUG=1` for the stack).
|
|
12
|
+
* Positional names come from the command's declaration, camelised like option names.
|
|
13
|
+
*/
|
|
14
|
+
export function safe(handler) {
|
|
15
|
+
return async (...args) => {
|
|
16
|
+
const cmd = args[args.length - 1];
|
|
17
|
+
const opts = args[args.length - 2];
|
|
18
|
+
const positionals = args.slice(0, -2);
|
|
19
|
+
|
|
20
|
+
const argv = { ...opts };
|
|
21
|
+
const declared = cmd.registeredArguments ?? [];
|
|
22
|
+
declared.forEach((arg, i) => {
|
|
23
|
+
argv[toCamel(arg.name())] = positionals[i];
|
|
24
|
+
});
|
|
25
|
+
// Global options live on the root command — merge them down (leaf wins).
|
|
26
|
+
let parent = cmd.parent;
|
|
27
|
+
while (parent) {
|
|
28
|
+
Object.assign(argv, parent.opts(), argv);
|
|
29
|
+
parent = parent.parent;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
await handler(argv);
|
|
34
|
+
} catch (err) {
|
|
35
|
+
console.error(`Error: ${err.message}`);
|
|
36
|
+
if (err.details?.length) for (const d of err.details) console.error(` - ${d}`);
|
|
37
|
+
if (process.env.FOB_DEBUG) console.error(err.stack);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function toCamel(s) {
|
|
44
|
+
return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Build the authed Snapshots client from the current profile. */
|
|
48
|
+
export function clientFor() {
|
|
49
|
+
return fobSnap(resolveCredentials());
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Standard `--json` output flag. */
|
|
53
|
+
export function jsonOption(cmd) {
|
|
54
|
+
return cmd.option('--json', 'Output raw JSON');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Pagination + `--json` for list commands. */
|
|
58
|
+
export function listOptions(cmd) {
|
|
59
|
+
return jsonOption(cmd)
|
|
60
|
+
.option('--page <n>', 'Page number', Number, 1)
|
|
61
|
+
.option('--limit <n>', 'Page size (max 500)', Number, 100);
|
|
62
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Plain-text table + JSON output helpers for CLI commands. */
|
|
2
|
+
|
|
3
|
+
/** Pretty-print a value as indented JSON. */
|
|
4
|
+
export function printJson(value) {
|
|
5
|
+
console.log(JSON.stringify(value, null, 2));
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Render rows as an aligned text table.
|
|
10
|
+
* @param {Array<{ header: string, get: (row: any) => string }>} columns
|
|
11
|
+
* @param {any[]} rows
|
|
12
|
+
*/
|
|
13
|
+
export function printTable(columns, rows) {
|
|
14
|
+
if (!rows || rows.length === 0) {
|
|
15
|
+
console.log('(none)');
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const cells = rows.map((row) => columns.map((c) => String(c.get(row) ?? '')));
|
|
19
|
+
const widths = columns.map((c, i) => Math.max(c.header.length, ...cells.map((r) => r[i].length)));
|
|
20
|
+
const line = (arr) => arr.map((v, i) => v.padEnd(widths[i])).join(' ').trimEnd();
|
|
21
|
+
|
|
22
|
+
console.log(line(columns.map((c) => c.header)));
|
|
23
|
+
console.log(line(widths.map((w) => '-'.repeat(w))));
|
|
24
|
+
for (const r of cells) console.log(line(r));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Truncate a string for table display. */
|
|
28
|
+
export function trunc(v, n = 32) {
|
|
29
|
+
const s = v == null ? '' : String(v);
|
|
30
|
+
return s.length > n ? s.slice(0, n - 1) + '…' : s;
|
|
31
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fob-snap config profiles <action>` — manage credential profiles.
|
|
3
|
+
*
|
|
4
|
+
* A profile is a named `{ api_url, api_key, api_secret }` set stored in
|
|
5
|
+
* ~/.fob/fob-snap/config.yml. `add` takes flags, or prompts interactively for any
|
|
6
|
+
* missing credential (secret via a hidden prompt) — the `login` flow.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { Command } from 'commander';
|
|
10
|
+
import { input, password } from '@inquirer/prompts';
|
|
11
|
+
|
|
12
|
+
import { safe, jsonOption } from '../_helpers.js';
|
|
13
|
+
import { printJson, printTable } from '../_output.js';
|
|
14
|
+
import { DEFAULT_API_URL } from '../../http.js';
|
|
15
|
+
import {
|
|
16
|
+
addProfile, removeProfile, useProfile, listProfiles, describeCurrent,
|
|
17
|
+
} from '../config-store.js';
|
|
18
|
+
|
|
19
|
+
async function addHandler(argv) {
|
|
20
|
+
const api_url = argv.apiUrl || DEFAULT_API_URL;
|
|
21
|
+
const api_key = argv.apiKey || (await input({ message: 'API key:' }));
|
|
22
|
+
const api_secret = argv.apiSecret || (await password({ message: 'API secret:', mask: '*' }));
|
|
23
|
+
if (!api_key || !api_secret) throw new Error('Both an API key and secret are required.');
|
|
24
|
+
|
|
25
|
+
addProfile(argv.name, { api_url, api_key, api_secret });
|
|
26
|
+
console.log(`Saved Snapshots credentials for profile '${argv.name}' (${api_url}).`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function listHandler(argv) {
|
|
30
|
+
const { current, path, profiles } = listProfiles();
|
|
31
|
+
if (argv.json) return printJson({ current, profiles });
|
|
32
|
+
printTable(
|
|
33
|
+
[
|
|
34
|
+
{ header: '', get: (p) => (p.current ? '*' : ' ') },
|
|
35
|
+
{ header: 'PROFILE', get: (p) => p.name },
|
|
36
|
+
{ header: 'API URL', get: (p) => p.api_url },
|
|
37
|
+
],
|
|
38
|
+
profiles,
|
|
39
|
+
);
|
|
40
|
+
console.log(`\nConfig: ${path}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function useHandler(argv) {
|
|
44
|
+
useProfile(argv.name);
|
|
45
|
+
console.log(`Now using profile '${argv.name}'.`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function removeHandler(argv) {
|
|
49
|
+
removeProfile(argv.name);
|
|
50
|
+
console.log(`Removed profile '${argv.name}'.`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function currentHandler(argv) {
|
|
54
|
+
const cur = describeCurrent();
|
|
55
|
+
if (!cur) throw new Error('No profile selected. Run `fob-snap config profiles add <name>`.');
|
|
56
|
+
if (argv.json) return printJson(cur);
|
|
57
|
+
console.log(`Profile '${cur.name}' → ${cur.api_url}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function buildProfilesCommand() {
|
|
61
|
+
const profiles = new Command('profiles').alias('login').description('Manage credential profiles');
|
|
62
|
+
|
|
63
|
+
profiles
|
|
64
|
+
.command('add')
|
|
65
|
+
.description("Add or update a profile's credentials (prompts for any omitted secret)")
|
|
66
|
+
.argument('<name>', 'Profile name')
|
|
67
|
+
.option('--api-url <url>', `API base URL (origin only). Defaults to ${DEFAULT_API_URL}`, DEFAULT_API_URL)
|
|
68
|
+
.option('--api-key <key>', 'API key')
|
|
69
|
+
.option('--api-secret <secret>', 'API secret')
|
|
70
|
+
.action(safe(addHandler));
|
|
71
|
+
|
|
72
|
+
jsonOption(profiles.command('list').description('List profiles (current marked *)')).action(safe(listHandler));
|
|
73
|
+
jsonOption(profiles.command('current').alias('whoami').description('Show the active profile')).action(safe(currentHandler));
|
|
74
|
+
|
|
75
|
+
profiles.command('use').description('Set the current profile').argument('<name>', 'Profile name').action(safe(useHandler));
|
|
76
|
+
profiles.command('remove').alias('rm').description('Remove a profile').argument('<name>', 'Profile name').action(safe(removeHandler));
|
|
77
|
+
|
|
78
|
+
return profiles;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function buildConfigCommand() {
|
|
82
|
+
return new Command('config').description('Manage credential profiles').addCommand(buildProfilesCommand());
|
|
83
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI credential store — reads/writes ~/.fob/fob-snap/config.yml (mode 0600) and
|
|
3
|
+
* resolves which credentials the current command uses.
|
|
4
|
+
*
|
|
5
|
+
* Config lives under the shared family root ~/.fob/ so every fob-<tool> keeps its
|
|
6
|
+
* config in one place. Override the whole dir with FOB_SNAP_CONFIG_DIR.
|
|
7
|
+
*
|
|
8
|
+
* CLI-only: the importable client (src/index.js) never imports this. Handlers call
|
|
9
|
+
* resolveCredentials() and pass the result to client functions.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import yaml from 'js-yaml';
|
|
16
|
+
|
|
17
|
+
const CONFIG_DIR = process.env.FOB_SNAP_CONFIG_DIR || join(homedir(), '.fob', 'fob-snap');
|
|
18
|
+
const CONFIG_PATH = join(CONFIG_DIR, 'config.yml');
|
|
19
|
+
|
|
20
|
+
let profileOverride = null;
|
|
21
|
+
|
|
22
|
+
/** Set by the `--profile <name>` global flag (root preAction hook). Beats current_profile. */
|
|
23
|
+
export function setProfileOverride(name) {
|
|
24
|
+
profileOverride = name;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function loadConfig() {
|
|
28
|
+
if (existsSync(CONFIG_PATH)) {
|
|
29
|
+
const cfg = yaml.load(readFileSync(CONFIG_PATH, 'utf8')) || {};
|
|
30
|
+
return { current_profile: cfg.current_profile ?? null, profiles: cfg.profiles ?? {} };
|
|
31
|
+
}
|
|
32
|
+
return { current_profile: null, profiles: {} };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function saveConfig(cfg) {
|
|
36
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
37
|
+
writeFileSync(CONFIG_PATH, yaml.dump(cfg), { mode: 0o600 });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function addProfile(name, { api_url, api_key, api_secret }) {
|
|
41
|
+
const cfg = loadConfig();
|
|
42
|
+
cfg.profiles[name] = { api_url, api_key, api_secret };
|
|
43
|
+
if (!cfg.current_profile) cfg.current_profile = name;
|
|
44
|
+
saveConfig(cfg);
|
|
45
|
+
return cfg;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function removeProfile(name) {
|
|
49
|
+
const cfg = loadConfig();
|
|
50
|
+
if (!cfg.profiles[name]) throw new Error(`No profile named '${name}'.`);
|
|
51
|
+
delete cfg.profiles[name];
|
|
52
|
+
if (cfg.current_profile === name) cfg.current_profile = Object.keys(cfg.profiles)[0] ?? null;
|
|
53
|
+
saveConfig(cfg);
|
|
54
|
+
return cfg;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function useProfile(name) {
|
|
58
|
+
const cfg = loadConfig();
|
|
59
|
+
if (!cfg.profiles[name]) throw new Error(`No profile named '${name}'. Run \`fob-snap config profiles add ${name}\`.`);
|
|
60
|
+
cfg.current_profile = name;
|
|
61
|
+
saveConfig(cfg);
|
|
62
|
+
return cfg;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function configPath() {
|
|
66
|
+
return CONFIG_PATH;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Profiles for display — non-secret metadata only (name, current, api_url). */
|
|
70
|
+
export function listProfiles() {
|
|
71
|
+
const cfg = loadConfig();
|
|
72
|
+
const profiles = Object.entries(cfg.profiles).map(([name, p]) => ({
|
|
73
|
+
name,
|
|
74
|
+
current: name === cfg.current_profile,
|
|
75
|
+
api_url: p.api_url,
|
|
76
|
+
}));
|
|
77
|
+
return { current: cfg.current_profile, path: CONFIG_PATH, profiles };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Resolve credentials for the current command.
|
|
82
|
+
* Precedence: `--profile` override > config `current_profile`. Does not read env —
|
|
83
|
+
* an env var that silently overrode the active profile would be a footgun.
|
|
84
|
+
* @returns {{ api_url: string, api_key: string, api_secret: string, name: string }}
|
|
85
|
+
*/
|
|
86
|
+
export function resolveCredentials() {
|
|
87
|
+
const cfg = loadConfig();
|
|
88
|
+
const name = profileOverride || cfg.current_profile;
|
|
89
|
+
|
|
90
|
+
if (profileOverride && !cfg.profiles[profileOverride]) {
|
|
91
|
+
throw new Error(`Profile '${profileOverride}' is not configured. Run \`fob-snap config profiles add ${profileOverride}\`.`);
|
|
92
|
+
}
|
|
93
|
+
if (name && cfg.profiles[name]) {
|
|
94
|
+
return { ...cfg.profiles[name], name };
|
|
95
|
+
}
|
|
96
|
+
throw new Error(
|
|
97
|
+
'No Snapshots profile selected. Run `fob-snap config profiles add <name>`, then `use <name>` (or pass --profile <name>).',
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Non-secret description of the identity the CLI would use right now, or null. */
|
|
102
|
+
export function describeCurrent() {
|
|
103
|
+
try {
|
|
104
|
+
const { api_key, api_secret, ...rest } = resolveCredentials();
|
|
105
|
+
return rest;
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fob-snap dashboards <action>` — manage dashboards, placements, and share links.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { Command } from 'commander';
|
|
6
|
+
|
|
7
|
+
import { safe, listOptions, jsonOption, clientFor } from '../_helpers.js';
|
|
8
|
+
import { printJson, printTable, trunc } from '../_output.js';
|
|
9
|
+
|
|
10
|
+
async function listHandler(argv) {
|
|
11
|
+
const res = await clientFor().dashboards.list({ page: argv.page, limit: argv.limit });
|
|
12
|
+
if (argv.json) return printJson(res);
|
|
13
|
+
printTable(
|
|
14
|
+
[
|
|
15
|
+
{ header: 'ID', get: (d) => d.id },
|
|
16
|
+
{ header: 'TITLE', get: (d) => trunc(d.title, 40) },
|
|
17
|
+
{ header: 'CREATED', get: (d) => d.created_at },
|
|
18
|
+
],
|
|
19
|
+
res.data,
|
|
20
|
+
);
|
|
21
|
+
if (res.page_context) console.log(`\n${res.page_context.total} dashboard(s).`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function showHandler(argv) {
|
|
25
|
+
const client = clientFor();
|
|
26
|
+
const { data: dashboard } = await client.dashboards.get(argv.id);
|
|
27
|
+
const { data: placements } = await client.dashboards.listWidgets(argv.id);
|
|
28
|
+
printJson({ ...dashboard, widgets: placements });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function createHandler(argv) {
|
|
32
|
+
const { data: dashboard } = await clientFor().dashboards.create({ title: argv.title });
|
|
33
|
+
if (argv.json) return printJson(dashboard);
|
|
34
|
+
console.log(`Created dashboard '${dashboard.title}' → ${dashboard.id}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function deleteHandler(argv) {
|
|
38
|
+
await clientFor().dashboards.delete(argv.id);
|
|
39
|
+
console.log(`Deleted dashboard ${argv.id}.`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function addWidgetHandler(argv) {
|
|
43
|
+
const { data: placement } = await clientFor().dashboards.addWidget(argv.dashboard, { widget_id: argv.widget });
|
|
44
|
+
if (argv.json) return printJson(placement);
|
|
45
|
+
console.log(`Placed widget ${argv.widget} on dashboard ${argv.dashboard} (placement ${placement.id}).`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function removeWidgetHandler(argv) {
|
|
49
|
+
await clientFor().dashboards.removeWidget(argv.dashboard, argv.placement);
|
|
50
|
+
console.log(`Removed placement ${argv.placement} from dashboard ${argv.dashboard}.`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function shareHandler(argv) {
|
|
54
|
+
const { data: share } = await clientFor().dashboards.share(argv.id);
|
|
55
|
+
if (argv.json) return printJson(share);
|
|
56
|
+
console.log(`Public link: /s/${share.share_token}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function unshareHandler(argv) {
|
|
60
|
+
await clientFor().dashboards.unshare(argv.id);
|
|
61
|
+
console.log(`Revoked the public link for dashboard ${argv.id}.`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function buildDashboardsCommand() {
|
|
65
|
+
const dashboards = new Command('dashboards').alias('dashboard').description('Manage dashboards, placements, and share links');
|
|
66
|
+
|
|
67
|
+
listOptions(dashboards.command('list').description("List the org's dashboards")).action(safe(listHandler));
|
|
68
|
+
jsonOption(dashboards.command('show').description('Show a dashboard with its placements').argument('<id>', 'Dashboard id')).action(safe(showHandler));
|
|
69
|
+
|
|
70
|
+
dashboards
|
|
71
|
+
.command('create')
|
|
72
|
+
.description('Create a dashboard')
|
|
73
|
+
.requiredOption('--title <title>', 'Dashboard title')
|
|
74
|
+
.option('--json', 'Output raw JSON')
|
|
75
|
+
.action(safe(createHandler));
|
|
76
|
+
|
|
77
|
+
dashboards.command('delete').alias('rm').description('Delete a dashboard').argument('<id>', 'Dashboard id').action(safe(deleteHandler));
|
|
78
|
+
|
|
79
|
+
dashboards
|
|
80
|
+
.command('add-widget')
|
|
81
|
+
.description('Place a widget on a dashboard')
|
|
82
|
+
.argument('<dashboard>', 'Dashboard id')
|
|
83
|
+
.argument('<widget>', 'Widget id')
|
|
84
|
+
.option('--json', 'Output raw JSON')
|
|
85
|
+
.action(safe(addWidgetHandler));
|
|
86
|
+
|
|
87
|
+
dashboards
|
|
88
|
+
.command('remove-widget')
|
|
89
|
+
.description('Remove a placement from a dashboard')
|
|
90
|
+
.argument('<dashboard>', 'Dashboard id')
|
|
91
|
+
.argument('<placement>', 'Placement id (from `dashboards show`)')
|
|
92
|
+
.action(safe(removeWidgetHandler));
|
|
93
|
+
|
|
94
|
+
jsonOption(dashboards.command('share').description('Create/return the public share link').argument('<id>', 'Dashboard id')).action(safe(shareHandler));
|
|
95
|
+
dashboards.command('unshare').description('Revoke the public share link').argument('<id>', 'Dashboard id').action(safe(unshareHandler));
|
|
96
|
+
|
|
97
|
+
return dashboards;
|
|
98
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { describeCurrent } from './config-store.js';
|
|
2
|
+
import { DEFAULT_API_URL } from '../http.js';
|
|
3
|
+
|
|
4
|
+
export function gettingStartedHandler() {
|
|
5
|
+
const current = describeCurrent();
|
|
6
|
+
if (current) {
|
|
7
|
+
console.log(`You're set up — using profile '${current.name}' (${current.api_url}).\n`);
|
|
8
|
+
}
|
|
9
|
+
console.log(`fob-snap — push snapshots and manage widgets/dashboards from the terminal.
|
|
10
|
+
|
|
11
|
+
1. Add a profile (prompts for the secret):
|
|
12
|
+
fob-snap config profiles add default --api-key <KEY>
|
|
13
|
+
(api_url defaults to ${DEFAULT_API_URL}; use --api-url for self-hosted/staging.)
|
|
14
|
+
|
|
15
|
+
2. Create a widget:
|
|
16
|
+
fob-snap widgets create --title "MRR" --type kpi
|
|
17
|
+
|
|
18
|
+
3. Push a snapshot (the whole point):
|
|
19
|
+
fob-snap snapshots push <widget-id> --data '{"value":145000,"label":"MRR","unit":"$"}'
|
|
20
|
+
fob-snap snapshots push <widget-id> --data @payload.json --as-of 2026-01-31T00:00:00Z
|
|
21
|
+
|
|
22
|
+
4. Scrub the history:
|
|
23
|
+
fob-snap snapshots list <widget-id>
|
|
24
|
+
|
|
25
|
+
Every push is a new immutable version. Use a Push Only API key for push scripts.`);
|
|
26
|
+
}
|
package/src/cli/index.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI entry point — a three-level command tree:
|
|
3
|
+
*
|
|
4
|
+
* fob-snap <resource> <action> [target] [options]
|
|
5
|
+
*
|
|
6
|
+
* Credentials come from ~/.fob/fob-snap/config.yml; `config` manages profiles.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { dirname, join } from 'node:path';
|
|
12
|
+
|
|
13
|
+
import { Command } from 'commander';
|
|
14
|
+
|
|
15
|
+
import { setProfileOverride } from './config-store.js';
|
|
16
|
+
import { gettingStartedHandler } from './getting-started.js';
|
|
17
|
+
import { buildConfigCommand } from './config/index.js';
|
|
18
|
+
import { buildSnapshotsCommand } from './snapshots/index.js';
|
|
19
|
+
import { buildWidgetsCommand } from './widgets/index.js';
|
|
20
|
+
import { buildDashboardsCommand } from './dashboards/index.js';
|
|
21
|
+
|
|
22
|
+
function packageVersion() {
|
|
23
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
return JSON.parse(readFileSync(join(here, '..', '..', 'package.json'), 'utf8')).version;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function run(argv) {
|
|
28
|
+
const program = new Command();
|
|
29
|
+
|
|
30
|
+
program
|
|
31
|
+
.name('fob-snap')
|
|
32
|
+
.usage('<resource> <action> [target] [options]')
|
|
33
|
+
.description('Push snapshots and manage widgets/dashboards for Snapshots (snapshots.finopsbricks.com).')
|
|
34
|
+
.version(packageVersion(), '-v, --version', 'Show version number')
|
|
35
|
+
.option('--profile <name>', 'Use credentials from a specific configured profile')
|
|
36
|
+
.hook('preAction', (thisCommand) => {
|
|
37
|
+
const { profile } = thisCommand.opts();
|
|
38
|
+
if (profile) setProfileOverride(profile);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
program
|
|
42
|
+
.command('getting-started')
|
|
43
|
+
.description('Print setup instructions')
|
|
44
|
+
.action(gettingStartedHandler);
|
|
45
|
+
|
|
46
|
+
program
|
|
47
|
+
.addCommand(buildConfigCommand())
|
|
48
|
+
.addCommand(buildSnapshotsCommand())
|
|
49
|
+
.addCommand(buildWidgetsCommand())
|
|
50
|
+
.addCommand(buildDashboardsCommand())
|
|
51
|
+
.allowUnknownOption(false)
|
|
52
|
+
.showHelpAfterError();
|
|
53
|
+
|
|
54
|
+
program.parse(argv, { from: 'user' });
|
|
55
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fob-snap snapshots <action>` — push and list snapshot versions.
|
|
3
|
+
*
|
|
4
|
+
* `push` is the product's defining action: submit a FULL typed payload and it's
|
|
5
|
+
* stored as a new immutable version.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
import { Command } from 'commander';
|
|
10
|
+
|
|
11
|
+
import { safe, listOptions, clientFor } from '../_helpers.js';
|
|
12
|
+
import { printJson, printTable, trunc } from '../_output.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Parse a `--data` argument: `@path` reads a JSON file, otherwise the value is
|
|
16
|
+
* treated as an inline JSON string. Returns the parsed `data` payload.
|
|
17
|
+
*/
|
|
18
|
+
function parseData(arg) {
|
|
19
|
+
if (!arg) throw new Error('Provide the payload with --data <@file.json | inline-json>.');
|
|
20
|
+
const raw = arg.startsWith('@') ? readFileSync(arg.slice(1), 'utf8') : arg;
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(raw);
|
|
24
|
+
} catch (err) {
|
|
25
|
+
throw new Error(`--data is not valid JSON: ${err.message}`);
|
|
26
|
+
}
|
|
27
|
+
// Accept either the bare payload, or a full { data, as_of } envelope.
|
|
28
|
+
return parsed && typeof parsed === 'object' && 'data' in parsed ? parsed : { data: parsed };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function pushHandler(argv) {
|
|
32
|
+
const envelope = parseData(argv.data);
|
|
33
|
+
const body = { data: envelope.data, as_of: argv.asOf ?? envelope.as_of };
|
|
34
|
+
const { data: snapshot } = await clientFor().snapshots.push(argv.widget, body);
|
|
35
|
+
if (argv.json) return printJson(snapshot);
|
|
36
|
+
console.log(`Pushed v${snapshot.version} to ${snapshot.widget} (as of ${snapshot.as_of}).`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function listHandler(argv) {
|
|
40
|
+
const res = await clientFor().snapshots.list(argv.widget, { page: argv.page, limit: argv.limit });
|
|
41
|
+
if (argv.json) return printJson(res);
|
|
42
|
+
printTable(
|
|
43
|
+
[
|
|
44
|
+
{ header: 'VERSION', get: (s) => `v${s.version}` },
|
|
45
|
+
{ header: 'AS OF', get: (s) => s.as_of },
|
|
46
|
+
{ header: 'RECEIVED', get: (s) => s.received_at },
|
|
47
|
+
{ header: 'DATA', get: (s) => trunc(JSON.stringify(s.data), 40) },
|
|
48
|
+
],
|
|
49
|
+
res.data,
|
|
50
|
+
);
|
|
51
|
+
if (res.page_context) console.log(`\n${res.page_context.total} version(s).`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function buildSnapshotsCommand() {
|
|
55
|
+
const snapshots = new Command('snapshots').alias('snap').description('Push and list snapshot versions');
|
|
56
|
+
|
|
57
|
+
snapshots
|
|
58
|
+
.command('push')
|
|
59
|
+
.description('Push a snapshot (full typed payload) to a widget')
|
|
60
|
+
.argument('<widget>', 'Widget id')
|
|
61
|
+
.requiredOption('--data <json>', 'Payload as inline JSON or @file.json (bare payload, or { data, as_of })')
|
|
62
|
+
.option('--as-of <iso>', 'Business time this data describes (ISO 8601; defaults to now)')
|
|
63
|
+
.option('--json', 'Output raw JSON')
|
|
64
|
+
.action(safe(pushHandler));
|
|
65
|
+
|
|
66
|
+
listOptions(
|
|
67
|
+
snapshots.command('list').description("List a widget's versions, newest first").argument('<widget>', 'Widget id'),
|
|
68
|
+
).action(safe(listHandler));
|
|
69
|
+
|
|
70
|
+
return snapshots;
|
|
71
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fob-snap widgets <action>` — manage widgets over the REST API.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { Command } from 'commander';
|
|
7
|
+
|
|
8
|
+
import { safe, listOptions, jsonOption, clientFor } from '../_helpers.js';
|
|
9
|
+
import { printJson, printTable, trunc } from '../_output.js';
|
|
10
|
+
|
|
11
|
+
const WIDGET_TYPES = ['line', 'bar', 'area', 'kpi', 'table', 'pie'];
|
|
12
|
+
|
|
13
|
+
function parseConfig(arg) {
|
|
14
|
+
if (!arg) return undefined;
|
|
15
|
+
const raw = arg.startsWith('@') ? readFileSync(arg.slice(1), 'utf8') : arg;
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(raw);
|
|
18
|
+
} catch (err) {
|
|
19
|
+
throw new Error(`--config is not valid JSON: ${err.message}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function listHandler(argv) {
|
|
24
|
+
const res = await clientFor().widgets.list({ page: argv.page, limit: argv.limit });
|
|
25
|
+
if (argv.json) return printJson(res);
|
|
26
|
+
printTable(
|
|
27
|
+
[
|
|
28
|
+
{ header: 'ID', get: (w) => w.id },
|
|
29
|
+
{ header: 'TITLE', get: (w) => trunc(w.title, 32) },
|
|
30
|
+
{ header: 'TYPE', get: (w) => w.type },
|
|
31
|
+
{ header: 'RETENTION', get: (w) => (w.retention_days == null ? 'keep-all' : `${w.retention_days}d`) },
|
|
32
|
+
{ header: 'CREATED', get: (w) => w.created_at },
|
|
33
|
+
],
|
|
34
|
+
res.data,
|
|
35
|
+
);
|
|
36
|
+
if (res.page_context) console.log(`\n${res.page_context.total} widget(s).`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function showHandler(argv) {
|
|
40
|
+
const { data: widget } = await clientFor().widgets.get(argv.id);
|
|
41
|
+
printJson(widget);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function createHandler(argv) {
|
|
45
|
+
if (!WIDGET_TYPES.includes(argv.type)) {
|
|
46
|
+
throw new Error(`--type must be one of: ${WIDGET_TYPES.join(', ')}`);
|
|
47
|
+
}
|
|
48
|
+
const body = {
|
|
49
|
+
title: argv.title,
|
|
50
|
+
type: argv.type,
|
|
51
|
+
retention_days: argv.retentionDays === undefined ? null : Number(argv.retentionDays),
|
|
52
|
+
config: parseConfig(argv.config),
|
|
53
|
+
};
|
|
54
|
+
const { data: widget } = await clientFor().widgets.create(body);
|
|
55
|
+
if (argv.json) return printJson(widget);
|
|
56
|
+
console.log(`Created ${argv.type} widget '${widget.title}' → ${widget.id}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function deleteHandler(argv) {
|
|
60
|
+
await clientFor().widgets.delete(argv.id);
|
|
61
|
+
console.log(`Deleted widget ${argv.id}.`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function buildWidgetsCommand() {
|
|
65
|
+
const widgets = new Command('widgets').alias('widget').description('Manage widgets');
|
|
66
|
+
|
|
67
|
+
listOptions(widgets.command('list').description("List the org's widgets")).action(safe(listHandler));
|
|
68
|
+
jsonOption(widgets.command('show').description('Show one widget').argument('<id>', 'Widget id')).action(safe(showHandler));
|
|
69
|
+
|
|
70
|
+
widgets
|
|
71
|
+
.command('create')
|
|
72
|
+
.description('Create a widget')
|
|
73
|
+
.requiredOption('--title <title>', 'Widget title')
|
|
74
|
+
.requiredOption('--type <type>', `Widget type (${WIDGET_TYPES.join('|')})`)
|
|
75
|
+
.option('--retention-days <n>', 'Keep only the last N days of versions (default: keep all)')
|
|
76
|
+
.option('--config <json>', 'Visualization config as inline JSON or @file.json')
|
|
77
|
+
.option('--json', 'Output raw JSON')
|
|
78
|
+
.action(safe(createHandler));
|
|
79
|
+
|
|
80
|
+
widgets.command('delete').alias('rm').description('Delete a widget (snapshots cascade)').argument('<id>', 'Widget id').action(safe(deleteHandler));
|
|
81
|
+
|
|
82
|
+
return widgets;
|
|
83
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Snapshots API transport.
|
|
4
|
+
*
|
|
5
|
+
* PURE: credentials come from the `credentials` argument only — this module never
|
|
6
|
+
* reads `process.env` or the CLI config file. The CLI resolves creds from its config
|
|
7
|
+
* profiles and injects them; workers inject their own. (engineering-standards
|
|
8
|
+
* `no-ambient-configuration`.)
|
|
9
|
+
*
|
|
10
|
+
* Base URL is origin-only (e.g. https://snapshots.finopsbricks.com); the `/api/v1`
|
|
11
|
+
* prefix is carried in the paths passed by the resource layer.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {Object} Credentials
|
|
16
|
+
* @property {string} api_key
|
|
17
|
+
* @property {string} api_secret
|
|
18
|
+
* @property {string} [api_url] - origin only; defaults to the hosted endpoint
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Origin the client talks to when the caller doesn't supply `api_url`. */
|
|
22
|
+
export const DEFAULT_API_URL = 'https://snapshots.finopsbricks.com';
|
|
23
|
+
|
|
24
|
+
export class ApiError extends Error {
|
|
25
|
+
/**
|
|
26
|
+
* @param {string} message
|
|
27
|
+
* @param {{ code?: string, status?: number, details?: string[]|null }} [opts]
|
|
28
|
+
*/
|
|
29
|
+
constructor(message, { code, status, details } = {}) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = 'ApiError';
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.status = status;
|
|
34
|
+
this.details = details || null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {Credentials} credentials
|
|
40
|
+
* @returns {{ api_url: string, api_key: string, api_secret: string }}
|
|
41
|
+
*/
|
|
42
|
+
function resolveCreds(credentials) {
|
|
43
|
+
const api_url = credentials?.api_url ?? DEFAULT_API_URL;
|
|
44
|
+
const api_key = credentials?.api_key;
|
|
45
|
+
const api_secret = credentials?.api_secret;
|
|
46
|
+
if (!api_key || !api_secret) {
|
|
47
|
+
throw new ApiError(
|
|
48
|
+
`Missing Snapshots credentials: pass { api_key, api_secret } (api_url optional, defaults to ${DEFAULT_API_URL}).`,
|
|
49
|
+
{ code: 'NO_CREDENTIALS' },
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return { api_url, api_key, api_secret };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildUrl(baseUrl, path, searchParams) {
|
|
56
|
+
const base = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';
|
|
57
|
+
const url = new URL(path.replace(/^\//, ''), base);
|
|
58
|
+
if (searchParams) {
|
|
59
|
+
for (const [key, value] of Object.entries(searchParams)) {
|
|
60
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
61
|
+
url.searchParams.set(key, String(value));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return url;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {string} method
|
|
70
|
+
* @param {string} path
|
|
71
|
+
* @param {any} [body]
|
|
72
|
+
* @param {{ credentials: Credentials, searchParams?: Object }} options
|
|
73
|
+
*/
|
|
74
|
+
async function apiRequest(method, path, body, { credentials, searchParams } = /** @type {any} */ ({})) {
|
|
75
|
+
const creds = resolveCreds(credentials);
|
|
76
|
+
const url = buildUrl(creds.api_url, path, searchParams);
|
|
77
|
+
|
|
78
|
+
const headers = {
|
|
79
|
+
'api-key': creds.api_key,
|
|
80
|
+
'api-secret': creds.api_secret,
|
|
81
|
+
accept: 'application/json',
|
|
82
|
+
};
|
|
83
|
+
const init = { method, headers };
|
|
84
|
+
if (body !== undefined) {
|
|
85
|
+
headers['content-type'] = 'application/json';
|
|
86
|
+
init.body = JSON.stringify(body);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let response;
|
|
90
|
+
try {
|
|
91
|
+
response = await fetch(url, init);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
throw new ApiError(`Network error reaching ${url.origin}: ${err.message}`, { code: 'NETWORK_ERROR' });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const text = await response.text();
|
|
97
|
+
let respBody = null;
|
|
98
|
+
if (text) {
|
|
99
|
+
try {
|
|
100
|
+
respBody = JSON.parse(text);
|
|
101
|
+
} catch {
|
|
102
|
+
throw new ApiError(
|
|
103
|
+
`Invalid JSON response (status ${response.status}): ${text.slice(0, 200)}`,
|
|
104
|
+
{ code: 'INVALID_RESPONSE', status: response.status },
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (!response.ok) {
|
|
110
|
+
const code = respBody?.error?.code || 'HTTP_ERROR';
|
|
111
|
+
const message = respBody?.error?.message || `${response.status} ${response.statusText}`;
|
|
112
|
+
throw new ApiError(message, { code, status: response.status, details: respBody?.error?.details || null });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return respBody;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Bind credentials once and expose verb helpers. The resource layer builds on this,
|
|
120
|
+
* so every endpoint is defined once and the CLI and importable client can't drift.
|
|
121
|
+
* @param {Credentials} credentials
|
|
122
|
+
*/
|
|
123
|
+
export function createTransport(credentials) {
|
|
124
|
+
return {
|
|
125
|
+
get: (path, opts = {}) => apiRequest('GET', path, undefined, { credentials, ...opts }),
|
|
126
|
+
post: (path, body, opts = {}) => apiRequest('POST', path, body ?? {}, { credentials, ...opts }),
|
|
127
|
+
patch: (path, body, opts = {}) => apiRequest('PATCH', path, body ?? {}, { credentials, ...opts }),
|
|
128
|
+
delete: (path, opts = {}) => apiRequest('DELETE', path, undefined, { credentials, ...opts }),
|
|
129
|
+
};
|
|
130
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* @fob/snap — the importable Snapshots client.
|
|
4
|
+
*
|
|
5
|
+
* import { fobSnap } from '@finopsbricks/fob-snap';
|
|
6
|
+
* const snap = fobSnap({ api_key, api_secret }); // api_url optional (hosted origin)
|
|
7
|
+
* await snap.snapshots.push(widgetId, { data, as_of });
|
|
8
|
+
* const { data } = await snap.widgets.list();
|
|
9
|
+
*
|
|
10
|
+
* The `fob-snap` CLI builds the same client (see src/cli/_helpers.js `clientFor`) and
|
|
11
|
+
* calls these same namespaces, so the CLI and library can never drift: every endpoint
|
|
12
|
+
* is defined once, in src/resources/.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createTransport } from './http.js';
|
|
16
|
+
import { buildSnapshots } from './resources/snapshots.js';
|
|
17
|
+
import { buildWidgets } from './resources/widgets.js';
|
|
18
|
+
import { buildDashboards } from './resources/dashboards.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {import('./http.js').Credentials} credentials Required `{ api_key, api_secret }`;
|
|
22
|
+
* optional `api_url` (origin-only) overrides the hosted endpoint. Never read from env.
|
|
23
|
+
*/
|
|
24
|
+
export function fobSnap(credentials) {
|
|
25
|
+
const ctx = createTransport(credentials);
|
|
26
|
+
return {
|
|
27
|
+
snapshots: buildSnapshots(ctx),
|
|
28
|
+
widgets: buildWidgets(ctx),
|
|
29
|
+
dashboards: buildDashboards(ctx),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export { ApiError, createTransport, DEFAULT_API_URL } from './http.js';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/** Dashboards resource — CRUD + placements + share over /api/v1/dashboards. */
|
|
3
|
+
|
|
4
|
+
export function buildDashboards(ctx) {
|
|
5
|
+
return {
|
|
6
|
+
/** @param {{ page?: number, limit?: number }} [params] */
|
|
7
|
+
list: ({ page, limit } = {}) => ctx.get('/api/v1/dashboards', { searchParams: { page, limit } }),
|
|
8
|
+
|
|
9
|
+
/** @param {string} id */
|
|
10
|
+
get: (id) => ctx.get(`/api/v1/dashboards/${id}`),
|
|
11
|
+
|
|
12
|
+
/** @param {{ title: string }} body */
|
|
13
|
+
create: (body) => ctx.post('/api/v1/dashboards', body),
|
|
14
|
+
|
|
15
|
+
/** @param {string} id @param {{ title?: string, layout?: Object }} patch */
|
|
16
|
+
update: (id, patch) => ctx.patch(`/api/v1/dashboards/${id}`, patch),
|
|
17
|
+
|
|
18
|
+
/** @param {string} id */
|
|
19
|
+
delete: (id) => ctx.delete(`/api/v1/dashboards/${id}`),
|
|
20
|
+
|
|
21
|
+
/** List placements on a dashboard. @param {string} id */
|
|
22
|
+
listWidgets: (id) => ctx.get(`/api/v1/dashboards/${id}/widgets`),
|
|
23
|
+
|
|
24
|
+
/** Place a widget. @param {string} id @param {{ widget_id: string, position?: Object }} body */
|
|
25
|
+
addWidget: (id, body) => ctx.post(`/api/v1/dashboards/${id}/widgets`, body),
|
|
26
|
+
|
|
27
|
+
/** Remove a placement. @param {string} id @param {string} placementId */
|
|
28
|
+
removeWidget: (id, placementId) => ctx.delete(`/api/v1/dashboards/${id}/widgets/${placementId}`),
|
|
29
|
+
|
|
30
|
+
/** Create/return the public share link. @param {string} id */
|
|
31
|
+
share: (id) => ctx.post(`/api/v1/dashboards/${id}/share`, {}),
|
|
32
|
+
|
|
33
|
+
/** Revoke the public share link. @param {string} id */
|
|
34
|
+
unshare: (id) => ctx.delete(`/api/v1/dashboards/${id}/share`),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Snapshots resource — the product's defining endpoint (push, not pull).
|
|
4
|
+
* A push submits a FULL typed payload; it's stored as a new immutable version.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('../http.js').createTransport} Transport */
|
|
8
|
+
|
|
9
|
+
export function buildSnapshots(ctx) {
|
|
10
|
+
return {
|
|
11
|
+
/**
|
|
12
|
+
* Push a snapshot to a widget.
|
|
13
|
+
* @param {string} widgetId
|
|
14
|
+
* @param {{ data: Object, as_of?: string }} body
|
|
15
|
+
*/
|
|
16
|
+
push: (widgetId, { data, as_of } = /** @type {any} */ ({})) =>
|
|
17
|
+
ctx.post(`/api/v1/widgets/${widgetId}/snapshots`, { data, as_of }),
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* List a widget's snapshot versions, newest first.
|
|
21
|
+
* @param {string} widgetId
|
|
22
|
+
* @param {{ page?: number, limit?: number }} [params]
|
|
23
|
+
*/
|
|
24
|
+
list: (widgetId, { page, limit } = {}) =>
|
|
25
|
+
ctx.get(`/api/v1/widgets/${widgetId}/snapshots`, { searchParams: { page, limit } }),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/** Widgets resource — CRUD over /api/v1/widgets. */
|
|
3
|
+
|
|
4
|
+
export function buildWidgets(ctx) {
|
|
5
|
+
return {
|
|
6
|
+
/** @param {{ page?: number, limit?: number }} [params] */
|
|
7
|
+
list: ({ page, limit } = {}) => ctx.get('/api/v1/widgets', { searchParams: { page, limit } }),
|
|
8
|
+
|
|
9
|
+
/** @param {string} id */
|
|
10
|
+
get: (id) => ctx.get(`/api/v1/widgets/${id}`),
|
|
11
|
+
|
|
12
|
+
/** @param {{ title: string, type: string, retention_days?: number|null, config?: Object }} body */
|
|
13
|
+
create: (body) => ctx.post('/api/v1/widgets', body),
|
|
14
|
+
|
|
15
|
+
/** @param {string} id @param {{ title?: string, retention_days?: number|null, config?: Object }} patch */
|
|
16
|
+
update: (id, patch) => ctx.patch(`/api/v1/widgets/${id}`, patch),
|
|
17
|
+
|
|
18
|
+
/** @param {string} id */
|
|
19
|
+
delete: (id) => ctx.delete(`/api/v1/widgets/${id}`),
|
|
20
|
+
};
|
|
21
|
+
}
|