@apotech-os/cli 0.2.0 → 0.4.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/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @apotech-os/cli
2
+
3
+ CLI for Wopilo OS apps: scaffold locally, plan/apply your manifest against a
4
+ server, and publish releases.
5
+
6
+ ```sh
7
+ npm install -g @apotech-os/cli
8
+ ```
9
+
10
+ ## Remotes and login
11
+
12
+ ```sh
13
+ apotech-os remote add --url https://your-server.example.com --as production
14
+ apotech-os login --remote production
15
+ ```
16
+
17
+ `login` starts a browser-based approval (device-code flow): the CLI prints a
18
+ confirmation code and opens the web app, a platform admin checks that the code
19
+ matches and clicks **Autoriser**, and the CLI receives an API key and stores it
20
+ in `~/.wopilo/credentials.json` (mode `0600`).
21
+
22
+ The key is an ordinary platform API key, labelled with the requesting machine
23
+ and revocable at any time under _Paramètres › Clés API_.
24
+
25
+ On a headless machine you can open the printed URL from another device, or skip
26
+ the browser entirely and paste a key you created by hand:
27
+
28
+ ```sh
29
+ apotech-os login --remote production --with-key
30
+ ```
31
+
32
+ Environment variables work too, and take no `--remote`:
33
+
34
+ - `WOPILO_API_URL` — server API root. No `/api` prefix is added automatically.
35
+ - `WOPILO_API_KEY` — Bearer token.
36
+
37
+ ## Commands
38
+
39
+ | Command | What it does |
40
+ | ----------------------------------------------- | ------------------------------------------ |
41
+ | `apotech-os dev` | Watch and rebuild the app manifest locally |
42
+ | `apotech-os build` | Build the app bundle |
43
+ | `apotech-os plan --remote <name>` | Diff the local manifest against the server |
44
+ | `apotech-os apply --remote <name>` | Apply the manifest to the server |
45
+ | `apotech-os publish --remote <name>` | Publish a versioned release |
46
+ | `apotech-os remote add --url <url> --as <name>` | Register a remote |
47
+ | `apotech-os login --remote <name>` | Obtain and store an API key |
48
+
49
+ See `docs/app-platform/app-developer-guide.md` in the repo for the full guide.
package/dist/index.js CHANGED
@@ -22631,7 +22631,10 @@ var RelationDefSchema = external_exports.object({
22631
22631
  var FIELD_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_]*$/;
22632
22632
  var FieldDefSchema = external_exports.object({
22633
22633
  universalIdentifier: external_exports.string().uuid(),
22634
- name: external_exports.string().regex(FIELD_NAME_REGEX, "field name must be a valid identifier (letters, digits, underscore; start with a letter)"),
22634
+ name: external_exports.string().regex(
22635
+ FIELD_NAME_REGEX,
22636
+ "field name must be a valid identifier (letters, digits, underscore; start with a letter)"
22637
+ ),
22635
22638
  type: external_exports.nativeEnum(FieldType),
22636
22639
  label: external_exports.string(),
22637
22640
  description: external_exports.string().optional(),
@@ -22644,7 +22647,8 @@ var IndexDefSchema = external_exports.object({
22644
22647
  universalIdentifier: external_exports.string(),
22645
22648
  // Field names in indexes are subject to the same identifier constraint as FieldDef.name.
22646
22649
  fields: external_exports.array(external_exports.string().regex(FIELD_NAME_REGEX, "index field name must be a valid identifier")).min(1),
22647
- isUnique: external_exports.boolean().optional()
22650
+ isUnique: external_exports.boolean().optional(),
22651
+ aggregateIndex: external_exports.boolean().optional()
22648
22652
  });
22649
22653
  var ViewFilterSchema = external_exports.object({
22650
22654
  field: external_exports.string(),
@@ -22664,10 +22668,23 @@ var ViewDefSchema = external_exports.object({
22664
22668
  sorts: external_exports.array(ViewSortSchema).optional(),
22665
22669
  isDefault: external_exports.boolean().optional()
22666
22670
  });
22667
- var ALLOWED_INTEGRATION_EVENTS = [
22668
- "shopify.order.placed",
22669
- "pipedrive.entity.changed"
22671
+ var RESERVED_EVENT_PREFIXES = [
22672
+ "app-",
22673
+ "app.",
22674
+ "shopify.",
22675
+ "pipedrive.",
22676
+ "app-record."
22670
22677
  ];
22678
+ var CUSTOM_EVENT_NAME_REGEX = /^[a-z][a-z0-9]*([.-][a-z0-9]+)*$/;
22679
+ var CustomEventNameSchema = external_exports.string().regex(
22680
+ CUSTOM_EVENT_NAME_REGEX,
22681
+ 'event name must be lowercase dotted-segments (e.g. "order.fulfilled")'
22682
+ ).refine(
22683
+ (name) => !RESERVED_EVENT_PREFIXES.some((prefix) => name.startsWith(prefix)),
22684
+ {
22685
+ message: `event name starts with a reserved prefix (${RESERVED_EVENT_PREFIXES.join(", ")})`
22686
+ }
22687
+ );
22671
22688
  var FunctionTriggerSchema = external_exports.discriminatedUnion("type", [
22672
22689
  external_exports.object({
22673
22690
  type: external_exports.literal("cron"),
@@ -22687,14 +22704,44 @@ var FunctionTriggerSchema = external_exports.discriminatedUnion("type", [
22687
22704
  }),
22688
22705
  external_exports.object({
22689
22706
  type: external_exports.literal("event"),
22690
- /** Integration event name. Must be in ALLOWED_INTEGRATION_EVENTS. */
22691
- name: external_exports.enum(ALLOWED_INTEGRATION_EVENTS)
22707
+ /**
22708
+ * Event name for function triggers. Accepts:
22709
+ * - Integration events from ALLOWED_INTEGRATION_EVENTS (e.g. 'shopify.order.placed')
22710
+ * - Custom events declared in the same manifest's `emits` array (e.g. 'order.fulfilled')
22711
+ *
22712
+ * Cross-manifest validation (custom name ∈ manifest.emits) is enforced by
22713
+ * AppSyncService.validateManifestConstraints, not here in the Zod schema.
22714
+ */
22715
+ name: external_exports.string()
22692
22716
  })
22693
22717
  ]);
22694
22718
  var FunctionDefSchema = external_exports.object({
22695
22719
  universalIdentifier: external_exports.string(),
22696
22720
  name: external_exports.string(),
22697
- trigger: FunctionTriggerSchema
22721
+ trigger: FunctionTriggerSchema,
22722
+ /**
22723
+ * P9 — Maximum retry attempts for this function (0 = no retries, fail immediately).
22724
+ * Capped by the shared router's maximum (currently 4). When absent the router
22725
+ * default of 4 applies.
22726
+ */
22727
+ retries: external_exports.number().int().min(0).optional(),
22728
+ /**
22729
+ * P9 — Best-effort concurrency hint for this function.
22730
+ *
22731
+ * NOTE — DOCUMENTED LIMITATION: Under the shared-router dispatch model the platform
22732
+ * cannot attach a per-app-function Inngest concurrency limit because there is no
22733
+ * per-app-function Inngest function. This value is stored in the manifest and
22734
+ * validated, but is NOT enforced at the Inngest level. A warning is logged at app
22735
+ * sync time so operators are aware. Enforcement would require migrating to
22736
+ * per-function Inngest registrations, which is out of scope for P9.
22737
+ */
22738
+ concurrency: external_exports.number().int().min(1).optional(),
22739
+ /**
22740
+ * P9 — Name of an intra-app event or function to fire on terminal failure.
22741
+ * Must be a name declared in manifest.emits OR the name of another function in
22742
+ * the same app. Cross-manifest validation is enforced by AppSyncService.
22743
+ */
22744
+ onFailure: external_exports.string().optional()
22698
22745
  });
22699
22746
  var AppRoleSchema = external_exports.object({
22700
22747
  reads: external_exports.array(external_exports.string()),
@@ -22704,16 +22751,48 @@ var AppRoleSchema = external_exports.object({
22704
22751
  * action: '*' grants access to all actions for the provider (wildcard).
22705
22752
  * provider: 'llm' with action: 'complete' grants LLM access.
22706
22753
  */
22707
- actions: external_exports.array(external_exports.object({ provider: external_exports.string(), action: external_exports.string() }))
22754
+ actions: external_exports.array(external_exports.object({ provider: external_exports.string(), action: external_exports.string() })),
22755
+ /**
22756
+ * Framework primitive capabilities granted to the app token.
22757
+ * Each string is a capability name, e.g. 'inbox'.
22758
+ * Absence means the capability is denied (deny-by-default, backward-compatible).
22759
+ * P2 approvals will reuse this field.
22760
+ */
22761
+ capabilities: external_exports.array(external_exports.string()).optional()
22708
22762
  });
22709
22763
  var PageDefSchema = external_exports.object({
22710
22764
  universalIdentifier: external_exports.string().uuid(),
22711
- path: external_exports.string().regex(/^[a-zA-Z0-9_-]+$/, "page path must be a simple slug (letters, digits, hyphens, underscores)"),
22765
+ path: external_exports.string().regex(
22766
+ /^[a-zA-Z0-9_-]+$/,
22767
+ "page path must be a simple slug (letters, digits, hyphens, underscores)"
22768
+ ),
22712
22769
  title: external_exports.string(),
22713
22770
  icon: external_exports.string().optional(),
22714
22771
  entry: external_exports.string()
22715
22772
  // relative path inside the tarball, e.g. 'dist/ui/attribution.js'
22716
22773
  });
22774
+ var SettingsFieldSchema = external_exports.object({
22775
+ key: external_exports.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/, "settings key must be a valid identifier"),
22776
+ type: external_exports.enum(["string", "number", "boolean", "select", "json"]),
22777
+ label: external_exports.string(),
22778
+ default: external_exports.unknown().optional(),
22779
+ options: external_exports.array(external_exports.string()).optional(),
22780
+ /** `secret: false` is the only allowed value — omitted is equivalent to false.
22781
+ * True is rejected so that secret values cannot accidentally land in settings. */
22782
+ secret: external_exports.literal(false).optional()
22783
+ });
22784
+ var AppSettingsSchema = external_exports.object({
22785
+ fields: external_exports.array(SettingsFieldSchema)
22786
+ });
22787
+ var PROMPT_NAME_REGEX = /^[a-z][a-z0-9]*([.\-/][a-z0-9]+)*$/;
22788
+ var PromptDefSchema = external_exports.object({
22789
+ name: external_exports.string().regex(
22790
+ PROMPT_NAME_REGEX,
22791
+ "prompt name must be lowercase segments separated by dots, hyphens, or slashes"
22792
+ ),
22793
+ template: external_exports.string(),
22794
+ labels: external_exports.array(external_exports.string()).optional()
22795
+ });
22717
22796
  var AppManifestSchema = external_exports.object({
22718
22797
  universalIdentifier: external_exports.string().uuid(),
22719
22798
  slug: external_exports.string().regex(/^[a-z][a-z0-9-]*$/),
@@ -22724,7 +22803,7 @@ var AppManifestSchema = external_exports.object({
22724
22803
  description: external_exports.string().optional(),
22725
22804
  icon: external_exports.string(),
22726
22805
  color: external_exports.string(),
22727
- // tailwind token, e.g. 'space-pilotage'
22806
+ // tailwind token, e.g. 'space-brand'
22728
22807
  placeholder: external_exports.boolean().optional(),
22729
22808
  // true for spaces with no views yet
22730
22809
  reads: external_exports.array(external_exports.string()),
@@ -22741,7 +22820,10 @@ var AppManifestSchema = external_exports.object({
22741
22820
  universalIdentifier: external_exports.string().uuid(),
22742
22821
  // objectKey allows letters, digits, hyphens, dots (e.g. 'shopify-order.v1', 'product').
22743
22822
  // Bars SQL-injection chars: no quotes, semicolons, spaces, or control chars.
22744
- objectKey: external_exports.string().regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/, "objectKey must start with a letter and contain only letters, digits, hyphens, dots"),
22823
+ objectKey: external_exports.string().regex(
22824
+ /^[a-zA-Z][a-zA-Z0-9._-]*$/,
22825
+ "objectKey must start with a letter and contain only letters, digits, hyphens, dots"
22826
+ ),
22745
22827
  labelSingular: external_exports.string(),
22746
22828
  labelPlural: external_exports.string(),
22747
22829
  description: external_exports.string().optional(),
@@ -22777,35 +22859,45 @@ var AppManifestSchema = external_exports.object({
22777
22859
  targetRef: external_exports.string(),
22778
22860
  fields: external_exports.array(FieldDefSchema)
22779
22861
  })
22780
- ).optional()
22862
+ ).optional(),
22863
+ /** P7 — Per-app settings schema. Optional; manifests without this field still validate. */
22864
+ settings: AppSettingsSchema.optional(),
22865
+ /**
22866
+ * P3 — Managed prompt definitions seeded to Langfuse on app install/sync.
22867
+ * Each entry creates or versions a prompt in Langfuse under the given name.
22868
+ * Optional; absence is backward-compatible.
22869
+ */
22870
+ prompts: external_exports.array(PromptDefSchema).optional(),
22871
+ /**
22872
+ * P5 — Custom events this app is allowed to emit via ctx.api.events.send().
22873
+ * Each name must match the safe dotted-lowercase pattern and must not start
22874
+ * with a reserved prefix (app-, shopify., pipedrive., app-record.).
22875
+ * Functions declaring trigger: { type: 'event', name } must use a name that
22876
+ * is either in ALLOWED_INTEGRATION_EVENTS or in this emits array.
22877
+ */
22878
+ emits: external_exports.array(CustomEventNameSchema).optional()
22781
22879
  });
22782
22880
  var ShopifyOrderV1Schema = external_exports.object({
22783
22881
  id: external_exports.string(),
22784
22882
  shopifyId: external_exports.string(),
22785
22883
  createdAt: external_exports.coerce.date(),
22786
22884
  totalPrice: external_exports.number(),
22787
- // maps to totalPriceTTC in DB
22788
22885
  subtotalPrice: external_exports.number().nullable(),
22789
- // subtotalPriceSet (nullable until re-synced)
22790
22886
  totalDiscounts: external_exports.number().nullable(),
22791
- // totalDiscountsSet (nullable until re-synced)
22792
22887
  discountCode: external_exports.string().nullable(),
22793
22888
  newOrRepeat: external_exports.string().nullable(),
22794
22889
  financialStatus: external_exports.string().nullable(),
22795
22890
  note: external_exports.string().nullable(),
22796
- // maps to grapevineRaw in DB (order.note)
22797
22891
  customerId: external_exports.string().nullable()
22798
22892
  });
22799
22893
  var shopifyOrderV1 = {
22800
22894
  key: "shopify-order.v1",
22801
- prismaModel: "PilotageOrder",
22802
- appRecord: { appSlug: "pilotage", objectKey: "pilotage-order" },
22895
+ prismaModel: "AppRecord",
22896
+ appRecord: { appSlug: "_core", objectKey: "shopify-order" },
22803
22897
  schema: ShopifyOrderV1Schema,
22804
22898
  requiredRole: "VIEWER"
22805
22899
  };
22806
- var CORE_OBJECTS = /* @__PURE__ */ new Map([
22807
- [shopifyOrderV1.key, shopifyOrderV1]
22808
- ]);
22900
+ var CORE_OBJECTS = /* @__PURE__ */ new Map([[shopifyOrderV1.key, shopifyOrderV1]]);
22809
22901
 
22810
22902
  // src/manifest-build.ts
22811
22903
  var ManifestBuildError = class extends Error {
@@ -22891,7 +22983,7 @@ async function buildApp(projectRoot, tarball) {
22891
22983
  (0, import_fs4.writeFileSync)(checksumPath, checksum2, "utf8");
22892
22984
  const tgzFiles = {
22893
22985
  "manifest.json": stamped,
22894
- "checksum": checksum2
22986
+ checksum: checksum2
22895
22987
  };
22896
22988
  if (bundleBuffer) {
22897
22989
  tgzFiles["dist/index.js"] = bundleBuffer;
@@ -22903,13 +22995,33 @@ async function buildApp(projectRoot, tarball) {
22903
22995
  tarballPath = (0, import_path2.join)(outputDir, `${manifest.slug}-${manifest.version}.tgz`);
22904
22996
  (0, import_fs4.writeFileSync)(tarballPath, tgzContent);
22905
22997
  tarballChecksum = (0, import_crypto.createHash)("sha256").update(tgzContent).digest("hex");
22906
- return { manifest: stamped, outputDir, manifestPath, checksumPath, checksum: checksum2, tarballPath, tarballChecksum, hasBundle, uiPageCount };
22998
+ return {
22999
+ manifest: stamped,
23000
+ outputDir,
23001
+ manifestPath,
23002
+ checksumPath,
23003
+ checksum: checksum2,
23004
+ tarballPath,
23005
+ tarballChecksum,
23006
+ hasBundle,
23007
+ uiPageCount
23008
+ };
22907
23009
  }
22908
23010
  const serialized = JSON.stringify(manifest);
22909
23011
  const checksum = (0, import_crypto.createHash)("sha256").update(serialized).digest("hex");
22910
23012
  (0, import_fs4.writeFileSync)(manifestPath, JSON.stringify(manifest, null, 2), "utf8");
22911
23013
  (0, import_fs4.writeFileSync)(checksumPath, checksum, "utf8");
22912
- return { manifest, outputDir, manifestPath, checksumPath, checksum, tarballPath, tarballChecksum, hasBundle, uiPageCount };
23014
+ return {
23015
+ manifest,
23016
+ outputDir,
23017
+ manifestPath,
23018
+ checksumPath,
23019
+ checksum,
23020
+ tarballPath,
23021
+ tarballChecksum,
23022
+ hasBundle,
23023
+ uiPageCount
23024
+ };
22913
23025
  }
22914
23026
  async function compileBundleIfExists(projectRoot, outputDir) {
22915
23027
  const entryPoint = (0, import_path2.join)(projectRoot, "src", "index.ts");
@@ -22935,7 +23047,13 @@ async function compileBundleIfExists(projectRoot, outputDir) {
22935
23047
  async function compileUiPages(projectRoot, outputDir, pages) {
22936
23048
  const result = /* @__PURE__ */ new Map();
22937
23049
  if (pages.length === 0) return result;
22938
- const UI_EXTERNALS = ["react", "react-dom", "react-dom/client", "react/jsx-runtime", "@apotech-os/ui-sdk"];
23050
+ const UI_EXTERNALS = [
23051
+ "react",
23052
+ "react-dom",
23053
+ "react-dom/client",
23054
+ "react/jsx-runtime",
23055
+ "@apotech-os/ui-sdk"
23056
+ ];
22939
23057
  for (const page of pages) {
22940
23058
  const entryPoint = (0, import_path2.join)(projectRoot, "src", "ui", `${page.path}.tsx`);
22941
23059
  if (!(0, import_fs4.existsSync)(entryPoint)) continue;
@@ -23007,7 +23125,9 @@ function buildTarHeader(name, size) {
23007
23125
  Buffer.from("0000000\0").copy(header, 108);
23008
23126
  Buffer.from("0000000\0").copy(header, 116);
23009
23127
  Buffer.from(size.toString(8).padStart(11, "0") + " ").copy(header, 124);
23010
- Buffer.from(Math.floor(Date.now() / 1e3).toString(8).padStart(11, "0") + " ").copy(header, 136);
23128
+ Buffer.from(
23129
+ Math.floor(Date.now() / 1e3).toString(8).padStart(11, "0") + " "
23130
+ ).copy(header, 136);
23011
23131
  header[156] = 48;
23012
23132
  Buffer.from("ustar\0").copy(header, 257);
23013
23133
  Buffer.from("00").copy(header, 263);
@@ -23108,10 +23228,14 @@ function renderPlan(response) {
23108
23228
  const symbol2 = OP_SYMBOL[action.op];
23109
23229
  const label = OP_LABEL[action.op];
23110
23230
  const marker = action.destructive ? " [destructive]" : "";
23111
- lines.push(` ${symbol2} ${label} ${action.entityType} "${action.name}" (${action.universalIdentifier})${marker}`);
23231
+ lines.push(
23232
+ ` ${symbol2} ${label} ${action.entityType} "${action.name}" (${action.universalIdentifier})${marker}`
23233
+ );
23112
23234
  if (action.changes) {
23113
23235
  for (const change of action.changes) {
23114
- lines.push(` ${change.attribute}: ${JSON.stringify(change.from)} \u2192 ${JSON.stringify(change.to)}`);
23236
+ lines.push(
23237
+ ` ${change.attribute}: ${JSON.stringify(change.from)} \u2192 ${JSON.stringify(change.to)}`
23238
+ );
23115
23239
  }
23116
23240
  }
23117
23241
  }
@@ -23150,7 +23274,9 @@ function listRemotes() {
23150
23274
  function storeApiKey(remoteName, key) {
23151
23275
  const data = readFile();
23152
23276
  if (!data.remotes[remoteName]) {
23153
- throw new Error(`Remote "${remoteName}" not found. Add it first with: apotech-os remote add --url <url> --as ${remoteName}`);
23277
+ throw new Error(
23278
+ `Remote "${remoteName}" not found. Add it first with: apotech-os remote add --url <url> --as ${remoteName}`
23279
+ );
23154
23280
  }
23155
23281
  data.credentials[remoteName] = key;
23156
23282
  writeFile(data);
@@ -23159,7 +23285,9 @@ function getRemoteUrl(remoteName) {
23159
23285
  const data = readFile();
23160
23286
  const remote = data.remotes[remoteName];
23161
23287
  if (!remote) {
23162
- throw new Error(`Remote "${remoteName}" not found. Add it first with: apotech-os remote add --url <url> --as ${remoteName}`);
23288
+ throw new Error(
23289
+ `Remote "${remoteName}" not found. Add it first with: apotech-os remote add --url <url> --as ${remoteName}`
23290
+ );
23163
23291
  }
23164
23292
  return remote.url;
23165
23293
  }
@@ -23220,7 +23348,9 @@ function buildDevCommand() {
23220
23348
  console.log(renderPlan(response));
23221
23349
  }
23222
23350
  if (response.applied) {
23223
- console.log(`[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] Synced (${response.summary.toAdd}+${response.summary.toChange}~${response.summary.toDestroy}-)`);
23351
+ console.log(
23352
+ `[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] Synced (${response.summary.toAdd}+${response.summary.toChange}~${response.summary.toDestroy}-)`
23353
+ );
23224
23354
  }
23225
23355
  await tryDevReload(projectRoot, baseUrl, apiKey, manifest.slug);
23226
23356
  } catch (err) {
@@ -23239,13 +23369,18 @@ function buildDevCommand() {
23239
23369
  } catch {
23240
23370
  return;
23241
23371
  }
23242
- if (!buildOutput.tarballPath || !buildOutput.tarballChecksum || !buildOutput.hasBundle) return;
23372
+ if (!buildOutput.tarballPath || !buildOutput.tarballChecksum || !buildOutput.hasBundle)
23373
+ return;
23243
23374
  const tarball = (0, import_fs6.readFileSync)(buildOutput.tarballPath);
23244
23375
  const checksum = (0, import_crypto2.createHash)("sha256").update(tarball).digest("hex");
23245
23376
  const url2 = `${serverUrl.replace(/\/$/, "")}/platform/apps/${encodeURIComponent(slug)}/dev-reload`;
23246
23377
  const form = new FormData();
23247
23378
  form.append("metadata", JSON.stringify({ slug, version: "dev", checksum }));
23248
- form.append("artifact", new Blob([tarball], { type: "application/gzip" }), `${slug}-dev.tgz`);
23379
+ form.append(
23380
+ "artifact",
23381
+ new Blob([tarball], { type: "application/gzip" }),
23382
+ `${slug}-dev.tgz`
23383
+ );
23249
23384
  const headers = {};
23250
23385
  if (key) headers["Authorization"] = `Bearer ${key}`;
23251
23386
  try {
@@ -23295,15 +23430,19 @@ function buildDevCommand() {
23295
23430
 
23296
23431
  // src/commands/plan.ts
23297
23432
  function buildPlanCommand() {
23298
- return new Command("plan").description("Compute a diff plan (zero writes)").option("--remote <name>", "Named remote server to target").action(async (opts) => {
23433
+ return new Command("plan").description("Compute a diff plan (zero writes)").option("--remote <name>", "Named remote server to target").option("--json", "Output JSON instead of human-readable text").action(async (opts) => {
23299
23434
  const projectRoot = process.cwd();
23300
23435
  let manifest;
23301
23436
  try {
23302
23437
  manifest = await buildManifest(projectRoot);
23303
23438
  } catch (err) {
23304
23439
  if (err instanceof ManifestBuildError) {
23305
- console.error(`[MANIFEST_BUILD_FAILED] ${err.message}`);
23306
- console.error(err.diagnostic);
23440
+ if (opts.json) {
23441
+ console.log(JSON.stringify({ ok: false, error: err.code, diagnostic: err.diagnostic }));
23442
+ } else {
23443
+ console.error(`[MANIFEST_BUILD_FAILED] ${err.message}`);
23444
+ console.error(err.diagnostic);
23445
+ }
23307
23446
  process.exit(1);
23308
23447
  }
23309
23448
  throw err;
@@ -23312,10 +23451,18 @@ function buildPlanCommand() {
23312
23451
  const apiKey = resolveApiKey(opts.remote);
23313
23452
  try {
23314
23453
  const response = await syncManifest({ baseUrl, apiKey, manifest, mode: "plan" });
23315
- console.log(renderPlan(response));
23454
+ if (opts.json) {
23455
+ console.log(JSON.stringify(response));
23456
+ } else {
23457
+ console.log(renderPlan(response));
23458
+ }
23316
23459
  } catch (err) {
23317
23460
  if (err instanceof ApiError) {
23318
- console.error(`Server error (${err.status}): ${err.message}`);
23461
+ if (opts.json) {
23462
+ console.log(JSON.stringify({ ok: false, status: err.status, error: err.message }));
23463
+ } else {
23464
+ console.error(`Server error (${err.status}): ${err.message}`);
23465
+ }
23319
23466
  process.exit(1);
23320
23467
  }
23321
23468
  throw err;
@@ -23402,14 +23549,102 @@ function buildRemoteCommand() {
23402
23549
  }
23403
23550
 
23404
23551
  // src/commands/login.ts
23552
+ var import_child_process = require("child_process");
23553
+ var import_os4 = require("os");
23554
+ function clientLabel() {
23555
+ try {
23556
+ return `${(0, import_os4.userInfo)().username}@${(0, import_os4.hostname)()}`;
23557
+ } catch {
23558
+ return (0, import_os4.hostname)();
23559
+ }
23560
+ }
23561
+ function openBrowser(url2) {
23562
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
23563
+ try {
23564
+ const child = (0, import_child_process.spawn)(command, [url2], {
23565
+ detached: true,
23566
+ stdio: "ignore",
23567
+ shell: process.platform === "win32"
23568
+ });
23569
+ child.on("error", () => void 0);
23570
+ child.unref();
23571
+ } catch {
23572
+ }
23573
+ }
23574
+ function sleep(ms) {
23575
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
23576
+ }
23577
+ async function postJson(url2, body) {
23578
+ const res = await fetch(url2, {
23579
+ method: "POST",
23580
+ headers: { "Content-Type": "application/json" },
23581
+ body: JSON.stringify(body)
23582
+ });
23583
+ const parsed = await res.json().catch(() => void 0);
23584
+ return { status: res.status, body: parsed };
23585
+ }
23586
+ async function promptForKey(remote) {
23587
+ const passwordMod = await Promise.resolve().then(() => (init_esm5(), esm_exports2));
23588
+ const password = passwordMod.default;
23589
+ const key = await password({ message: `API key for "${remote}":` });
23590
+ storeApiKey(remote, key);
23591
+ console.log(`Credentials stored for remote "${remote}".`);
23592
+ }
23593
+ async function browserLogin(remote, baseUrl) {
23594
+ const device = await postJson(`${baseUrl.replace(/\/$/, "")}/platform/cli-auth/device`, {
23595
+ clientLabel: clientLabel()
23596
+ });
23597
+ if (device.status === 404) {
23598
+ console.log("This server does not support browser login yet \u2014 falling back to an API key.");
23599
+ console.log("Create one in the web app under Param\xE8tres \u203A Cl\xE9s API.");
23600
+ await promptForKey(remote);
23601
+ return;
23602
+ }
23603
+ if (device.status >= 400) {
23604
+ throw new Error(`Could not start the login flow (HTTP ${device.status}).`);
23605
+ }
23606
+ const auth = device.body;
23607
+ console.log(`Opening ${auth.verificationUriComplete} in your browser\u2026`);
23608
+ console.log(` Confirmation code: ${auth.userCode}`);
23609
+ console.log(" (If the browser did not open, visit the URL above.)");
23610
+ openBrowser(auth.verificationUriComplete);
23611
+ const key = await pollForKey(baseUrl, auth);
23612
+ storeApiKey(remote, key);
23613
+ console.log(`Logged in to remote "${remote}". Credentials stored in ~/.wopilo/credentials.json.`);
23614
+ }
23615
+ async function pollForKey(baseUrl, auth) {
23616
+ const tokenUrl = `${baseUrl.replace(/\/$/, "")}/platform/cli-auth/token`;
23617
+ const deadline = Date.now() + auth.expiresIn * 1e3;
23618
+ process.stdout.write("Waiting for approval\u2026 ");
23619
+ while (Date.now() < deadline) {
23620
+ await sleep(auth.interval * 1e3);
23621
+ if (Date.now() >= deadline) break;
23622
+ const res = await postJson(tokenUrl, { deviceCode: auth.deviceCode });
23623
+ const result = res.body;
23624
+ if (result?.status === "approved") {
23625
+ console.log("\u2713");
23626
+ return result.apiKey;
23627
+ }
23628
+ if (result?.status === "denied") {
23629
+ console.log("\u2717");
23630
+ throw new Error("Login was denied in the browser.");
23631
+ }
23632
+ if (result?.status === "expired") {
23633
+ console.log("\u2717");
23634
+ throw new Error("Login request expired. Run the command again.");
23635
+ }
23636
+ }
23637
+ console.log("\u2717");
23638
+ throw new Error("Login request expired. Run the command again.");
23639
+ }
23405
23640
  function buildLoginCommand() {
23406
- return new Command("login").description("Store an API key for a remote server").requiredOption("--remote <name>", "Remote alias").action(async (opts) => {
23407
- getRemoteUrl(opts.remote);
23408
- const passwordMod = await Promise.resolve().then(() => (init_esm5(), esm_exports2));
23409
- const password = passwordMod.default;
23410
- const key = await password({ message: `API key for "${opts.remote}":` });
23411
- storeApiKey(opts.remote, key);
23412
- console.log(`Credentials stored for remote "${opts.remote}".`);
23641
+ return new Command("login").description("Log in to a remote server (opens your browser)").requiredOption("--remote <name>", "Remote alias").option("--with-key", "Paste an existing API key instead of using the browser (CI/headless)").action(async (opts) => {
23642
+ const baseUrl = getRemoteUrl(opts.remote);
23643
+ if (opts.withKey) {
23644
+ await promptForKey(opts.remote);
23645
+ return;
23646
+ }
23647
+ await browserLogin(opts.remote, baseUrl);
23413
23648
  });
23414
23649
  }
23415
23650
 
@@ -23528,7 +23763,9 @@ function buildPublishCommand() {
23528
23763
  } catch (err) {
23529
23764
  if (err instanceof ApiError) {
23530
23765
  if (opts.json) {
23531
- console.log(JSON.stringify({ error: String(err.status), message: err.message, body: err.body }));
23766
+ console.log(
23767
+ JSON.stringify({ error: String(err.status), message: err.message, body: err.body })
23768
+ );
23532
23769
  } else {
23533
23770
  console.error(`Server error (${err.status}): ${err.message}`);
23534
23771
  }