@manajemin-dev-cli/cli 0.0.0-stage → 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/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Manajemin developer tools
2
+ Copyright 2026 PT Manajemin Aksi Jejaring Usaha
3
+
4
+ This product includes software developed by PT Manajemin Aksi Jejaring Usaha (https://www.manajemin.com).
package/README.md CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # @manajemin-dev-cli/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `manajemin` command for developers. It acts in your developer organisation's **sandbox** only, through the platform's
4
+ developer MCP server: it cannot approve an app, reach production, or read a webhook secret or an app key.
5
+
6
+ ```sh
7
+ manajemin login # paste a developer API token from the developer portal (input is hidden)
8
+ manajemin init --id my-tasks
9
+ manajemin validate # no token needed; never contacts the URLs in your manifest
10
+ manajemin apply # registers the app in your sandbox as pending_review
11
+ manajemin trigger my-tasks
12
+ manajemin check my-tasks # the Connection check, step by step, with the first failure to fix
13
+ manajemin logs my-tasks
14
+ ```
15
+
16
+ The token is stored in `~/.config/manajemin/credentials.json`, readable only by you, and never printed. In CI set
17
+ `MANAJEMIN_TOKEN` instead. `MANAJEMIN_URL` points the CLI at another gate (default `https://www.manajemin.com`).
18
+
19
+ Not yet: a browser sign-in (device flow) instead of pasting a token, and `manajemin dev` with a tunnel to your machine.
package/commands.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export declare const DEFAULT_BASE_URL = "https://www.manajemin.com";
2
+ export interface Io {
3
+ out(line: string): void;
4
+ err(line: string): void;
5
+ /** Asks without echoing; null when there is no terminal. */
6
+ secret(prompt: string): Promise<string | null>;
7
+ token: () => string | null;
8
+ saveToken: (token: string) => string;
9
+ deleteToken: () => boolean;
10
+ baseUrl: string;
11
+ fetch?: typeof fetch;
12
+ cwd: string;
13
+ /** Waits; replaced in tests so a poll loop runs at once. */
14
+ sleep?: (ms: number) => Promise<void>;
15
+ /** Ends `dev` (Ctrl-C in the real CLI). */
16
+ signal?: AbortSignal;
17
+ }
18
+ export declare const HELP = "manajemin: the Manajemin developer CLI\n\n manajemin login store a developer API token (create one in the developer portal)\n manajemin login --device sign in through the browser: the CLI shows a code, you approve it in the portal\n manajemin dev [file] watch manifest.json: validate and apply on every save, and print deliveries as they arrive\n manajemin logout forget it\n manajemin init [--id <app id>] write manifest.json from the published example\n manajemin validate [file] check a manifest (no token needed; never contacts your URLs)\n manajemin apply [file] register it in your sandbox, as pending_review\n manajemin apps list your organisation's apps\n manajemin check <app id> run the Connection check against your server\n manajemin review <app id> run the automated review (exits 1 when it wants fixes; it approves nothing)\n manajemin trigger <app id> send yourself a signed app.test_event\n manajemin simulate <app id> <scenario> lifecycle, duplicate, out_of_order, unknown_event, bad_signature or stale_timestamp\n manajemin replay <app id> <delivery id> [--same-id] send a delivery from your sandbox log again\n manajemin health <app id> the last 30 days of probes and the last week's deliveries\n manajemin logs <app id> [--limit n]\n manajemin db status your managed databases, the price and this month's draft (never a connection)\n manajemin db create <app id> --region aws-eu-central-1|aws-us-west-2 create the app's sandbox database (synthetic data only)\n manajemin db delete <app id> delete it and everything in it (asks you to repeat the app id with --confirm <app id>)\n\n MANAJEMIN_TOKEN overrides the stored token (for CI). MANAJEMIN_URL points at another gate (default https://www.manajemin.com).\n The CLI acts in your sandbox only: it cannot approve an app, reach production, or read a secret, an app key or a database connection\n (a connection is shown once in the developer portal, which can make a new one at any time).";
19
+ export declare function run(argv: string[], io: Io): Promise<number>;
package/commands.js ADDED
@@ -0,0 +1,350 @@
1
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { callTool, McpError } from "./mcp.js";
3
+ export const DEFAULT_BASE_URL = "https://www.manajemin.com";
4
+ const TOKEN_SHAPE = /^mjd_[0-9a-f]{12}\.[0-9a-f]{64}$/;
5
+ const mcpOf = (io, token) => ({ baseUrl: io.baseUrl, token, fetch: io.fetch });
6
+ const pause = (io, ms) => (io.sleep ?? ((n) => new Promise((resolve) => setTimeout(resolve, n))))(ms);
7
+ export const HELP = `manajemin: the Manajemin developer CLI
8
+
9
+ manajemin login store a developer API token (create one in the developer portal)
10
+ manajemin login --device sign in through the browser: the CLI shows a code, you approve it in the portal
11
+ manajemin dev [file] watch manifest.json: validate and apply on every save, and print deliveries as they arrive
12
+ manajemin logout forget it
13
+ manajemin init [--id <app id>] write manifest.json from the published example
14
+ manajemin validate [file] check a manifest (no token needed; never contacts your URLs)
15
+ manajemin apply [file] register it in your sandbox, as pending_review
16
+ manajemin apps list your organisation's apps
17
+ manajemin check <app id> run the Connection check against your server
18
+ manajemin review <app id> run the automated review (exits 1 when it wants fixes; it approves nothing)
19
+ manajemin trigger <app id> send yourself a signed app.test_event
20
+ manajemin simulate <app id> <scenario> lifecycle, duplicate, out_of_order, unknown_event, bad_signature or stale_timestamp
21
+ manajemin replay <app id> <delivery id> [--same-id] send a delivery from your sandbox log again
22
+ manajemin health <app id> the last 30 days of probes and the last week's deliveries
23
+ manajemin logs <app id> [--limit n]
24
+ manajemin db status your managed databases, the price and this month's draft (never a connection)
25
+ manajemin db create <app id> --region aws-eu-central-1|aws-us-west-2 create the app's sandbox database (synthetic data only)
26
+ manajemin db delete <app id> delete it and everything in it (asks you to repeat the app id with --confirm <app id>)
27
+
28
+ MANAJEMIN_TOKEN overrides the stored token (for CI). MANAJEMIN_URL points at another gate (default ${DEFAULT_BASE_URL}).
29
+ The CLI acts in your sandbox only: it cannot approve an app, reach production, or read a secret, an app key or a database connection
30
+ (a connection is shown once in the developer portal, which can make a new one at any time).`;
31
+ function readManifest(io, file = "manifest.json") {
32
+ const path = file.startsWith("/") ? file : `${io.cwd}/${file}`;
33
+ if (!existsSync(path))
34
+ throw new McpError(`${file} not found (manajemin init writes one)`);
35
+ try {
36
+ return JSON.parse(readFileSync(path, "utf8"));
37
+ }
38
+ catch {
39
+ throw new McpError(`${file} is not valid JSON`);
40
+ }
41
+ }
42
+ function needToken(io) {
43
+ const token = io.token();
44
+ if (!token)
45
+ throw new McpError("no developer API token: run `manajemin login` or set MANAJEMIN_TOKEN");
46
+ return token;
47
+ }
48
+ function flag(args, name) {
49
+ const i = args.indexOf(name);
50
+ return i >= 0 ? args[i + 1] : undefined;
51
+ }
52
+ export async function run(argv, io) {
53
+ const [command, ...args] = argv;
54
+ const mcp = (token) => ({ baseUrl: io.baseUrl, token, fetch: io.fetch });
55
+ try {
56
+ switch (command) {
57
+ case "login": {
58
+ if (args.includes("--device"))
59
+ return await deviceLogin(io);
60
+ const token = (await io.secret("Developer API token: "))?.trim();
61
+ if (!token)
62
+ throw new McpError("no token given");
63
+ if (!TOKEN_SHAPE.test(token))
64
+ throw new McpError("that is not a developer API token (mjd_<12 hex>.<64 hex>)");
65
+ // Proves the token works before keeping it; the token itself is never printed.
66
+ const apps = (await callTool(mcp(token), "list_my_apps", {}));
67
+ const path = io.saveToken(token);
68
+ io.out(`Logged in. Token stored in ${path} (readable only by you). ${Array.isArray(apps) ? apps.length : 0} app(s) in your organisation.`);
69
+ return 0;
70
+ }
71
+ case "dev":
72
+ return await devLoop(io, args[0]);
73
+ case "logout":
74
+ io.out(io.deleteToken() ? "Logged out: the stored token is deleted. Revoke it in the developer portal if it may have leaked." : "No stored token.");
75
+ return 0;
76
+ case "init": {
77
+ const path = `${io.cwd}/manifest.json`;
78
+ if (existsSync(path))
79
+ throw new McpError("manifest.json already exists; not overwriting it");
80
+ const response = await (io.fetch ?? fetch)(`${io.baseUrl}/api/developers/spec/example-manifest.json`, { redirect: "error" });
81
+ if (!response.ok)
82
+ throw new McpError(`could not fetch the example manifest (HTTP ${response.status})`);
83
+ const manifest = (await response.json());
84
+ const id = flag(args, "--id");
85
+ if (id)
86
+ manifest.app.id = id;
87
+ writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`);
88
+ io.out(`Wrote manifest.json for app "${manifest.app.id}". Edit it, then: manajemin validate && manajemin apply`);
89
+ return 0;
90
+ }
91
+ case "validate": {
92
+ const report = (await callTool(mcp(io.token()), "validate_manifest", { manifest: readManifest(io, args[0]) }));
93
+ for (const w of report.warnings ?? [])
94
+ io.out(`warning: ${w}`);
95
+ if (!report.valid) {
96
+ for (const issue of report.issues ?? [])
97
+ io.err(`invalid: ${typeof issue === "string" ? issue : JSON.stringify(issue)}`);
98
+ return 1;
99
+ }
100
+ io.out(`valid (hash ${report.hash})`);
101
+ return 0;
102
+ }
103
+ case "apply": {
104
+ const result = (await callTool(mcp(needToken(io)), "apply_manifest", { manifest: readManifest(io, args[0]) }));
105
+ io.out(`applied ${result.appId} (hash ${result.hash}), ${result.reviewState}`);
106
+ if (result.next)
107
+ io.out(result.next);
108
+ return 0;
109
+ }
110
+ case "apps": {
111
+ const apps = (await callTool(mcp(needToken(io)), "list_my_apps", {}));
112
+ if (!Array.isArray(apps) || apps.length === 0)
113
+ io.out("no apps yet");
114
+ else
115
+ for (const a of apps)
116
+ io.out(`${a.id ?? a.appId} ${a.status ?? ""} ${a.reviewState ?? ""}`.trimEnd());
117
+ return 0;
118
+ }
119
+ case "check": {
120
+ const appId = args[0];
121
+ if (!appId)
122
+ throw new McpError("usage: manajemin check <app id>");
123
+ const result = (await callTool(mcp(needToken(io)), "run_connection_check", { appId }));
124
+ for (const s of result.steps ?? [])
125
+ io.out(`${s.ok ? "ok " : "FAIL"} ${s.step}${s.detail ? `: ${s.detail}` : ""}`);
126
+ io.out(result.ok ? "Connection check passed." : "Connection check failed: fix the first FAIL above and run it again.");
127
+ return result.ok ? 0 : 1;
128
+ }
129
+ case "review": {
130
+ const appId = args[0];
131
+ if (!appId)
132
+ throw new McpError("usage: manajemin review <app id>");
133
+ const report = (await callTool(mcp(needToken(io)), "run_review", { appId }));
134
+ io.out(`Review: ${report.score}/100, ${report.verdict}`);
135
+ const label = { pass: "ok ", warn: "WARN", fail: "FAIL", skipped: "skip" };
136
+ for (const c of report.checks ?? []) {
137
+ io.out(`${label[c.status] ?? c.status} ${c.title}${c.detail && c.detail !== "ok" ? `: ${c.detail}` : ""}`);
138
+ if (c.fix && c.status !== "pass")
139
+ io.out(` fix: ${c.fix}`);
140
+ }
141
+ for (const line of report.humanReview ?? [])
142
+ io.out(`For a person to read: ${line}`);
143
+ io.out(report.verdict === "needs_fixes" ? "Not ready: fix the FAIL and skip lines above and run it again." : "Nothing left to fix. An operator still decides.");
144
+ return report.verdict === "needs_fixes" ? 1 : 0;
145
+ }
146
+ case "trigger": {
147
+ const appId = args[0];
148
+ if (!appId)
149
+ throw new McpError("usage: manajemin trigger <app id>");
150
+ const result = (await callTool(mcp(needToken(io)), "send_test_event", { appId }));
151
+ io.out(`${result.ok ? "delivered" : "failed"}: status ${result.status} (${result.detail}), delivery ${result.deliveryId}`);
152
+ return result.ok ? 0 : 1;
153
+ }
154
+ case "simulate": {
155
+ const [appId, scenario] = args;
156
+ if (!appId || !scenario)
157
+ throw new McpError("usage: manajemin simulate <app id> <lifecycle|duplicate|out_of_order|unknown_event|bad_signature|stale_timestamp>");
158
+ const report = (await callTool(mcp(needToken(io)), "simulate", { appId, scenario }));
159
+ io.out(report.help);
160
+ if (report.steps.length === 0)
161
+ io.out("Nothing to send: your manifest subscribes to none of the events this scenario uses.");
162
+ for (const step of report.steps) {
163
+ io.out(`${step.ok ? "ok " : "FAIL"} ${step.label} (${step.eventType}): ${step.detail}`);
164
+ if (step.manual)
165
+ io.out(` check yourself: ${step.manual}`);
166
+ }
167
+ io.out(report.passed ? "Your endpoint did what was expected." : "Not what was expected: see the FAIL lines.");
168
+ return report.passed ? 0 : 1;
169
+ }
170
+ case "replay": {
171
+ const [appId, jobId] = args;
172
+ if (!appId || !jobId)
173
+ throw new McpError("usage: manajemin replay <app id> <delivery id> [--same-id]");
174
+ const result = (await callTool(mcp(needToken(io)), "replay_delivery", { appId, jobId, sameDeliveryId: args.includes("--same-id") }));
175
+ io.out(`${result.ok ? "delivered" : "failed"}: ${result.eventType}, status ${result.status} (${result.detail}), delivery ${result.deliveryId}`);
176
+ return result.ok ? 0 : 1;
177
+ }
178
+ case "health": {
179
+ const appId = args[0];
180
+ if (!appId)
181
+ throw new McpError("usage: manajemin health <app id>");
182
+ const report = (await callTool(mcp(needToken(io)), "get_app_health", { appId }));
183
+ const { health, delivery } = report;
184
+ io.out(health.uptimePct === null ? "Probes: none yet." : `Probes: ${health.uptimePct.toFixed(2)}% answered over ${health.probedDays} days; ${health.belowDays} of them above 1% failed (one vantage point).`);
185
+ // One character a day, oldest first: "." a good day, "x" a bad one, "-" nothing probed.
186
+ io.out(` ${health.days.map((d) => (d.pct === null ? "-" : 100 - d.pct > 1 ? "x" : ".")).join("")}`);
187
+ io.out(delivery.successPct === null ? "Deliveries (7 days): none." : `Deliveries (7 days): ${delivery.successPct.toFixed(1)}% accepted (${delivery.accepted} accepted, ${delivery.failed} failed for good)${delivery.latencyP50Ms !== null ? `; answer time p50 ${delivery.latencyP50Ms} ms, p95 ${delivery.latencyP95Ms} ms` : ""}`);
188
+ return 0;
189
+ }
190
+ case "logs": {
191
+ const appId = args[0];
192
+ if (!appId)
193
+ throw new McpError("usage: manajemin logs <app id> [--limit n]");
194
+ const limit = Number(flag(args, "--limit") ?? 25);
195
+ const log = await callTool(mcp(needToken(io)), "get_delivery_log", { appId, limit });
196
+ io.out(typeof log === "string" ? log : JSON.stringify(log, null, 2));
197
+ return 0;
198
+ }
199
+ case "db":
200
+ return await dbCommand(io, args);
201
+ case undefined:
202
+ case "help":
203
+ case "--help":
204
+ case "-h":
205
+ io.out(HELP);
206
+ return 0;
207
+ default:
208
+ io.err(`unknown command: ${command}\n\n${HELP}`);
209
+ return 2;
210
+ }
211
+ }
212
+ catch (err) {
213
+ io.err(`error: ${err instanceof Error ? err.message : String(err)}`);
214
+ return 1;
215
+ }
216
+ }
217
+ /**
218
+ * The device login (RFC 8628, plan F-1): ask for a code, show it, and wait while the developer approves it in the portal. The token
219
+ * comes back once and goes straight to the credentials file; it is never printed.
220
+ */
221
+ async function deviceLogin(io) {
222
+ const f = io.fetch ?? fetch;
223
+ const started = await f(`${io.baseUrl}/api/device/code`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "manajemin CLI" }), redirect: "error" });
224
+ if (!started.ok)
225
+ throw new McpError(`could not start the login (HTTP ${started.status})`);
226
+ const flow = (await started.json());
227
+ io.out(`Open ${io.baseUrl}${flow.verification_path} and sign in, then type this code:`);
228
+ io.out("");
229
+ io.out(` ${flow.user_code}`);
230
+ io.out("");
231
+ io.out("Only approve it if you just ran this command yourself. Waiting...");
232
+ let interval = flow.interval;
233
+ const deadline = Date.now() + flow.expires_in * 1000;
234
+ while (Date.now() < deadline) {
235
+ await pause(io, interval * 1000);
236
+ const polled = await f(`${io.baseUrl}/api/device/token`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ device_code: flow.device_code }), redirect: "error" });
237
+ const body = (await polled.json().catch(() => ({})));
238
+ if (body.access_token) {
239
+ if (!TOKEN_SHAPE.test(body.access_token))
240
+ throw new McpError("the platform answered with something that is not a developer token");
241
+ const path = io.saveToken(body.access_token);
242
+ io.out(`Logged in. Token stored in ${path} (readable only by you), valid for 30 days.`);
243
+ return 0;
244
+ }
245
+ if (body.error === "authorization_pending")
246
+ continue;
247
+ if (body.error === "slow_down") {
248
+ interval += 5;
249
+ continue;
250
+ }
251
+ if (body.error === "access_denied")
252
+ throw new McpError("the login was denied in the portal");
253
+ if (body.error === "token_limit_reached")
254
+ throw new McpError(body.error_description ?? "the organisation already holds the most active tokens; revoke one in the portal");
255
+ throw new McpError("the code expired; run the command again");
256
+ }
257
+ throw new McpError("the code expired; run the command again");
258
+ }
259
+ /**
260
+ * The inner loop (plan F-1, `manajemin dev`): validate and apply the manifest whenever it is saved, and print each delivery to the app as
261
+ * it arrives, so a change and its effect are on one screen. Stops on Ctrl-C. It acts in the sandbox only, like every command.
262
+ */
263
+ async function devLoop(io, file = "manifest.json") {
264
+ const token = needToken(io);
265
+ const path = file.startsWith("/") ? file : `${io.cwd}/${file}`;
266
+ const mtime = () => (existsSync(path) ? statSync(path).mtimeMs : 0);
267
+ const seen = new Set();
268
+ let appId = null;
269
+ let applied = 0;
270
+ let first = true;
271
+ io.out(`Watching ${file}. Press Ctrl-C to stop.`);
272
+ while (!io.signal?.aborted) {
273
+ if (mtime() !== applied) {
274
+ applied = mtime();
275
+ try {
276
+ const manifest = readManifest(io, file);
277
+ const report = (await callTool(mcpOf(io, token), "validate_manifest", { manifest }));
278
+ if (!report.valid) {
279
+ for (const issue of report.issues ?? [])
280
+ io.err(`invalid: ${typeof issue === "string" ? issue : JSON.stringify(issue)}`);
281
+ }
282
+ else {
283
+ const result = (await callTool(mcpOf(io, token), "apply_manifest", { manifest }));
284
+ appId = result.appId;
285
+ io.out(`applied ${result.appId} (hash ${result.hash.slice(0, 12)})`);
286
+ }
287
+ }
288
+ catch (err) {
289
+ io.err(`error: ${err instanceof Error ? err.message : String(err)}`);
290
+ }
291
+ }
292
+ if (appId) {
293
+ try {
294
+ const log = (await callTool(mcpOf(io, token), "get_delivery_log", { appId, limit: 20 }));
295
+ for (const d of [...(Array.isArray(log) ? log : [])].reverse()) {
296
+ if (seen.has(`${d.id}:${d.status}`))
297
+ continue;
298
+ seen.add(`${d.id}:${d.status}`);
299
+ if (!first)
300
+ io.out(`delivery ${d.eventType}: ${d.status}${d.lastError ? ` (${d.lastError.slice(0, 120)})` : ""}`);
301
+ }
302
+ first = false;
303
+ }
304
+ catch (err) {
305
+ io.err(`error: ${err instanceof Error ? err.message : String(err)}`);
306
+ }
307
+ }
308
+ await pause(io, 3000);
309
+ }
310
+ io.out("Stopped.");
311
+ return 0;
312
+ }
313
+ const REGIONS = { "aws-eu-central-1": "AWS_EU_CENTRAL_1", "aws-us-west-2": "AWS_US_WEST_2" };
314
+ /** `manajemin db ...`: the managed database. A connection is a secret and never travels through the CLI. */
315
+ async function dbCommand(io, args) {
316
+ const [sub, appId] = args;
317
+ if (sub === "status") {
318
+ const o = (await callTool(mcpOf(io, needToken(io)), "get_database", {}));
319
+ if (!o.available)
320
+ io.out("The managed database is not switched on yet.");
321
+ io.out(`Price (live, pooled in 1 GB blocks): $${o.price.storageUsdPerGbMonth} per GB-month; ${o.price.includedTokensPerBlock.toLocaleString("en-US")} query tokens included per block, then $${o.price.overageUsdPerMillionTokens} per million. Sandbox is free (up to ${o.sandboxCap} in total).`);
322
+ if (o.databases.length === 0)
323
+ io.out("No databases yet.");
324
+ for (const d of o.databases) {
325
+ const size = d.storageBytes === null ? "not read yet" : `${(d.storageBytes / 1024 ** 2).toFixed(1)} MB (${d.sampledAt})`;
326
+ io.out(`${d.appId ?? "(app removed)"} ${d.status} ${d.stage} ${d.region} ${size}${d.problem ? ` ! ${d.problem}` : ""}`);
327
+ }
328
+ if (o.statement)
329
+ io.out(`This month so far (${o.statement.period}): sandbox ${o.statement.sandboxGb} GB, live ${o.statement.liveGb} GB, ${o.statement.blocks} block(s), $${o.statement.totalUsd}. A draft, not an invoice.`);
330
+ return 0;
331
+ }
332
+ if (sub === "create") {
333
+ const region = REGIONS[flag(args, "--region") ?? ""];
334
+ if (!appId || !region)
335
+ throw new McpError("usage: manajemin db create <app id> --region aws-eu-central-1|aws-us-west-2");
336
+ const r = (await callTool(mcpOf(io, needToken(io)), "create_database", { appId, region }));
337
+ io.out(`Database ${r.database.status} for ${appId} (${r.database.region}). Synthetic data only. Open the developer portal and choose "Buat koneksi baru" to get a connection: it is shown once and never through this CLI.`);
338
+ return 0;
339
+ }
340
+ if (sub === "delete") {
341
+ if (!appId)
342
+ throw new McpError("usage: manajemin db delete <app id> --confirm <app id>");
343
+ if (flag(args, "--confirm") !== appId)
344
+ throw new McpError(`this deletes the database and everything in it; repeat the app id to confirm: manajemin db delete ${appId} --confirm ${appId}`);
345
+ await callTool(mcpOf(io, needToken(io)), "delete_database", { appId });
346
+ io.out(`Deleted the database of ${appId}.`);
347
+ return 0;
348
+ }
349
+ throw new McpError("usage: manajemin db status | create <app id> --region <region> | delete <app id> --confirm <app id>");
350
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Where the developer API token lives between runs: MANAJEMIN_TOKEN when set (CI), else a file only the user can read.
3
+ * The token is never printed, logged or sent anywhere but the platform's /api/mcp.
4
+ */
5
+ export declare function credentialsPath(env?: NodeJS.ProcessEnv): string;
6
+ export declare function readToken(env?: NodeJS.ProcessEnv): string | null;
7
+ export declare function saveToken(token: string, env?: NodeJS.ProcessEnv): string;
8
+ export declare function deleteToken(env?: NodeJS.ProcessEnv): boolean;
package/credentials.js ADDED
@@ -0,0 +1,39 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ /**
5
+ * Where the developer API token lives between runs: MANAJEMIN_TOKEN when set (CI), else a file only the user can read.
6
+ * The token is never printed, logged or sent anywhere but the platform's /api/mcp.
7
+ */
8
+ export function credentialsPath(env = process.env) {
9
+ const base = env.XDG_CONFIG_HOME || join(homedir(), ".config");
10
+ return join(base, "manajemin", "credentials.json");
11
+ }
12
+ export function readToken(env = process.env) {
13
+ if (env.MANAJEMIN_TOKEN)
14
+ return env.MANAJEMIN_TOKEN;
15
+ const path = credentialsPath(env);
16
+ if (!existsSync(path))
17
+ return null;
18
+ try {
19
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
20
+ return parsed.token ?? null;
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ export function saveToken(token, env = process.env) {
27
+ const path = credentialsPath(env);
28
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
29
+ writeFileSync(path, `${JSON.stringify({ token })}\n`, { mode: 0o600 });
30
+ chmodSync(path, 0o600);
31
+ return path;
32
+ }
33
+ export function deleteToken(env = process.env) {
34
+ const path = credentialsPath(env);
35
+ if (!existsSync(path))
36
+ return false;
37
+ rmSync(path);
38
+ return true;
39
+ }
package/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/main.js ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ import { createInterface } from "node:readline";
3
+ import { deleteToken, readToken, saveToken } from "./credentials.js";
4
+ import { DEFAULT_BASE_URL, run } from "./commands.js";
5
+ /** Reads a line without echoing it, so a pasted token never shows on screen or in a terminal recording. */
6
+ function secret(prompt) {
7
+ if (!process.stdin.isTTY) {
8
+ return new Promise((resolve) => {
9
+ let data = "";
10
+ process.stdin.on("data", (chunk) => (data += chunk));
11
+ process.stdin.on("end", () => resolve(data.trim() || null));
12
+ });
13
+ }
14
+ return new Promise((resolve) => {
15
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
16
+ const write = rl;
17
+ process.stdout.write(prompt);
18
+ write._writeToOutput = () => { };
19
+ rl.question("", (answer) => {
20
+ rl.close();
21
+ process.stdout.write("\n");
22
+ resolve(answer || null);
23
+ });
24
+ });
25
+ }
26
+ const stop = new AbortController();
27
+ process.on("SIGINT", () => stop.abort());
28
+ const code = await run(process.argv.slice(2), {
29
+ out: (line) => console.log(line),
30
+ err: (line) => console.error(line),
31
+ secret,
32
+ token: () => readToken(),
33
+ saveToken: (token) => saveToken(token),
34
+ deleteToken: () => deleteToken(),
35
+ baseUrl: (process.env.MANAJEMIN_URL ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
36
+ cwd: process.cwd(),
37
+ signal: stop.signal,
38
+ });
39
+ process.exit(code);
package/mcp.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The CLI speaks to the developer MCP server (`/api/mcp`): the same tools a coding agent uses, so the CLI holds no
3
+ * logic the platform does not already enforce. A developer API token (sandbox only, at most 90 days) unlocks the tools
4
+ * that act; without one only validation and the docs answer.
5
+ */
6
+ export declare class McpError extends Error {
7
+ readonly code: number | null;
8
+ constructor(message: string, code?: number | null);
9
+ }
10
+ export interface McpOptions {
11
+ baseUrl: string;
12
+ token?: string | null;
13
+ fetch?: typeof fetch;
14
+ }
15
+ export declare function callTool(options: McpOptions, name: string, args: Record<string, unknown>): Promise<unknown>;
package/mcp.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The CLI speaks to the developer MCP server (`/api/mcp`): the same tools a coding agent uses, so the CLI holds no
3
+ * logic the platform does not already enforce. A developer API token (sandbox only, at most 90 days) unlocks the tools
4
+ * that act; without one only validation and the docs answer.
5
+ */
6
+ export class McpError extends Error {
7
+ code;
8
+ constructor(message, code = null) {
9
+ super(message);
10
+ this.name = "McpError";
11
+ this.code = code;
12
+ }
13
+ }
14
+ let nextId = 1;
15
+ export async function callTool(options, name, args) {
16
+ const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
17
+ if (options.token)
18
+ headers.authorization = `Bearer ${options.token}`;
19
+ const response = await (options.fetch ?? fetch)(`${options.baseUrl.replace(/\/$/, "")}/api/mcp`, {
20
+ method: "POST",
21
+ headers,
22
+ body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method: "tools/call", params: { name, arguments: args } }),
23
+ redirect: "error",
24
+ signal: AbortSignal.timeout(60_000),
25
+ });
26
+ const body = (await response.json().catch(() => null));
27
+ if (body?.error)
28
+ throw new McpError(body.error.message, body.error.code);
29
+ if (!response.ok || !body?.result)
30
+ throw new McpError(`HTTP ${response.status}`);
31
+ const text = body.result.content?.find((c) => c.type === "text")?.text ?? "";
32
+ let parsed = text;
33
+ try {
34
+ parsed = JSON.parse(text);
35
+ }
36
+ catch {
37
+ // Some tools answer in prose.
38
+ }
39
+ if (body.result.isError)
40
+ throw new McpError(typeof parsed === "string" ? parsed : JSON.stringify(parsed));
41
+ return parsed;
42
+ }
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@manajemin-dev-cli/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Manajemin developer CLI: validate and apply a manifest, run the Connection check, send a test event, read the delivery log.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "manajemin": "./main.js"
9
+ },
10
+ "engines": {
11
+ "node": ">=20"
12
+ },
13
+ "keywords": [
14
+ "manajemin",
15
+ "cli"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ }
20
+ }