@anybuild-ai/ab 0.1.2 → 0.3.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.
Files changed (80) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +84 -5
  3. package/dist/api/entity-api.d.ts +35 -0
  4. package/dist/api/entity-api.d.ts.map +1 -0
  5. package/dist/api/entity-api.js +138 -0
  6. package/dist/api/entity-api.js.map +1 -0
  7. package/dist/commands/api-key.d.ts +3 -0
  8. package/dist/commands/api-key.d.ts.map +1 -0
  9. package/dist/commands/api-key.js +109 -0
  10. package/dist/commands/api-key.js.map +1 -0
  11. package/dist/commands/api.d.ts +3 -0
  12. package/dist/commands/api.d.ts.map +1 -0
  13. package/dist/commands/api.js +89 -0
  14. package/dist/commands/api.js.map +1 -0
  15. package/dist/commands/index.d.ts.map +1 -1
  16. package/dist/commands/index.js +6 -0
  17. package/dist/commands/index.js.map +1 -1
  18. package/dist/commands/pull.d.ts.map +1 -1
  19. package/dist/commands/pull.js +67 -5
  20. package/dist/commands/pull.js.map +1 -1
  21. package/dist/commands/status.d.ts.map +1 -1
  22. package/dist/commands/status.js +12 -4
  23. package/dist/commands/status.js.map +1 -1
  24. package/dist/commands/validate.d.ts.map +1 -1
  25. package/dist/commands/validate.js +3 -1
  26. package/dist/commands/validate.js.map +1 -1
  27. package/dist/config/global-config.d.ts +4 -1
  28. package/dist/config/global-config.d.ts.map +1 -1
  29. package/dist/config/global-config.js +25 -0
  30. package/dist/config/global-config.js.map +1 -1
  31. package/dist/config/index.d.ts +2 -2
  32. package/dist/config/index.d.ts.map +1 -1
  33. package/dist/config/index.js +1 -1
  34. package/dist/config/index.js.map +1 -1
  35. package/dist/config/types.d.ts +13 -0
  36. package/dist/config/types.d.ts.map +1 -1
  37. package/dist/export/checksum.d.ts +4 -0
  38. package/dist/export/checksum.d.ts.map +1 -1
  39. package/dist/export/checksum.js +8 -0
  40. package/dist/export/checksum.js.map +1 -1
  41. package/dist/export/import-batch.d.ts.map +1 -1
  42. package/dist/export/import-batch.js +142 -24
  43. package/dist/export/import-batch.js.map +1 -1
  44. package/dist/export/path-based-status.d.ts.map +1 -1
  45. package/dist/export/path-based-status.js +4 -2
  46. package/dist/export/path-based-status.js.map +1 -1
  47. package/dist/export/restore-hint.d.ts +8 -0
  48. package/dist/export/restore-hint.d.ts.map +1 -0
  49. package/dist/export/restore-hint.js +38 -0
  50. package/dist/export/restore-hint.js.map +1 -0
  51. package/dist/export/schema-json.d.ts +21 -0
  52. package/dist/export/schema-json.d.ts.map +1 -0
  53. package/dist/export/schema-json.js +125 -0
  54. package/dist/export/schema-json.js.map +1 -0
  55. package/dist/export/status.d.ts +2 -2
  56. package/dist/export/status.d.ts.map +1 -1
  57. package/dist/export/status.js +117 -47
  58. package/dist/export/status.js.map +1 -1
  59. package/dist/export/sync.d.ts +4 -2
  60. package/dist/export/sync.d.ts.map +1 -1
  61. package/dist/export/sync.js +170 -20
  62. package/dist/export/sync.js.map +1 -1
  63. package/dist/export/types.d.ts +6 -3
  64. package/dist/export/types.d.ts.map +1 -1
  65. package/dist/export/working-dirs.d.ts +21 -1
  66. package/dist/export/working-dirs.d.ts.map +1 -1
  67. package/dist/export/working-dirs.js +76 -2
  68. package/dist/export/working-dirs.js.map +1 -1
  69. package/dist/export/working-tree-validation.d.ts +1 -1
  70. package/dist/export/working-tree-validation.d.ts.map +1 -1
  71. package/dist/export/working-tree-validation.js +32 -0
  72. package/dist/export/working-tree-validation.js.map +1 -1
  73. package/dist/io/read-credentials.d.ts +3 -0
  74. package/dist/io/read-credentials.d.ts.map +1 -1
  75. package/dist/io/read-credentials.js +31 -20
  76. package/dist/io/read-credentials.js.map +1 -1
  77. package/dist/router.d.ts.map +1 -1
  78. package/dist/router.js +4 -1
  79. package/dist/router.js.map +1 -1
  80. package/package.json +3 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - `anybuild api <METHOD> <path>` calls entity endpoints (OData) of the project's host with a stored API key: only `<api_url>/api/…`, no full URLs, no redirects; body to stdout, status to stderr, exit code 1 on HTTP errors. Writes (POST / PATCH / DELETE) need a key stored with writes allowed.
6
+ - `anybuild api-key set | show | remove`: store an API key per host in `~/.ab/config.json` (terminal only, hidden input, checked against the server before it is stored, writes allowed only when confirmed), show it masked, or remove it.
7
+ - Hidden prompts (password, API key) accept pasted input that arrives in one chunk.
8
+ - Writable `be/scenarios/*.json` (AnyInput scenarios, readable format) and `be/capability_profiles/*.json` (AnyInput capability profiles, `<type>.<name>.json`): create/update/delete on push; the server translates names, embeds examples and saves through the AnyInput registry. `validate` runs the full AnyInput validation. Profiles are sent before scenarios, both after `be/entities` / `be/views`.
9
+
10
+ ## 0.2.0
11
+
12
+ - `validate` is public again: same pending batch as `push`, sent with `validate_only`. The server checks import gates (paths, checksums, JSON identity/expand, JS parse, delete guards) and does not apply, build, or stamp. It does not prove SQL or entity compile.
13
+ - Writable `be/entities/` and `be/views/` (simple authoring JSON); designer views convert to code on push; collision filenames (`slug.<thing_id>.ext`); pull after push to refresh `meta/` catalogs
14
+ - Writable `ui/portals/*.json` for portal (`ui_application`) records (create/update/delete on push; public/secure master pages + navigation)
15
+ - Writable `ui/navigation/*.json` for portal navigation trees (create/update/delete on push; menus load this tree at runtime)
16
+ - Default entity widgets (autogenerated list/create/edit) export under read-only `meta/ui/lit/components/`; custom Lit widgets stay in `ui/lit/components/`
17
+ - Pull treats a missing CLI checksum as unstamped (must download); status shows those files as Modified
18
+ - `pull --force <path>` re-downloads only those files (does not fetch the whole project); `status` and a no-op pull print how to restore a local file from the server
19
+ - Pull writes the files-API checksum when it differs from a cached manifest stamp (live schema projection vs last CLI stamp)
20
+ - Push commits checksums for files that saved even if other files in the same batch fail
21
+ - View/entity save success stays applied if build or a dependant rebuild fails; CLI prints `Warning:` and still updates the checksum
22
+ - View authoring sources identify the target by thing UUID (`id`), not `entity_id` / `view_id` / `component_id` (those labels are not unique across applications)
23
+
3
24
  ## 0.1.2
4
25
 
5
26
  - `push` asks for confirmation when the batch includes deletions; use `--yes` / `-y` to skip (required non-interactively)
package/README.md CHANGED
@@ -55,8 +55,43 @@ anybuild logout https://your-host.example.com
55
55
 
56
56
  On push conflicts, **pull** again, resolve locally, then **push**.
57
57
 
58
+ A normal **pull** only downloads files whose last snapshot (`.ab/file-state.json`) differs from the server. If a local file still looks Modified after that, the disk copy does not match the stamped checksum. Restore that file without re-downloading the whole project:
59
+
60
+ ```bash
61
+ anybuild pull --force be/views/transport_events.json
62
+ ```
63
+
58
64
  If a push includes **deletions**, the CLI lists them and asks for confirmation. Pass `--yes` (or `-y`) to skip the prompt (required in non-interactive / CI use).
59
65
 
66
+ ## Working trees
67
+
68
+ `status` / `push` track these folders:
69
+
70
+ | Path | What you edit |
71
+ | --- | --- |
72
+ | `ui/lit/components/` | Custom Lit widgets (`.js`) and theme JSON |
73
+ | `ui/navigation/` | Navigation instance JSON |
74
+ | `ui/portals/` | Portal (`ui_application`) JSON |
75
+ | `be/plv8/` | PLV8 functions (`.js`) |
76
+ | `be/node/` | Node modules (`.js`) |
77
+ | `be/entities/` | Entity authoring JSON |
78
+ | `be/views/` | Custom view authoring JSON |
79
+
80
+ `meta/` is **read-only** (catalogs, generated schema dumps, default entity widgets, AI rule files). Do not put source entity/view JSON there.
81
+
82
+ **Entities, views, navigation, and portals**
83
+
84
+ - Files are simple JSON (`id` = thing UUID; `entity_id` / `view_id` / `navigation_id` / `application_id` stay inside the file as labels). View **sources** use target `id` (thing UUID), not `entity_id` / `view_id`, so they can point at objects in other applications. Format: `AGENTS.md` plus `meta/be/entities/RULES.md`, `meta/be/views/RULES.md`, `meta/ui/navigation/RULES.md`, and `meta/ui/portals/RULES.md` after clone/pull.
85
+ - New views are always **code mode** (SQL + named sources).
86
+ - Custom **designer** views export as the same JSON. Editing one and pushing **converts it to code** on the server. Untouched designer views stay designer.
87
+ - Default entity/component views are **not** under `be/views/` (they stay in `meta/`).
88
+ - Default entity widgets (autogenerated list/create/edit) are **not** under `ui/lit/components/` (they stay in `meta/ui/lit/components/`). After pull, delete leftover copies from `ui/lit/components/` if they still appear as Added.
89
+ - If two records share the same `entity_id` / `view_id` / `navigation_id` / `application_id`, files are `slug.json` and `slug.<thing_id>.json`. Push does **not** rename the live id from the filename.
90
+ - Schema apply is one POST: save, then build in dependency order (entities before views, source views before dependents). In a mixed push the order is widgets, then navigation, then portals, then schema.
91
+ - After a schema, navigation, or portal push, run **`anybuild pull`**. Catalogs under `meta/be/catalog/` refresh only on pull.
92
+
93
+ Checksums: `.json` under `ui/lit`, `ui/navigation`, `ui/portals`, `be/entities`, and `be/views` uses canonical JSON; other files use raw UTF-8.
94
+
60
95
  ## Commands
61
96
 
62
97
  | Command | Description |
@@ -64,12 +99,56 @@ If a push includes **deletions**, the CLI lists them and asks for confirmation.
64
99
  | `anybuild login <host-url>` | Sign in (prompts for username and password) |
65
100
  | `anybuild logout <host-url>` | Sign out and remove the local session for that host |
66
101
  | `anybuild clone <host-url>/<app> [directory]` | Download an application into `./<app>/` (or `[directory]`; use `.` for cwd). Options: `--force`, `--debug` |
67
- | `anybuild pull` | Download latest changes. Options: `--force`, `--debug` |
102
+ | `anybuild pull [paths…]` | Download latest changes. Options: `--force` (overwrite local files even when the last snapshot already matches the server; with no paths this re-downloads everything), `--debug` |
68
103
  | `anybuild status` | List local added / modified / deleted files |
104
+ | `anybuild validate [paths…]` | Check pending changes against the server without applying them (checksums, JSON shape, JS parse, schema expand). Does not compile entities or views. Options: `--debug` |
69
105
  | `anybuild push [paths…]` | Upload local changes (optional file paths). Options: `--debug`, `--yes` / `-y` (skip confirm when the push includes deletions) |
106
+ | `anybuild api <GET\|POST\|PATCH\|DELETE> <path> [--data <json> \| --data-file <file>]` | Call an entity endpoint (OData) of the project's host with the stored API key. `<path>` is relative to `/api/`. Body to stdout, status line to stderr, exit code 1 on HTTP errors |
107
+ | `anybuild api-key set [--allow-writes \| --read-only]` | Store an API key for the project's host (hidden prompt, terminal only). Checks the key first; asks whether writes are allowed (default no) |
108
+ | `anybuild api-key show` / `remove` | Show which key is stored (never the secret) / forget it |
70
109
 
71
110
  Also: `anybuild help`, `anybuild -v` / `--version`.
72
111
 
112
+ ### Calling entity endpoints
113
+
114
+ Entities with endpoints are served as an OData API under `/api/<path>`. `anybuild api` calls them for testing and seeding, for you or for an AI agent working in the project.
115
+
116
+ #### Setting up an API key (once per host, by a person)
117
+
118
+ `anybuild api` never uses your login. It needs an API key, stored once per host on your machine.
119
+
120
+ 1. **Create the key** in Anybuild: Identities → open the identity the calls should run as (preferably a service account with a minimal role, not your own user) → API keys → Create API key. Give it a name and a short expiry, and do not make it unscoped. Copy the key (`odk_…`): it is shown only once.
121
+ 2. **Grant the endpoints** it may use: open the key on the same page; in the scope editor tick Read / Save / Submit / Delete for each entity it needs, then Save scopes.
122
+ 3. **Store it in the CLI**: open a terminal in the project folder (the folder that contains `.ab/`) and run
123
+
124
+ ```bash
125
+ anybuild api-key set
126
+ ```
127
+
128
+ - At `API key for https://… (input hidden):` paste the key and press Enter. Nothing is shown while you paste; that is expected.
129
+ - The CLI checks the key against the server. A rejected key is not stored.
130
+ - At `Allow writes (POST / PATCH / DELETE) …? [y/N]` answer `y` only on a development or test environment. With `N` (the default) the key can only read.
131
+ - It ends with `Stored odk_<id>_… for https://… (environment: …), read only.` (or `reads and writes`).
132
+ 4. **Check it**: `anybuild api-key show` prints which key is stored (never the secret); `anybuild api GET '<app>/<entity>?$top=1'` should return data.
133
+
134
+ Good to know:
135
+
136
+ - The key belongs to the host, not to one project: every project on that host on this machine uses it.
137
+ - To replace the key or change the write setting, run `anybuild api-key set` again.
138
+ - When you are done: `anybuild api-key remove`, then revoke the key on the Identities page.
139
+
140
+ #### Calling
141
+
142
+ ```bash
143
+ anybuild api GET 'my_app/invoice?$top=5&$count=true'
144
+ anybuild api POST my_app/invoice --data '{"invoice_number":"INV-1"}'
145
+ anybuild api PATCH 'my_app/invoice(<thing_id>)' --data '{"note":"x"}'
146
+ anybuild api POST 'my_app/invoice(<thing_id>)/submit'
147
+ ```
148
+
149
+ - Requests only go to the project's `api_url` (`.ab/config.json`); full URLs and redirects are refused, so the key is not sent elsewhere.
150
+ - POST / PATCH / DELETE are refused unless the key was stored with writes allowed.
151
+
73
152
  ### Clone examples
74
153
 
75
154
  ```bash
@@ -86,15 +165,15 @@ anybuild clone https://your-host.example.com/my-app ./other-folder --force
86
165
 
87
166
  | Location | Purpose |
88
167
  | --- | --- |
89
- | `~/.ab/config.json` | Your login sessions (credentials for each host) |
168
+ | `~/.ab/config.json` | Your login sessions and stored API keys (credentials for each host) |
90
169
  | `.ab/` in the project | Project settings and sync state (no passwords) |
91
170
 
92
- Run project commands (`pull`, `push`, `status`) from inside a cloned application directory.
171
+ Run project commands (`pull`, `push`, `status`, `validate`) from inside a cloned application directory.
93
172
 
94
173
  ## Security
95
174
 
96
- - Sessions live in `~/.ab/` with restrictive file permissions on Unix. Do not share or commit that folder.
97
- - Prefer **HTTPS** host URLs.
175
+ - Sessions and API keys live in `~/.ab/` with restrictive file permissions on Unix. Do not share or commit that folder.
176
+ - `anybuild api-key set` only runs in a terminal (hidden input), so a key is always stored by a person. The CLI never prints a stored key.
98
177
  - On shared machines, run `anybuild logout <host-url>` when done.
99
178
  - Avoid `--debug` in shared or CI logs.
100
179
 
@@ -0,0 +1,35 @@
1
+ /** Methods `anybuild api` sends. Anything but GET changes data and needs a key stored with writes allowed. */
2
+ export declare const API_METHODS: readonly ["GET", "POST", "PATCH", "DELETE"];
3
+ export type ApiMethod = (typeof API_METHODS)[number];
4
+ export declare function parseApiMethod(value: string | undefined): ApiMethod;
5
+ export declare function isWriteMethod(method: ApiMethod): boolean;
6
+ export declare function isValidApiKey(value: string): boolean;
7
+ /** odk_<key id>_… — the key id is not secret, the rest is never shown. */
8
+ export declare function maskApiKey(value: string): string;
9
+ /**
10
+ * The URL is always `<api_url>/api/<path>` of the project, so a stored key is only ever sent to that host.
11
+ * `path` may be given with or without the leading `/api/`; it may carry a query string.
12
+ */
13
+ export declare function buildApiUrl(apiUrl: string, path: string): string;
14
+ /** Validates the body locally, so a typo does not become a server round trip. */
15
+ export declare function parseJsonBody(text: string, source: string): string;
16
+ export type ApiCallResult = {
17
+ status: number;
18
+ statusText: string;
19
+ contentType: string;
20
+ body: string;
21
+ durationMs: number;
22
+ };
23
+ export declare function callEntityApi(options: {
24
+ apiUrl: string;
25
+ path: string;
26
+ method: ApiMethod;
27
+ apiKey: string;
28
+ body?: string;
29
+ timeoutMs?: number;
30
+ }, fetchImpl?: typeof fetch): Promise<ApiCallResult>;
31
+ /** JSON bodies are pretty printed; anything else (e.g. $metadata XML) is returned as is. */
32
+ export declare function formatBody(result: ApiCallResult): string;
33
+ /** The OData error message, when the body has one. */
34
+ export declare function errorMessage(result: ApiCallResult): string | undefined;
35
+ //# sourceMappingURL=entity-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-api.d.ts","sourceRoot":"","sources":["../../src/api/entity-api.ts"],"names":[],"mappings":"AAGA,8GAA8G;AAC9G,eAAO,MAAM,WAAW,6CAA8C,CAAC;AACvE,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAMrD,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CASnE;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAExD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED,0EAA0E;AAC1E,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAGhD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CA2BhE;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CASlE;AAED,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,wBAAsB,aAAa,CACjC,OAAO,EAAE;IACP,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,SAAS,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,EACD,SAAS,GAAE,OAAO,KAAa,GAC9B,OAAO,CAAC,aAAa,CAAC,CA8CxB;AAED,4FAA4F;AAC5F,wBAAgB,UAAU,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,CAYxD;AAED,sDAAsD;AACtD,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,GAAG,SAAS,CAYtE"}
@@ -0,0 +1,138 @@
1
+ import { normalizeApiUrl } from "../config/normalize-url.js";
2
+ import { AbCliError, CLI_PROGRAM } from "../errors.js";
3
+ /** Methods `anybuild api` sends. Anything but GET changes data and needs a key stored with writes allowed. */
4
+ export const API_METHODS = ["GET", "POST", "PATCH", "DELETE"];
5
+ const API_PREFIX = "/api/";
6
+ const API_KEY_PATTERN = /^odk_[A-Za-z0-9-]+_[A-Za-z0-9_-]+$/;
7
+ const REQUEST_TIMEOUT_MS = 120_000;
8
+ export function parseApiMethod(value) {
9
+ const method = (value ?? "").trim().toUpperCase();
10
+ if (!API_METHODS.includes(method)) {
11
+ throw new AbCliError("CONFIG", `Method must be one of ${API_METHODS.join(", ")}, got ${JSON.stringify(value ?? "")}.`);
12
+ }
13
+ return method;
14
+ }
15
+ export function isWriteMethod(method) {
16
+ return method !== "GET";
17
+ }
18
+ export function isValidApiKey(value) {
19
+ return API_KEY_PATTERN.test(value);
20
+ }
21
+ /** odk_<key id>_… — the key id is not secret, the rest is never shown. */
22
+ export function maskApiKey(value) {
23
+ const match = /^(odk_[A-Za-z0-9-]+)_/.exec(value);
24
+ return match ? `${match[1]}_…` : "odk_…";
25
+ }
26
+ /**
27
+ * The URL is always `<api_url>/api/<path>` of the project, so a stored key is only ever sent to that host.
28
+ * `path` may be given with or without the leading `/api/`; it may carry a query string.
29
+ */
30
+ export function buildApiUrl(apiUrl, path) {
31
+ const raw = (path ?? "").trim();
32
+ if (!raw) {
33
+ throw new AbCliError("CONFIG", `Path is required, e.g. ${CLI_PROGRAM} api GET my_app/invoice?$top=5`);
34
+ }
35
+ if (/^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith("//")) {
36
+ throw new AbCliError("CONFIG", "Path must be relative to the project's API (for example my_app/invoice), not a full URL.");
37
+ }
38
+ let relative = raw.replace(/^\/+/, "");
39
+ if (relative.toLowerCase().startsWith("api/")) {
40
+ relative = relative.slice(4);
41
+ }
42
+ if (!relative || relative.split(/[?#]/)[0].split("/").some((segment) => segment === "..")) {
43
+ throw new AbCliError("CONFIG", `Path ${JSON.stringify(raw)} is not a valid API path.`);
44
+ }
45
+ // keep $, (, ), ', commas readable; encode spaces and other characters a URL cannot carry
46
+ // accept an already encoded path (%20) as well as a readable one; encode once
47
+ let decoded = relative;
48
+ try {
49
+ decoded = decodeURI(relative);
50
+ }
51
+ catch {
52
+ // keep as typed
53
+ }
54
+ return `${normalizeApiUrl(apiUrl)}${API_PREFIX}${encodeURI(decoded)}`;
55
+ }
56
+ /** Validates the body locally, so a typo does not become a server round trip. */
57
+ export function parseJsonBody(text, source) {
58
+ try {
59
+ return JSON.stringify(JSON.parse(text));
60
+ }
61
+ catch (e) {
62
+ throw new AbCliError("CONFIG", `${source} is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
63
+ }
64
+ }
65
+ export async function callEntityApi(options, fetchImpl = fetch) {
66
+ const url = buildApiUrl(options.apiUrl, options.path);
67
+ const headers = new Headers({
68
+ Authorization: `Bearer ${options.apiKey}`,
69
+ Accept: "application/json, application/xml;q=0.9, */*;q=0.1",
70
+ });
71
+ if (options.body !== undefined) {
72
+ headers.set("Content-Type", "application/json");
73
+ }
74
+ const controller = new AbortController();
75
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? REQUEST_TIMEOUT_MS);
76
+ const started = Date.now();
77
+ let res;
78
+ try {
79
+ res = await fetchImpl(url, {
80
+ method: options.method,
81
+ headers,
82
+ body: options.body,
83
+ // a redirect would carry the key to wherever it points
84
+ redirect: "manual",
85
+ signal: controller.signal,
86
+ });
87
+ }
88
+ catch (e) {
89
+ if (controller.signal.aborted) {
90
+ throw new AbCliError("HTTP", `${options.method} ${url} timed out after ${Math.round((options.timeoutMs ?? REQUEST_TIMEOUT_MS) / 1000)} s.`);
91
+ }
92
+ throw new AbCliError("HTTP", `${options.method} ${url} failed: ${e instanceof Error ? e.message : String(e)}`);
93
+ }
94
+ finally {
95
+ clearTimeout(timer);
96
+ }
97
+ if (res.status >= 300 && res.status < 400) {
98
+ throw new AbCliError("HTTP", `${options.method} ${url} answered with a redirect (${res.status}); the CLI does not follow redirects with an API key.`);
99
+ }
100
+ return {
101
+ status: res.status,
102
+ statusText: res.statusText,
103
+ contentType: res.headers.get("content-type") ?? "",
104
+ body: await res.text(),
105
+ durationMs: Date.now() - started,
106
+ };
107
+ }
108
+ /** JSON bodies are pretty printed; anything else (e.g. $metadata XML) is returned as is. */
109
+ export function formatBody(result) {
110
+ if (!result.body) {
111
+ return "";
112
+ }
113
+ if (/json/i.test(result.contentType)) {
114
+ try {
115
+ return JSON.stringify(JSON.parse(result.body), null, 2);
116
+ }
117
+ catch {
118
+ return result.body;
119
+ }
120
+ }
121
+ return result.body;
122
+ }
123
+ /** The OData error message, when the body has one. */
124
+ export function errorMessage(result) {
125
+ try {
126
+ const parsed = JSON.parse(result.body);
127
+ if (parsed?.error && typeof parsed.error.message === "string") {
128
+ return typeof parsed.error.code === "string"
129
+ ? `${parsed.error.code}: ${parsed.error.message}`
130
+ : parsed.error.message;
131
+ }
132
+ }
133
+ catch {
134
+ // not JSON
135
+ }
136
+ return undefined;
137
+ }
138
+ //# sourceMappingURL=entity-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-api.js","sourceRoot":"","sources":["../../src/api/entity-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEvD,8GAA8G;AAC9G,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAC;AAGvE,MAAM,UAAU,GAAG,OAAO,CAAC;AAC3B,MAAM,eAAe,GAAG,oCAAoC,CAAC;AAC7D,MAAM,kBAAkB,GAAG,OAAO,CAAC;AAEnC,MAAM,UAAU,cAAc,CAAC,KAAyB;IACtD,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAClD,IAAI,CAAE,WAAiC,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,MAAM,IAAI,UAAU,CAClB,QAAQ,EACR,yBAAyB,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC,GAAG,CACvF,CAAC;IACJ,CAAC;IACD,OAAO,MAAmB,CAAC;AAC7B,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,MAAiB;IAC7C,OAAO,MAAM,KAAK,KAAK,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC,CAAC;AAED,0EAA0E;AAC1E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IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { CommandHandler } from "./types.js";
2
+ export declare const apiKey: CommandHandler;
3
+ //# sourceMappingURL=api-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key.d.ts","sourceRoot":"","sources":["../../src/commands/api-key.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA0GjD,eAAO,MAAM,MAAM,EAAE,cAoBpB,CAAC"}
@@ -0,0 +1,109 @@
1
+ import { isValidApiKey, maskApiKey, callEntityApi, errorMessage } from "../api/entity-api.js";
2
+ import { getApiKeyFromGlobal, removeApiKeyFromGlobal, upsertApiKeyInGlobal, } from "../config/global-config.js";
3
+ import { loadProjectConfigFromCwd } from "../config/project-config.js";
4
+ import { sessionKey } from "../config/session-key.js";
5
+ import { AbCliError, CLI_PROGRAM } from "../errors.js";
6
+ import { confirmYesNo } from "../io/confirm-yes.js";
7
+ import { readSecretHidden } from "../io/read-credentials.js";
8
+ import { logProgress } from "../progress.js";
9
+ function usage() {
10
+ console.error(`Usage:
11
+ ${CLI_PROGRAM} api-key set [--allow-writes | --read-only] Store an API key for this project's environment (asks for it, hidden)
12
+ ${CLI_PROGRAM} api-key show Show which key is stored (never the secret)
13
+ ${CLI_PROGRAM} api-key remove Forget the stored key
14
+
15
+ The key is used by "${CLI_PROGRAM} api" for every project on this host. Before "set":
16
+ 1. Identities page → open the identity (preferably a service account) → API keys → Create API key
17
+ (short expiry, not unscoped). Copy the key; it is shown only once.
18
+ 2. Open the key and tick the endpoints it may use (Read / Save / Submit / Delete), then Save scopes.
19
+ Run "set" in the project folder, paste the key (nothing is shown) and press Enter.
20
+ Allow writes only on development or test environments.`);
21
+ }
22
+ function requireTerminal() {
23
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
24
+ throw new AbCliError("CONFIG", `${CLI_PROGRAM} api-key set must be run by a person in a terminal (it asks for the key with hidden input).`);
25
+ }
26
+ }
27
+ async function setKey(flags) {
28
+ const allowFlag = flags.includes("--allow-writes");
29
+ const readOnlyFlag = flags.includes("--read-only");
30
+ const unknown = flags.filter((flag) => flag !== "--allow-writes" && flag !== "--read-only");
31
+ if (unknown.length > 0 || (allowFlag && readOnlyFlag)) {
32
+ usage();
33
+ process.exitCode = 1;
34
+ return;
35
+ }
36
+ requireTerminal();
37
+ const project = loadProjectConfigFromCwd();
38
+ const key = sessionKey(project.api_url, project.environment);
39
+ const apiKey = await readSecretHidden(`API key for ${project.api_url} (input hidden): `);
40
+ if (!isValidApiKey(apiKey)) {
41
+ throw new AbCliError("CONFIG", "That is not an Anybuild API key (expected odk_<id>_<secret>). Nothing was stored.");
42
+ }
43
+ // the key is checked before it is stored: 401 means the server does not accept it; 403 only means it has no scope on $metadata
44
+ logProgress("Checking the key…");
45
+ const check = await callEntityApi({
46
+ apiUrl: project.api_url,
47
+ path: `${project.application_id}/$metadata`,
48
+ method: "GET",
49
+ apiKey,
50
+ });
51
+ if (check.status === 401) {
52
+ throw new AbCliError("AUTH_LOGIN", `The server rejected the key (${errorMessage(check) ?? "401"}). Nothing was stored.`);
53
+ }
54
+ if (check.status === 403) {
55
+ logProgress(`Note: the key is valid but has no scope on ${project.application_id}/$metadata. That is fine unless you need $metadata; grant endpoint scopes on the Identities page.`);
56
+ }
57
+ else if (check.status >= 400) {
58
+ logProgress(`Note: checking the key returned HTTP ${check.status} (${errorMessage(check) ?? check.statusText}).`);
59
+ }
60
+ let allowWrites = allowFlag;
61
+ if (!allowFlag && !readOnlyFlag) {
62
+ allowWrites = await confirmYesNo(`Allow writes (POST / PATCH / DELETE) with this key on ${project.api_url}? Only for development or test data. [y/N] `);
63
+ }
64
+ upsertApiKeyInGlobal(key, {
65
+ api_key: apiKey,
66
+ allow_writes: allowWrites,
67
+ saved_at: new Date().toISOString(),
68
+ });
69
+ console.log(`Stored ${maskApiKey(apiKey)} for ${project.api_url} (environment: ${project.environment}), ${allowWrites ? "reads and writes" : "read only"}.`);
70
+ }
71
+ function showKey() {
72
+ const project = loadProjectConfigFromCwd();
73
+ const entry = getApiKeyFromGlobal(sessionKey(project.api_url, project.environment));
74
+ if (!entry) {
75
+ console.log(`No API key stored for ${project.api_url} (environment: ${project.environment}).`);
76
+ return;
77
+ }
78
+ console.log(`${maskApiKey(entry.api_key)} for ${project.api_url} (environment: ${project.environment}), ${entry.allow_writes ? "reads and writes" : "read only"}, stored ${entry.saved_at}.`);
79
+ }
80
+ function removeKey() {
81
+ const project = loadProjectConfigFromCwd();
82
+ const removed = removeApiKeyFromGlobal(sessionKey(project.api_url, project.environment));
83
+ console.log(removed
84
+ ? `Removed the API key for ${project.api_url}. Revoke it on the Identities page if it is no longer needed.`
85
+ : `No API key stored for ${project.api_url}.`);
86
+ }
87
+ export const apiKey = async (args) => {
88
+ const [sub, ...flags] = args;
89
+ try {
90
+ if (sub === "set") {
91
+ await setKey(flags);
92
+ }
93
+ else if (sub === "show" && flags.length === 0) {
94
+ showKey();
95
+ }
96
+ else if (sub === "remove" && flags.length === 0) {
97
+ removeKey();
98
+ }
99
+ else {
100
+ usage();
101
+ process.exitCode = 1;
102
+ }
103
+ }
104
+ catch (e) {
105
+ console.error(`${CLI_PROGRAM} api-key: ${e instanceof Error ? e.message : String(e)}`);
106
+ process.exitCode = 1;
107
+ }
108
+ };
109
+ //# sourceMappingURL=api-key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key.js","sourceRoot":"","sources":["../../src/commands/api-key.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EACL,mBAAmB,EACnB,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD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,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC;IAC7B,IAAI,CAAC;QACH,IAAI,GAAG,KAAK,KAAK,EAAE,CAAC;YAClB,MAAM,MAAM,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;aACI,IAAI,GAAG,KAAK,MAAM,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9C,OAAO,EAAE,CAAC;QACZ,CAAC;aACI,IAAI,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAChD,SAAS,EAAE,CAAC;QACd,CAAC;aACI,CAAC;YACJ,KAAK,EAAE,CAAC;YACR,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,CAAC,KAAK,CAAC,GAAG,WAAW,aAAa,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QACvF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC;AACH,CAAC,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { CommandHandler } from "./types.js";
2
+ export declare const api: CommandHandler;
3
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/commands/api.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAuCjD,eAAO,MAAM,GAAG,EAAE,cAuDjB,CAAC"}
@@ -0,0 +1,89 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { callEntityApi, errorMessage, formatBody, isWriteMethod, parseApiMethod, parseJsonBody, } from "../api/entity-api.js";
3
+ import { getApiKeyFromGlobal } from "../config/global-config.js";
4
+ import { loadProjectConfigFromCwd } from "../config/project-config.js";
5
+ import { sessionKey } from "../config/session-key.js";
6
+ import { AbCliError, CLI_PROGRAM } from "../errors.js";
7
+ function usage() {
8
+ console.error(`Usage: ${CLI_PROGRAM} api <GET|POST|PATCH|DELETE> <path> [--data <json> | --data-file <file>]
9
+
10
+ Calls an entity endpoint of this project's environment with the key stored by "${CLI_PROGRAM} api-key set".
11
+ <path> is relative to /api/, e.g.:
12
+ ${CLI_PROGRAM} api GET "my_app/invoice?\\$top=5&\\$count=true"
13
+ ${CLI_PROGRAM} api POST my_app/invoice --data '{"invoice_number":"INV-1"}'
14
+ ${CLI_PROGRAM} api PATCH "my_app/invoice(<thing_id>)" --data-file body.json
15
+ ${CLI_PROGRAM} api POST "my_app/invoice(<thing_id>)/submit"
16
+
17
+ The response body goes to stdout, the status line to stderr; the exit code is 1 for HTTP errors.`);
18
+ }
19
+ function readBody(flags) {
20
+ let body;
21
+ for (let i = 0; i < flags.length; i++) {
22
+ const flag = flags[i];
23
+ if (flag === "--data" || flag === "--data-file") {
24
+ const value = flags[i + 1];
25
+ if (value === undefined) {
26
+ throw new AbCliError("CONFIG", `${flag} needs a value.`);
27
+ }
28
+ if (body !== undefined) {
29
+ throw new AbCliError("CONFIG", "Give the body once (--data or --data-file).");
30
+ }
31
+ body = flag === "--data"
32
+ ? parseJsonBody(value, "--data")
33
+ : parseJsonBody(readFileSync(value, "utf8"), value);
34
+ i++;
35
+ }
36
+ else {
37
+ throw new AbCliError("CONFIG", `Unknown option ${flag}.`);
38
+ }
39
+ }
40
+ return body;
41
+ }
42
+ export const api = async (args) => {
43
+ const [methodArg, path, ...flags] = args;
44
+ if (methodArg === undefined || path === undefined || methodArg === "--help" || methodArg === "-h") {
45
+ usage();
46
+ process.exitCode = methodArg === undefined || path === undefined ? 1 : 0;
47
+ return;
48
+ }
49
+ try {
50
+ const method = parseApiMethod(methodArg);
51
+ const body = readBody(flags);
52
+ if (body !== undefined && method === "GET") {
53
+ throw new AbCliError("CONFIG", "GET does not take a body.");
54
+ }
55
+ const project = loadProjectConfigFromCwd();
56
+ const entry = getApiKeyFromGlobal(sessionKey(project.api_url, project.environment));
57
+ if (!entry) {
58
+ throw new AbCliError("NO_SESSION", `No API key for ${project.api_url}. A person sets one up once: create an API key on the Identities page (API keys), tick the endpoints it may use, then run "${CLI_PROGRAM} api-key set" in this project folder and paste the key. See "Setting up an API key" in the CLI README.`);
59
+ }
60
+ if (isWriteMethod(method) && !entry.allow_writes) {
61
+ throw new AbCliError("CONFIG", `The API key for ${project.api_url} is stored read only, so ${method} is refused. A person can run "${CLI_PROGRAM} api-key set" again and allow writes (development or test environments only).`);
62
+ }
63
+ const result = await callEntityApi({
64
+ apiUrl: project.api_url,
65
+ path,
66
+ method,
67
+ apiKey: entry.api_key,
68
+ body,
69
+ });
70
+ const formatted = formatBody(result);
71
+ if (formatted) {
72
+ process.stdout.write(formatted.endsWith("\n") ? formatted : `${formatted}\n`);
73
+ }
74
+ const seconds = (result.durationMs / 1000).toFixed(1);
75
+ const status = `HTTP ${result.status}${result.statusText ? ` ${result.statusText}` : ""} (${seconds} s)`;
76
+ if (result.status >= 400) {
77
+ console.error(`${status}: ${errorMessage(result) ?? "request failed"}`);
78
+ process.exitCode = 1;
79
+ }
80
+ else {
81
+ console.error(status);
82
+ }
83
+ }
84
+ catch (e) {
85
+ console.error(`${CLI_PROGRAM} api: ${e instanceof Error ? e.message : String(e)}`);
86
+ process.exitCode = 1;
87
+ }
88
+ };
89
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/commands/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EACL,aAAa,EACb,YAAY,EACZ,UAAU,EACV,aAAa,EACb,cAAc,EACd,aAAa,GACd,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,M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AAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,eAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAOnD,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,eAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAUnD,CAAC"}
@@ -1,9 +1,12 @@
1
+ import { api } from "./api.js";
2
+ import { apiKey } from "./api-key.js";
1
3
  import { clone } from "./clone.js";
2
4
  import { login } from "./login.js";
3
5
  import { logout } from "./logout.js";
4
6
  import { pull } from "./pull.js";
5
7
  import { push } from "./push.js";
6
8
  import { status } from "./status.js";
9
+ import { validate } from "./validate.js";
7
10
  export const commands = {
8
11
  login,
9
12
  logout,
@@ -11,5 +14,8 @@ export const commands = {
11
14
  pull,
12
15
  status,
13
16
  push,
17
+ validate,
18
+ api,
19
+ "api-key": apiKey,
14
20
  };
15
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,MAAM,CAAC,MAAM,QAAQ,GAAmC;IACtD,KAAK;IACL,MAAM;IACN,KAAK;IACL,IAAI;IACJ,MAAM;IACN,IAAI;CACL,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAKzC,MAAM,CAAC,MAAM,QAAQ,GAAmC;IACtD,KAAK;IACL,MAAM;IACN,KAAK;IACL,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,QAAQ;IACR,GAAG;IACH,SAAS,EAAE,MAAM;CAClB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"pull.d.ts","sourceRoot":"","sources":["../../src/commands/pull.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,eAAO,MAAM,IAAI,EAAE,cAoDlB,CAAC"}
1
+ {"version":3,"file":"pull.d.ts","sourceRoot":"","sources":["../../src/commands/pull.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA6DjD,eAAO,MAAM,IAAI,EAAE,cAgElB,CAAC"}