@apotech-os/cli 0.5.0-rc.1 → 0.6.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/dist/index.js CHANGED
@@ -6132,13 +6132,13 @@ function createPrompt(view) {
6132
6132
  const { promise: promise2, resolve: resolve4, reject } = PromisePolyfill.withResolver();
6133
6133
  const cancel = () => reject(new CancelPromptError());
6134
6134
  if (signal) {
6135
- const abort = () => reject(new AbortPromptError({ cause: signal.reason }));
6135
+ const abort2 = () => reject(new AbortPromptError({ cause: signal.reason }));
6136
6136
  if (signal.aborted) {
6137
- abort();
6137
+ abort2();
6138
6138
  return Object.assign(promise2, { cancel });
6139
6139
  }
6140
- signal.addEventListener("abort", abort);
6141
- cleanups.add(() => signal.removeEventListener("abort", abort));
6140
+ signal.addEventListener("abort", abort2);
6141
+ cleanups.add(() => signal.removeEventListener("abort", abort2));
6142
6142
  }
6143
6143
  cleanups.add(onExit((code, signal2) => {
6144
6144
  reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal2}`));
@@ -6362,6 +6362,10 @@ var {
6362
6362
  Help
6363
6363
  } = import_index.default;
6364
6364
 
6365
+ // src/index.ts
6366
+ var import_fs8 = require("fs");
6367
+ var import_path6 = require("path");
6368
+
6365
6369
  // ../../node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js
6366
6370
  var import_fs2 = require("fs");
6367
6371
  var import_promises3 = require("fs/promises");
@@ -6515,10 +6519,10 @@ var ReaddirpStream = class extends import_node_stream.Readable {
6515
6519
  }
6516
6520
  async _formatEntry(dirent, path) {
6517
6521
  let entry;
6518
- const basename3 = this._isDirent ? dirent.name : dirent;
6522
+ const basename4 = this._isDirent ? dirent.name : dirent;
6519
6523
  try {
6520
- const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path, basename3));
6521
- entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename3 };
6524
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path, basename4));
6525
+ entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename4 };
6522
6526
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
6523
6527
  } catch (err) {
6524
6528
  this._onError(err);
@@ -7057,9 +7061,9 @@ var NodeFsHandler = class {
7057
7061
  _watchWithNodeFs(path, listener) {
7058
7062
  const opts = this.fsw.options;
7059
7063
  const directory = sysPath.dirname(path);
7060
- const basename3 = sysPath.basename(path);
7064
+ const basename4 = sysPath.basename(path);
7061
7065
  const parent = this.fsw._getWatchedDir(directory);
7062
- parent.add(basename3);
7066
+ parent.add(basename4);
7063
7067
  const absolutePath = sysPath.resolve(path);
7064
7068
  const options = {
7065
7069
  persistent: opts.persistent
@@ -7069,7 +7073,7 @@ var NodeFsHandler = class {
7069
7073
  let closer;
7070
7074
  if (opts.usePolling) {
7071
7075
  const enableBin = opts.interval !== opts.binaryInterval;
7072
- options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval;
7076
+ options.interval = enableBin && isBinaryPath(basename4) ? opts.binaryInterval : opts.interval;
7073
7077
  closer = setFsWatchFileListener(path, absolutePath, options, {
7074
7078
  listener,
7075
7079
  rawEmitter: this.fsw._emitRaw
@@ -7091,11 +7095,11 @@ var NodeFsHandler = class {
7091
7095
  if (this.fsw.closed) {
7092
7096
  return;
7093
7097
  }
7094
- const dirname3 = sysPath.dirname(file2);
7095
- const basename3 = sysPath.basename(file2);
7096
- const parent = this.fsw._getWatchedDir(dirname3);
7098
+ const dirname4 = sysPath.dirname(file2);
7099
+ const basename4 = sysPath.basename(file2);
7100
+ const parent = this.fsw._getWatchedDir(dirname4);
7097
7101
  let prevStats = stats;
7098
- if (parent.has(basename3))
7102
+ if (parent.has(basename4))
7099
7103
  return;
7100
7104
  const listener = async (path, newStats) => {
7101
7105
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
@@ -7120,9 +7124,9 @@ var NodeFsHandler = class {
7120
7124
  prevStats = newStats2;
7121
7125
  }
7122
7126
  } catch (error51) {
7123
- this.fsw._remove(dirname3, basename3);
7127
+ this.fsw._remove(dirname4, basename4);
7124
7128
  }
7125
- } else if (parent.has(basename3)) {
7129
+ } else if (parent.has(basename4)) {
7126
7130
  const at = newStats.atimeMs;
7127
7131
  const mt = newStats.mtimeMs;
7128
7132
  if (!at || at <= mt || mt !== prevStats.mtimeMs) {
@@ -22650,9 +22654,21 @@ var IndexDefSchema = external_exports.object({
22650
22654
  isUnique: external_exports.boolean().optional(),
22651
22655
  aggregateIndex: external_exports.boolean().optional()
22652
22656
  });
22657
+ var VIEW_FILTER_OPS = [
22658
+ "eq",
22659
+ "neq",
22660
+ "contains",
22661
+ "ncontains",
22662
+ "gt",
22663
+ "lt",
22664
+ "gte",
22665
+ "lte",
22666
+ "empty",
22667
+ "nempty"
22668
+ ];
22653
22669
  var ViewFilterSchema = external_exports.object({
22654
22670
  field: external_exports.string(),
22655
- op: external_exports.enum(["eq", "neq", "contains", "gte", "lte"]),
22671
+ op: external_exports.enum(VIEW_FILTER_OPS),
22656
22672
  value: external_exports.unknown()
22657
22673
  });
22658
22674
  var ViewSortSchema = external_exports.object({
@@ -22679,12 +22695,9 @@ var CUSTOM_EVENT_NAME_REGEX = /^[a-z][a-z0-9]*([.-][a-z0-9]+)*$/;
22679
22695
  var CustomEventNameSchema = external_exports.string().regex(
22680
22696
  CUSTOM_EVENT_NAME_REGEX,
22681
22697
  '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
- );
22698
+ ).refine((name) => !RESERVED_EVENT_PREFIXES.some((prefix) => name.startsWith(prefix)), {
22699
+ message: `event name starts with a reserved prefix (${RESERVED_EVENT_PREFIXES.join(", ")})`
22700
+ });
22688
22701
  var FunctionTriggerSchema = external_exports.discriminatedUnion("type", [
22689
22702
  external_exports.object({
22690
22703
  type: external_exports.literal("cron"),
@@ -22810,6 +22823,14 @@ var SettingsFieldSchema = external_exports.object({
22810
22823
  var AppSettingsSchema = external_exports.object({
22811
22824
  fields: external_exports.array(SettingsFieldSchema)
22812
22825
  });
22826
+ var SETTINGS_ENTRY_REGEX = /^dist\/ui\/[A-Za-z0-9_-]+\.js$/;
22827
+ var SettingsPageSchema = external_exports.object({
22828
+ universalIdentifier: external_exports.string().uuid(),
22829
+ /** Relative path inside the tarball, e.g. 'dist/ui/settings.js'. */
22830
+ entry: external_exports.string().regex(SETTINGS_ENTRY_REGEX, "settingsPage entry must be a 'dist/ui/<name>.js' path"),
22831
+ /** Page heading; defaults to "Paramètres" in the shell. */
22832
+ title: external_exports.string().optional()
22833
+ });
22813
22834
  var PROMPT_NAME_REGEX = /^[a-z][a-z0-9]*([.\-/][a-z0-9]+)*$/;
22814
22835
  var PromptDefSchema = external_exports.object({
22815
22836
  name: external_exports.string().regex(
@@ -22819,7 +22840,7 @@ var PromptDefSchema = external_exports.object({
22819
22840
  template: external_exports.string(),
22820
22841
  labels: external_exports.array(external_exports.string()).optional()
22821
22842
  });
22822
- var AppManifestSchema = external_exports.object({
22843
+ var AppManifestFieldsSchema = external_exports.object({
22823
22844
  universalIdentifier: external_exports.string().uuid(),
22824
22845
  slug: external_exports.string().regex(/^[a-z][a-z0-9-]*$/),
22825
22846
  // = contextId for RBAC
@@ -22888,6 +22909,9 @@ var AppManifestSchema = external_exports.object({
22888
22909
  ).optional(),
22889
22910
  /** P7 — Per-app settings schema. Optional; manifests without this field still validate. */
22890
22911
  settings: AppSettingsSchema.optional(),
22912
+ /** Custom settings page mounted under Paramètres › Espaces. Requires a
22913
+ * non-empty `settings.fields` — enforced by the refinements below. */
22914
+ settingsPage: SettingsPageSchema.optional(),
22891
22915
  /**
22892
22916
  * P3 — Managed prompt definitions seeded to Langfuse on app install/sync.
22893
22917
  * Each entry creates or versions a prompt in Langfuse under the given name.
@@ -22903,6 +22927,39 @@ var AppManifestSchema = external_exports.object({
22903
22927
  */
22904
22928
  emits: external_exports.array(CustomEventNameSchema).optional()
22905
22929
  });
22930
+ var AppManifestSchema = AppManifestFieldsSchema.superRefine((manifest, ctx) => {
22931
+ const settingsPage = manifest.settingsPage;
22932
+ if (!settingsPage) return;
22933
+ if (!manifest.settings || manifest.settings.fields.length === 0) {
22934
+ ctx.addIssue({
22935
+ code: "custom",
22936
+ path: ["settingsPage"],
22937
+ message: "settingsPage requires a non-empty settings.fields"
22938
+ });
22939
+ }
22940
+ const pages = manifest.pages ?? [];
22941
+ if (pages.some((page) => page.entry === settingsPage.entry)) {
22942
+ ctx.addIssue({
22943
+ code: "custom",
22944
+ path: ["settingsPage", "entry"],
22945
+ message: "settingsPage.entry must differ from every pages[].entry"
22946
+ });
22947
+ }
22948
+ if (pages.some((page) => `dist/ui/${page.path}.js` === settingsPage.entry)) {
22949
+ ctx.addIssue({
22950
+ code: "custom",
22951
+ path: ["settingsPage", "entry"],
22952
+ message: "settingsPage.entry collides with the bundle the CLI emits for a pages[] path"
22953
+ });
22954
+ }
22955
+ if (pages.some((page) => page.universalIdentifier === settingsPage.universalIdentifier)) {
22956
+ ctx.addIssue({
22957
+ code: "custom",
22958
+ path: ["settingsPage", "universalIdentifier"],
22959
+ message: "settingsPage.universalIdentifier collides with a pages[] universalIdentifier"
22960
+ });
22961
+ }
22962
+ });
22906
22963
  var ShopifyOrderV1Schema = external_exports.object({
22907
22964
  id: external_exports.string(),
22908
22965
  shopifyId: external_exports.string(),
@@ -23000,7 +23057,7 @@ async function buildApp(projectRoot, tarball) {
23000
23057
  if (tarball && manifest.version) {
23001
23058
  const bundleBuffer = await compileBundleIfExists(projectRoot, outputDir);
23002
23059
  hasBundle = bundleBuffer !== null;
23003
- const uiBuffers = await compileUiPages(projectRoot, outputDir, manifest.pages ?? []);
23060
+ const uiBuffers = await compileUiBundles(projectRoot, outputDir, collectUiTargets(manifest));
23004
23061
  uiPageCount = uiBuffers.size;
23005
23062
  const stamped = stampUiSdkVersion(manifest, projectRoot, uiBuffers.size > 0);
23006
23063
  const serialized2 = JSON.stringify(stamped);
@@ -23070,9 +23127,26 @@ async function compileBundleIfExists(projectRoot, outputDir) {
23070
23127
  }
23071
23128
  return (0, import_fs4.readFileSync)(outFile);
23072
23129
  }
23073
- async function compileUiPages(projectRoot, outputDir, pages) {
23130
+ function collectUiTargets(manifest) {
23131
+ const targets = (manifest.pages ?? []).map((page) => ({
23132
+ sourceName: page.path,
23133
+ outputPath: `dist/ui/${page.path}.js`,
23134
+ label: `page "${page.path}"`,
23135
+ requiresSource: false
23136
+ }));
23137
+ if (manifest.settingsPage) {
23138
+ targets.push({
23139
+ sourceName: (0, import_path2.basename)(manifest.settingsPage.entry, ".js"),
23140
+ outputPath: manifest.settingsPage.entry,
23141
+ label: "settings page",
23142
+ requiresSource: true
23143
+ });
23144
+ }
23145
+ return targets;
23146
+ }
23147
+ async function compileUiBundles(projectRoot, outputDir, targets) {
23074
23148
  const result = /* @__PURE__ */ new Map();
23075
- if (pages.length === 0) return result;
23149
+ if (targets.length === 0) return result;
23076
23150
  const UI_EXTERNALS = [
23077
23151
  "react",
23078
23152
  "react-dom",
@@ -23080,11 +23154,18 @@ async function compileUiPages(projectRoot, outputDir, pages) {
23080
23154
  "react/jsx-runtime",
23081
23155
  "@apotech-os/ui-sdk"
23082
23156
  ];
23083
- for (const page of pages) {
23084
- const entryPoint = (0, import_path2.join)(projectRoot, "src", "ui", `${page.path}.tsx`);
23085
- if (!(0, import_fs4.existsSync)(entryPoint)) continue;
23086
- const outFile = (0, import_path2.join)(outputDir, "dist", "ui", `${page.path}.js`);
23087
- (0, import_fs4.mkdirSync)((0, import_path2.join)(outputDir, "dist", "ui"), { recursive: true });
23157
+ for (const target of targets) {
23158
+ const entryPoint = (0, import_path2.join)(projectRoot, "src", "ui", `${target.sourceName}.tsx`);
23159
+ if (!(0, import_fs4.existsSync)(entryPoint)) {
23160
+ if (!target.requiresSource) continue;
23161
+ throw new ManifestBuildError(
23162
+ `UI ${target.label} source not found`,
23163
+ `Expected: ${entryPoint}
23164
+ The manifest declares "${target.outputPath}", so its source file must exist.`
23165
+ );
23166
+ }
23167
+ const outFile = (0, import_path2.join)(outputDir, target.outputPath);
23168
+ (0, import_fs4.mkdirSync)((0, import_path2.dirname)(outFile), { recursive: true });
23088
23169
  const buildResult = await (0, import_esbuild2.build)({
23089
23170
  entryPoints: [entryPoint],
23090
23171
  bundle: true,
@@ -23098,14 +23179,14 @@ async function compileUiPages(projectRoot, outputDir, pages) {
23098
23179
  });
23099
23180
  if (buildResult.errors.length > 0) {
23100
23181
  const msg = buildResult.errors.map((e) => e.text).join("\n");
23101
- throw new ManifestBuildError(`UI page "${page.path}" compilation failed`, msg);
23182
+ throw new ManifestBuildError(`UI ${target.label} compilation failed`, msg);
23102
23183
  }
23103
- result.set(`dist/ui/${page.path}.js`, (0, import_fs4.readFileSync)(outFile));
23184
+ result.set(target.outputPath, (0, import_fs4.readFileSync)(outFile));
23104
23185
  }
23105
23186
  return result;
23106
23187
  }
23107
- function stampUiSdkVersion(manifest, projectRoot, hasUiPages) {
23108
- if (!hasUiPages) return manifest;
23188
+ function stampUiSdkVersion(manifest, projectRoot, hasUiBundles) {
23189
+ if (!hasUiBundles) return manifest;
23109
23190
  const candidates = [
23110
23191
  (0, import_path2.join)(projectRoot, "node_modules", "@apotech-os", "ui-sdk", "package.json"),
23111
23192
  // Monorepo workspaces may hoist to the root node_modules.
@@ -23177,7 +23258,7 @@ function buildBuildCommand() {
23177
23258
  console.log(` bundle : dist/index.js (included)`);
23178
23259
  }
23179
23260
  if (result.uiPageCount) {
23180
- console.log(` ui pages : ${result.uiPageCount} page(s) in dist/ui/ (included)`);
23261
+ console.log(` ui bundles : ${result.uiPageCount} file(s) in dist/ui/ (included)`);
23181
23262
  }
23182
23263
  }
23183
23264
  } catch (err) {
@@ -23226,12 +23307,39 @@ async function syncManifest(opts) {
23226
23307
  }
23227
23308
  return body;
23228
23309
  }
23310
+ async function installApp(opts) {
23311
+ const url2 = `${opts.baseUrl.replace(/\/$/, "")}/platform/apps/install`;
23312
+ const headers = {
23313
+ "Content-Type": "application/json"
23314
+ };
23315
+ if (opts.apiKey) {
23316
+ headers["Authorization"] = `Bearer ${opts.apiKey}`;
23317
+ }
23318
+ const res = await fetch(url2, {
23319
+ method: "POST",
23320
+ headers,
23321
+ body: JSON.stringify({ slug: opts.slug, version: opts.version })
23322
+ });
23323
+ const body = await res.json().catch(() => ({ message: res.statusText }));
23324
+ if (!res.ok) {
23325
+ const code = extractCode(body);
23326
+ const message = extractMessage(body) ?? `HTTP ${res.status}`;
23327
+ throw new ApiError(code ? `[${code}] ${message}` : message, res.status, body);
23328
+ }
23329
+ return body;
23330
+ }
23229
23331
  function extractMessage(body) {
23230
23332
  if (body && typeof body === "object" && "message" in body) {
23231
23333
  return String(body["message"]);
23232
23334
  }
23233
23335
  return void 0;
23234
23336
  }
23337
+ function extractCode(body) {
23338
+ if (body && typeof body === "object" && "code" in body) {
23339
+ return String(body["code"]);
23340
+ }
23341
+ return void 0;
23342
+ }
23235
23343
 
23236
23344
  // src/plan-render.ts
23237
23345
  var OP_SYMBOL = {
@@ -23320,7 +23428,7 @@ function getRemoteUrl(remoteName) {
23320
23428
  function getApiKey(remoteName) {
23321
23429
  return readFile().credentials[remoteName];
23322
23430
  }
23323
- var DEFAULT_REMOTE_URL = process.env["WOPILO_API_URL"] ?? "http://localhost:3001";
23431
+ var DEFAULT_REMOTE_URL = process.env["WOPILO_API_URL"] ?? "https://wopilo.plateform.apotechstudio.com/";
23324
23432
  function resolveApiKey(remoteName) {
23325
23433
  if (remoteName) return getApiKey(remoteName);
23326
23434
  return process.env["WOPILO_API_KEY"] ?? void 0;
@@ -23329,11 +23437,14 @@ function resolveApiKey(remoteName) {
23329
23437
  // src/commands/dev.ts
23330
23438
  var DEBOUNCE_MS = 300;
23331
23439
  function buildDevCommand() {
23332
- return new Command("dev").description("Watch src/** and sync manifest on change").option("--remote <name>", "Named remote server to target").option("--verbose", "Show detailed output on each sync").action(async (opts) => {
23440
+ return new Command("dev").description("Watch src/** and sync the manifest on change (local iteration only)").option("--remote <name>", "Named remote server to target").option("--verbose", "Show detailed output on each sync").action(async (opts) => {
23333
23441
  const projectRoot = process.cwd();
23334
23442
  const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
23335
23443
  const apiKey = resolveApiKey(opts.remote);
23336
23444
  console.log(`Watching ${projectRoot}/src/** \u2192 ${baseUrl}`);
23445
+ console.log(
23446
+ "dev syncs the manifest only (plus hot-reloaded handlers) \u2014 it publishes no artefact and installs no version. Use `apotech-os deploy --remote <name>` to ship."
23447
+ );
23337
23448
  let debounceTimer = null;
23338
23449
  let syncing = false;
23339
23450
  let pendingSync = false;
@@ -23496,99 +23607,48 @@ function buildPlanCommand() {
23496
23607
  });
23497
23608
  }
23498
23609
 
23499
- // src/commands/apply.ts
23500
- function buildApplyCommand() {
23501
- return new Command("apply").description("Build + apply the manifest (one-shot)").option("--remote <name>", "Named remote server to target").option("--force", "Apply destructive changes without prompting").option("--json", "Output JSON instead of human-readable text").action(async (opts) => {
23502
- const projectRoot = process.cwd();
23503
- let manifest;
23504
- try {
23505
- manifest = await buildManifest(projectRoot);
23506
- } catch (err) {
23507
- if (err instanceof ManifestBuildError) {
23508
- if (opts.json) {
23509
- console.log(JSON.stringify({ ok: false, error: err.code, diagnostic: err.diagnostic }));
23510
- } else {
23511
- console.error(`[MANIFEST_BUILD_FAILED] ${err.message}`);
23512
- console.error(err.diagnostic);
23513
- }
23514
- process.exit(1);
23515
- }
23516
- throw err;
23517
- }
23518
- const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
23519
- const apiKey = resolveApiKey(opts.remote);
23520
- try {
23521
- const response = await syncManifest({
23522
- baseUrl,
23523
- apiKey,
23524
- manifest,
23525
- mode: "apply",
23526
- force: opts.force
23527
- });
23528
- if (opts.json) {
23529
- console.log(JSON.stringify(response));
23530
- if (!response.applied) {
23531
- process.exit(1);
23532
- }
23533
- } else {
23534
- console.log(renderPlan(response));
23535
- if (response.applied) {
23536
- console.log("\nApply complete.");
23537
- } else if (response.actions.some((a) => a.destructive)) {
23538
- console.log("\nDestructive changes detected. Re-run with --force to apply.");
23539
- process.exit(1);
23540
- }
23541
- }
23542
- } catch (err) {
23543
- if (err instanceof ApiError) {
23544
- if (opts.json) {
23545
- console.log(JSON.stringify({ ok: false, status: err.status, error: err.message }));
23546
- } else {
23547
- console.error(`Server error (${err.status}): ${err.message}`);
23548
- }
23549
- process.exit(1);
23550
- }
23551
- throw err;
23552
- }
23553
- });
23554
- }
23555
-
23556
- // src/commands/remote.ts
23557
- function buildRemoteCommand() {
23558
- const remote = new Command("remote").description("Manage target servers");
23559
- remote.command("add").description("Add a named remote server").requiredOption("--url <url>", "Server base URL").requiredOption("--as <name>", "Remote alias").action((opts) => {
23560
- addRemote(opts.as, opts.url);
23561
- console.log(`Remote "${opts.as}" added \u2192 ${opts.url}`);
23562
- });
23563
- remote.command("list").description("List configured remotes").action(() => {
23564
- const remotes = listRemotes();
23565
- const entries = Object.entries(remotes);
23566
- if (entries.length === 0) {
23567
- console.log("No remotes configured.");
23568
- return;
23569
- }
23570
- for (const [name, config2] of entries) {
23571
- console.log(` ${name} ${config2.url}`);
23572
- }
23573
- });
23574
- return remote;
23575
- }
23610
+ // src/commands/publish.ts
23611
+ var import_fs7 = require("fs");
23612
+ var import_path5 = require("path");
23576
23613
 
23577
- // src/commands/login.ts
23578
- function buildLoginCommand() {
23579
- return new Command("login").description("Store an API key for a remote server").requiredOption("--remote <name>", "Remote alias").action(async (opts) => {
23580
- getRemoteUrl(opts.remote);
23581
- const passwordMod = await Promise.resolve().then(() => (init_esm5(), esm_exports2));
23582
- const password = passwordMod.default;
23583
- const key = await password({ message: `API key for "${opts.remote}":` });
23584
- storeApiKey(opts.remote, key);
23585
- console.log(`Credentials stored for remote "${opts.remote}".`);
23586
- });
23614
+ // src/lifecycle-hints.ts
23615
+ var HINTS = [
23616
+ [
23617
+ "VERSION_NOT_INCREASED",
23618
+ "Bump manifest.version to deploy changes \u2014 registry and artefact only advance together, on one version."
23619
+ ],
23620
+ [
23621
+ "DUPLICATE_VERSION",
23622
+ "Bump manifest.version to deploy changes \u2014 this version has already been published."
23623
+ ],
23624
+ [
23625
+ "APP_ALREADY_INSTALLED",
23626
+ "This version is already installed. Bump manifest.version and deploy again."
23627
+ ],
23628
+ [
23629
+ "CANNOT_DOWNGRADE_APPLICATION",
23630
+ "Downgrades are refused. Publish a version strictly greater than the installed one."
23631
+ ],
23632
+ [
23633
+ "SERVER_VERSION_INCOMPATIBLE",
23634
+ "The target server does not satisfy engines.wopilo in package.json."
23635
+ ],
23636
+ [
23637
+ "PACKAGE_NAME_SLUG_MISMATCH",
23638
+ "The published slug must equal manifest.slug \u2014 check src/app.manifest.ts."
23639
+ ]
23640
+ ];
23641
+ function lifecycleHint(errorMessage) {
23642
+ for (const [code, hint] of HINTS) {
23643
+ if (errorMessage.includes(code)) return hint;
23644
+ }
23645
+ if (/App ".*" not found/.test(errorMessage)) {
23646
+ return "No app is registered under that slug on this remote. If you renamed the app, restore the original manifest.slug \u2014 renaming a published app is not supported. Otherwise publish it first.";
23647
+ }
23648
+ return void 0;
23587
23649
  }
23588
23650
 
23589
23651
  // src/commands/publish.ts
23590
- var import_fs7 = require("fs");
23591
- var import_path5 = require("path");
23592
23652
  function readPackageJson(projectRoot) {
23593
23653
  const path = (0, import_path5.join)(projectRoot, "package.json");
23594
23654
  if (!(0, import_fs7.existsSync)(path)) {
@@ -23617,7 +23677,7 @@ async function publishMultipart(opts) {
23617
23677
  const res = await fetch(url2, { method: "POST", headers, body: form });
23618
23678
  const body = await res.json().catch(() => ({ message: res.statusText }));
23619
23679
  if (!res.ok) {
23620
- const errorCode = extractCode(body);
23680
+ const errorCode = extractCode2(body);
23621
23681
  const message = extractMessage2(body) ?? `HTTP ${res.status}`;
23622
23682
  throw new ApiError(errorCode ? `[${errorCode}] ${message}` : message, res.status, body);
23623
23683
  }
@@ -23629,18 +23689,79 @@ function extractMessage2(body) {
23629
23689
  }
23630
23690
  return void 0;
23631
23691
  }
23632
- function extractCode(body) {
23692
+ function extractCode2(body) {
23633
23693
  if (body && typeof body === "object" && "code" in body) {
23634
23694
  return String(body["code"]);
23635
23695
  }
23636
23696
  return void 0;
23637
23697
  }
23698
+ async function publishApp(opts) {
23699
+ const buildOutput = await buildApp(opts.projectRoot, true);
23700
+ if (!buildOutput.tarballPath || !buildOutput.tarballChecksum || !buildOutput.manifest.version) {
23701
+ throw new ManifestBuildError(
23702
+ "Build did not produce a tarball",
23703
+ 'Add a "version" field to src/app.manifest.ts \u2014 publishing requires a versioned artefact.'
23704
+ );
23705
+ }
23706
+ const slug = buildOutput.manifest.slug;
23707
+ const version2 = buildOutput.manifest.version;
23708
+ let enginesWopilo;
23709
+ if ((0, import_fs7.existsSync)((0, import_path5.join)(opts.projectRoot, "package.json"))) {
23710
+ const pkg = readPackageJson(opts.projectRoot);
23711
+ enginesWopilo = pkg.engines?.wopilo;
23712
+ if (pkg.version && pkg.version !== version2 && !opts.quiet) {
23713
+ console.warn(
23714
+ `Note: package.json version (${pkg.version}) differs from manifest version (${version2}); publishing the manifest version. Bump manifest.version to release a new artefact.`
23715
+ );
23716
+ }
23717
+ }
23718
+ const tarballSize = (0, import_fs7.readFileSync)(buildOutput.tarballPath).length;
23719
+ const result = await publishMultipart({
23720
+ baseUrl: opts.baseUrl,
23721
+ apiKey: opts.apiKey,
23722
+ tarballPath: buildOutput.tarballPath,
23723
+ tarballChecksum: buildOutput.tarballChecksum,
23724
+ packageName: slug,
23725
+ packageVersion: version2,
23726
+ enginesWopilo,
23727
+ json: opts.quiet ?? false
23728
+ });
23729
+ const storedSlug = result.slug ?? slug;
23730
+ return {
23731
+ versionId: result.versionId,
23732
+ slug,
23733
+ storedSlug,
23734
+ version: version2,
23735
+ tarballSize,
23736
+ checksum: buildOutput.tarballChecksum
23737
+ };
23738
+ }
23638
23739
  function buildPublishCommand() {
23639
- return new Command("app:publish").description("Build + publish the app to a remote server").requiredOption("--remote <name>", "Named remote server to publish to").option("--json", "Output result as JSON (for CI)").action(async (opts) => {
23640
- const projectRoot = process.cwd();
23641
- let buildOutput;
23740
+ return new Command("app:publish").description("Build + publish a versioned artefact (no install side-effect)").requiredOption("--remote <name>", "Named remote server to publish to").option("--json", "Output result as JSON (for CI)").action(async (opts) => {
23741
+ const baseUrl = getRemoteUrl(opts.remote);
23742
+ const apiKey = resolveApiKey(opts.remote);
23642
23743
  try {
23643
- buildOutput = await buildApp(projectRoot, true);
23744
+ const result = await publishApp({
23745
+ projectRoot: process.cwd(),
23746
+ baseUrl,
23747
+ apiKey,
23748
+ quiet: opts.json ?? false
23749
+ });
23750
+ if (opts.json) {
23751
+ console.log(
23752
+ JSON.stringify({
23753
+ versionId: result.versionId,
23754
+ package: result.slug,
23755
+ version: result.version,
23756
+ tarballSize: result.tarballSize,
23757
+ checksum: result.checksum
23758
+ })
23759
+ );
23760
+ } else {
23761
+ console.log(`Published ${result.slug}@${result.version} \u2192 ${result.versionId}`);
23762
+ console.log(` tarball : ${result.tarballSize} bytes`);
23763
+ console.log(` checksum : ${result.checksum}`);
23764
+ }
23644
23765
  } catch (err) {
23645
23766
  if (err instanceof ManifestBuildError) {
23646
23767
  if (opts.json) {
@@ -23651,78 +23772,353 @@ function buildPublishCommand() {
23651
23772
  }
23652
23773
  process.exit(1);
23653
23774
  }
23654
- throw err;
23655
- }
23656
- if (!buildOutput.tarballPath || !buildOutput.tarballChecksum || !buildOutput.manifest.version) {
23657
- console.error('Build did not produce a tarball \u2014 check manifest has a "version" field');
23658
- process.exit(1);
23659
- }
23660
- const slug = buildOutput.manifest.slug;
23661
- const version2 = buildOutput.manifest.version;
23662
- let enginesWopilo;
23663
- if ((0, import_fs7.existsSync)((0, import_path5.join)(projectRoot, "package.json"))) {
23664
- const pkg = readPackageJson(projectRoot);
23665
- enginesWopilo = pkg.engines?.wopilo;
23666
- if (pkg.version && pkg.version !== version2 && !opts.json) {
23667
- console.warn(
23668
- `Note: package.json version (${pkg.version}) differs from manifest version (${version2}); publishing the manifest version. Bump manifest.version to release a new artefact.`
23669
- );
23775
+ {
23776
+ const status = err instanceof ApiError ? err.status : void 0;
23777
+ const message = err instanceof Error ? err.message : String(err);
23778
+ const hint = lifecycleHint(message);
23779
+ if (opts.json) {
23780
+ console.log(
23781
+ JSON.stringify({
23782
+ error: status !== void 0 ? String(status) : "PUBLISH_FAILED",
23783
+ message,
23784
+ ...err instanceof ApiError ? { body: err.body } : {},
23785
+ ...hint ? { hint } : {}
23786
+ })
23787
+ );
23788
+ } else {
23789
+ console.error(
23790
+ status !== void 0 ? `Server error (${status}): ${message}` : `Publish failed: ${message}`
23791
+ );
23792
+ if (hint) console.error(hint);
23793
+ }
23794
+ process.exit(1);
23670
23795
  }
23671
23796
  }
23797
+ });
23798
+ }
23799
+
23800
+ // src/commands/deploy.ts
23801
+ function abort(step, err, json2, retry) {
23802
+ const status = err instanceof ApiError ? err.status : void 0;
23803
+ const message = err instanceof Error ? err.message : String(err);
23804
+ const diagnostic = err instanceof ManifestBuildError ? err.diagnostic : void 0;
23805
+ const hint = lifecycleHint(message);
23806
+ if (json2) {
23807
+ console.log(
23808
+ JSON.stringify({
23809
+ ok: false,
23810
+ step,
23811
+ ...status !== void 0 ? { status } : {},
23812
+ error: err instanceof ManifestBuildError ? err.code : message,
23813
+ ...diagnostic ? { diagnostic } : {},
23814
+ ...hint ? { hint } : {},
23815
+ ...retry ? { retry } : {}
23816
+ })
23817
+ );
23818
+ } else {
23819
+ console.error(
23820
+ status !== void 0 ? `Deploy aborted at ${step} \u2014 server error (${status}): ${message}` : `Deploy aborted at ${step}: ${message}`
23821
+ );
23822
+ if (diagnostic) console.error(diagnostic);
23823
+ if (hint) console.error(hint);
23824
+ if (retry) console.error(retry);
23825
+ }
23826
+ process.exit(1);
23827
+ }
23828
+ function buildDeployCommand() {
23829
+ return new Command("deploy").description("Build, publish, and install the app on a remote \u2014 one version-locked flow").requiredOption("--remote <name>", "Named remote server to deploy to").option("--no-install", "Publish the artefact without activating it (CI)").option("--force", "Allow destructive schema changes").option("--json", "Output result as JSON (for CI)").action(async (opts) => {
23830
+ const projectRoot = process.cwd();
23672
23831
  const baseUrl = getRemoteUrl(opts.remote);
23673
23832
  const apiKey = resolveApiKey(opts.remote);
23674
- const tarballSize = (0, import_fs7.readFileSync)(buildOutput.tarballPath).length;
23833
+ const json2 = opts.json ?? false;
23834
+ if (opts.install && !opts.force) {
23835
+ let plan;
23836
+ try {
23837
+ const manifest = await buildManifest(projectRoot);
23838
+ plan = await syncManifest({ baseUrl, apiKey, manifest, mode: "plan" });
23839
+ } catch (err) {
23840
+ abort("plan", err, json2);
23841
+ }
23842
+ const destructive = plan.actions.filter((a) => a.destructive);
23843
+ if (destructive.length > 0) {
23844
+ if (json2) {
23845
+ console.log(
23846
+ JSON.stringify({
23847
+ ok: false,
23848
+ step: "plan",
23849
+ error: "DESTRUCTIVE_CHANGES",
23850
+ actions: destructive,
23851
+ hint: "Re-run with --force to apply destructive changes."
23852
+ })
23853
+ );
23854
+ } else {
23855
+ console.error("Destructive changes detected \u2014 nothing was published or installed.\n");
23856
+ console.error(renderPlan(plan));
23857
+ console.error("\nRe-run with --force to apply them.");
23858
+ }
23859
+ process.exit(1);
23860
+ }
23861
+ }
23862
+ let published;
23675
23863
  try {
23676
- const result = await publishMultipart({
23677
- baseUrl,
23678
- apiKey,
23679
- tarballPath: buildOutput.tarballPath,
23680
- tarballChecksum: buildOutput.tarballChecksum,
23681
- packageName: slug,
23682
- packageVersion: version2,
23683
- enginesWopilo,
23684
- json: opts.json ?? false
23685
- });
23686
- if (opts.json) {
23864
+ published = await publishApp({ projectRoot, baseUrl, apiKey, quiet: json2 });
23865
+ } catch (err) {
23866
+ abort("publish", err, json2);
23867
+ }
23868
+ if (!opts.install) {
23869
+ if (json2) {
23687
23870
  console.log(
23688
23871
  JSON.stringify({
23689
- versionId: result.versionId,
23690
- package: slug,
23691
- version: version2,
23692
- tarballSize,
23693
- checksum: buildOutput.tarballChecksum
23872
+ ok: true,
23873
+ slug: published.slug,
23874
+ version: published.version,
23875
+ versionId: published.versionId,
23876
+ installed: false
23694
23877
  })
23695
23878
  );
23696
23879
  } else {
23697
- console.log(`Published ${slug}@${version2} \u2192 ${result.versionId}`);
23698
- console.log(` tarball : ${tarballSize} bytes`);
23699
- console.log(` checksum : ${buildOutput.tarballChecksum}`);
23880
+ console.log(`Published ${published.slug}@${published.version} \u2192 ${published.versionId}`);
23881
+ console.log("--no-install: the artefact is stored but not activated.");
23700
23882
  }
23883
+ return;
23884
+ }
23885
+ if (published.storedSlug !== published.slug) {
23886
+ abort(
23887
+ "install",
23888
+ new Error(
23889
+ `This app is registered as "${published.storedSlug}" but the manifest now declares "${published.slug}". Renaming a published app's slug is not supported.`
23890
+ ),
23891
+ json2,
23892
+ `${published.storedSlug}@${published.version} is published but NOT installed. Restore slug "${published.storedSlug}" in src/app.manifest.ts and deploy again.`
23893
+ );
23894
+ }
23895
+ try {
23896
+ await installApp({
23897
+ baseUrl,
23898
+ apiKey,
23899
+ slug: published.slug,
23900
+ version: published.version
23901
+ });
23701
23902
  } catch (err) {
23702
- if (err instanceof ApiError) {
23903
+ abort(
23904
+ "install",
23905
+ err,
23906
+ json2,
23907
+ `${published.slug}@${published.version} is published but NOT installed. Retry activation with: apotech-os app:install --remote ${opts.remote} --version ${published.version}`
23908
+ );
23909
+ }
23910
+ if (json2) {
23911
+ console.log(
23912
+ JSON.stringify({
23913
+ ok: true,
23914
+ slug: published.slug,
23915
+ version: published.version,
23916
+ versionId: published.versionId,
23917
+ installed: true
23918
+ })
23919
+ );
23920
+ } else {
23921
+ console.log(`Published ${published.slug}@${published.version} \u2192 ${published.versionId}`);
23922
+ console.log(`Deployed ${published.slug}@${published.version} on "${opts.remote}".`);
23923
+ }
23924
+ });
23925
+ }
23926
+
23927
+ // src/commands/remote.ts
23928
+ function buildRemoteCommand() {
23929
+ const remote = new Command("remote").description("Manage target servers");
23930
+ remote.command("add").description("Add a named remote server").requiredOption("--url <url>", "Server base URL").requiredOption("--as <name>", "Remote alias").action((opts) => {
23931
+ addRemote(opts.as, opts.url);
23932
+ console.log(`Remote "${opts.as}" added \u2192 ${opts.url}`);
23933
+ });
23934
+ remote.command("list").description("List configured remotes").action(() => {
23935
+ const remotes = listRemotes();
23936
+ const entries = Object.entries(remotes);
23937
+ if (entries.length === 0) {
23938
+ console.log("No remotes configured.");
23939
+ return;
23940
+ }
23941
+ for (const [name, config2] of entries) {
23942
+ console.log(` ${name} ${config2.url}`);
23943
+ }
23944
+ });
23945
+ return remote;
23946
+ }
23947
+
23948
+ // src/commands/login.ts
23949
+ var import_child_process = require("child_process");
23950
+ var import_os4 = require("os");
23951
+ function clientLabel() {
23952
+ try {
23953
+ return `${(0, import_os4.userInfo)().username}@${(0, import_os4.hostname)()}`;
23954
+ } catch {
23955
+ return (0, import_os4.hostname)();
23956
+ }
23957
+ }
23958
+ function openBrowser(url2) {
23959
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
23960
+ try {
23961
+ const child = (0, import_child_process.spawn)(command, [url2], {
23962
+ detached: true,
23963
+ stdio: "ignore",
23964
+ shell: process.platform === "win32"
23965
+ });
23966
+ child.on("error", () => void 0);
23967
+ child.unref();
23968
+ } catch {
23969
+ }
23970
+ }
23971
+ function sleep(ms) {
23972
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
23973
+ }
23974
+ async function postJson(url2, body) {
23975
+ const res = await fetch(url2, {
23976
+ method: "POST",
23977
+ headers: { "Content-Type": "application/json" },
23978
+ body: JSON.stringify(body)
23979
+ });
23980
+ const parsed = await res.json().catch(() => void 0);
23981
+ return { status: res.status, body: parsed };
23982
+ }
23983
+ async function promptForKey(remote) {
23984
+ const passwordMod = await Promise.resolve().then(() => (init_esm5(), esm_exports2));
23985
+ const password = passwordMod.default;
23986
+ const key = await password({ message: `API key for "${remote}":` });
23987
+ storeApiKey(remote, key);
23988
+ console.log(`Credentials stored for remote "${remote}".`);
23989
+ }
23990
+ async function browserLogin(remote, baseUrl) {
23991
+ const device = await postJson(`${baseUrl.replace(/\/$/, "")}/platform/cli-auth/device`, {
23992
+ clientLabel: clientLabel()
23993
+ });
23994
+ if (device.status === 404) {
23995
+ console.log("This server does not support browser login yet \u2014 falling back to an API key.");
23996
+ console.log("Create one in the web app under Param\xE8tres \u203A Cl\xE9s API.");
23997
+ await promptForKey(remote);
23998
+ return;
23999
+ }
24000
+ if (device.status >= 400) {
24001
+ throw new Error(`Could not start the login flow (HTTP ${device.status}).`);
24002
+ }
24003
+ const auth = device.body;
24004
+ console.log(`Opening ${auth.verificationUriComplete} in your browser\u2026`);
24005
+ console.log(` Confirmation code: ${auth.userCode}`);
24006
+ console.log(" (If the browser did not open, visit the URL above.)");
24007
+ openBrowser(auth.verificationUriComplete);
24008
+ const key = await pollForKey(baseUrl, auth);
24009
+ storeApiKey(remote, key);
24010
+ console.log(`Logged in to remote "${remote}". Credentials stored in ~/.wopilo/credentials.json.`);
24011
+ }
24012
+ async function pollForKey(baseUrl, auth) {
24013
+ const tokenUrl = `${baseUrl.replace(/\/$/, "")}/platform/cli-auth/token`;
24014
+ const deadline = Date.now() + auth.expiresIn * 1e3;
24015
+ process.stdout.write("Waiting for approval\u2026 ");
24016
+ while (Date.now() < deadline) {
24017
+ await sleep(auth.interval * 1e3);
24018
+ if (Date.now() >= deadline) break;
24019
+ const res = await postJson(tokenUrl, { deviceCode: auth.deviceCode });
24020
+ const result = res.body;
24021
+ if (result?.status === "approved") {
24022
+ console.log("\u2713");
24023
+ return result.apiKey;
24024
+ }
24025
+ if (result?.status === "denied") {
24026
+ console.log("\u2717");
24027
+ throw new Error("Login was denied in the browser.");
24028
+ }
24029
+ if (result?.status === "expired") {
24030
+ console.log("\u2717");
24031
+ throw new Error("Login request expired. Run the command again.");
24032
+ }
24033
+ }
24034
+ console.log("\u2717");
24035
+ throw new Error("Login request expired. Run the command again.");
24036
+ }
24037
+ function buildLoginCommand() {
24038
+ 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) => {
24039
+ const baseUrl = getRemoteUrl(opts.remote);
24040
+ if (opts.withKey) {
24041
+ await promptForKey(opts.remote);
24042
+ return;
24043
+ }
24044
+ await browserLogin(opts.remote, baseUrl);
24045
+ });
24046
+ }
24047
+
24048
+ // src/commands/install.ts
24049
+ function buildInstallCommand() {
24050
+ return new Command("app:install").alias("app:upgrade").description("Install or upgrade a published version on a remote").requiredOption("--remote <name>", "Named remote server to target").option("--version <version>", "Version to install (default: the manifest version)").option("--json", "Output result as JSON (for CI)").action(async (opts) => {
24051
+ let slug;
24052
+ let version2 = opts.version;
24053
+ try {
24054
+ const manifest = await buildManifest(process.cwd());
24055
+ slug = manifest.slug;
24056
+ version2 ??= manifest.version;
24057
+ } catch (err) {
24058
+ if (err instanceof ManifestBuildError) {
23703
24059
  if (opts.json) {
23704
- console.log(
23705
- JSON.stringify({ error: String(err.status), message: err.message, body: err.body })
23706
- );
24060
+ console.log(JSON.stringify({ ok: false, error: err.code, diagnostic: err.diagnostic }));
23707
24061
  } else {
23708
- console.error(`Server error (${err.status}): ${err.message}`);
24062
+ console.error(`[MANIFEST_BUILD_FAILED] ${err.message}`);
24063
+ console.error(err.diagnostic);
23709
24064
  }
23710
24065
  process.exit(1);
23711
24066
  }
23712
24067
  throw err;
23713
24068
  }
24069
+ const baseUrl = getRemoteUrl(opts.remote);
24070
+ const apiKey = resolveApiKey(opts.remote);
24071
+ try {
24072
+ await installApp({ baseUrl, apiKey, slug, version: version2 });
24073
+ if (opts.json) {
24074
+ console.log(JSON.stringify({ ok: true, slug, version: version2 ?? null }));
24075
+ } else {
24076
+ console.log(
24077
+ `Installed ${slug}${version2 ? `@${version2}` : " (latest published version)"} on "${opts.remote}"`
24078
+ );
24079
+ }
24080
+ } catch (err) {
24081
+ const status = err instanceof ApiError ? err.status : void 0;
24082
+ const message = err instanceof Error ? err.message : String(err);
24083
+ const hint = lifecycleHint(message);
24084
+ if (opts.json) {
24085
+ console.log(
24086
+ JSON.stringify({
24087
+ ok: false,
24088
+ ...status !== void 0 ? { status } : {},
24089
+ error: message,
24090
+ ...hint ? { hint } : {}
24091
+ })
24092
+ );
24093
+ } else {
24094
+ console.error(
24095
+ status !== void 0 ? `Server error (${status}): ${message}` : `Install failed: ${message}`
24096
+ );
24097
+ if (hint) console.error(hint);
24098
+ }
24099
+ process.exit(1);
24100
+ }
23714
24101
  });
23715
24102
  }
23716
24103
 
23717
24104
  // src/index.ts
23718
- var program2 = new Command().name("apotech-os").description("Wopilo OS CLI \u2014 scaffold, plan, and sync your app manifest").version("0.1.0");
24105
+ function readVersion() {
24106
+ try {
24107
+ const pkg = (0, import_fs8.readFileSync)((0, import_path6.join)(__dirname, "..", "package.json"), "utf8");
24108
+ return JSON.parse(pkg).version ?? "0.0.0";
24109
+ } catch {
24110
+ return "0.0.0";
24111
+ }
24112
+ }
24113
+ var program2 = new Command().name("apotech-os").description("Wopilo OS CLI \u2014 scaffold, plan, and deploy your app").version(readVersion()).enablePositionalOptions();
23719
24114
  program2.addCommand(buildDevCommand());
23720
24115
  program2.addCommand(buildPlanCommand());
23721
- program2.addCommand(buildApplyCommand());
24116
+ program2.addCommand(buildDeployCommand());
23722
24117
  program2.addCommand(buildRemoteCommand());
23723
24118
  program2.addCommand(buildLoginCommand());
23724
24119
  program2.addCommand(buildBuildCommand());
23725
24120
  program2.addCommand(buildPublishCommand());
24121
+ program2.addCommand(buildInstallCommand());
23726
24122
  program2.parseAsync(process.argv).catch((err) => {
23727
24123
  console.error(err instanceof Error ? err.message : String(err));
23728
24124
  process.exit(1);