@apotech-os/cli 0.4.0 → 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"),
@@ -22713,6 +22726,32 @@ var FunctionTriggerSchema = external_exports.discriminatedUnion("type", [
22713
22726
  * AppSyncService.validateManifestConstraints, not here in the Zod schema.
22714
22727
  */
22715
22728
  name: external_exports.string()
22729
+ }),
22730
+ /**
22731
+ * Called synchronously by an app UI page, which receives the handler's return
22732
+ * value in the HTTP response.
22733
+ *
22734
+ * This is the only way a page can reach an integration: the action endpoint
22735
+ * requires an app token, and a browser session is refused. The platform mints
22736
+ * the token server-side and runs the handler in-process.
22737
+ *
22738
+ * Distinct from `httpRoute`, which is fire-and-forget (it dispatches an event
22739
+ * and answers with a run id). Keeping them as separate trigger types keeps one
22740
+ * handler tied to one dispatch path and one payload shape.
22741
+ *
22742
+ * SECURITY: the handler runs with the app's FULL manifest role, not the
22743
+ * caller's. Treat every uiInvoke function as a semi-public endpoint and
22744
+ * re-check anything sensitive inside the handler.
22745
+ */
22746
+ external_exports.object({
22747
+ type: external_exports.literal("uiInvoke"),
22748
+ /**
22749
+ * Minimum role the CALLING SESSION must hold on this app.
22750
+ * Defaults to EDITOR — fail-closed, since the handler is privileged.
22751
+ */
22752
+ minRole: external_exports.enum(["VIEWER", "EDITOR", "ADMIN"]).optional(),
22753
+ /** Wall-clock budget in ms. Clamped server-side by APP_SYNC_INVOKE_MAX_MS. */
22754
+ timeoutMs: external_exports.number().int().min(1e3).max(3e4).optional()
22716
22755
  })
22717
22756
  ]);
22718
22757
  var FunctionDefSchema = external_exports.object({
@@ -22784,6 +22823,14 @@ var SettingsFieldSchema = external_exports.object({
22784
22823
  var AppSettingsSchema = external_exports.object({
22785
22824
  fields: external_exports.array(SettingsFieldSchema)
22786
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
+ });
22787
22834
  var PROMPT_NAME_REGEX = /^[a-z][a-z0-9]*([.\-/][a-z0-9]+)*$/;
22788
22835
  var PromptDefSchema = external_exports.object({
22789
22836
  name: external_exports.string().regex(
@@ -22793,7 +22840,7 @@ var PromptDefSchema = external_exports.object({
22793
22840
  template: external_exports.string(),
22794
22841
  labels: external_exports.array(external_exports.string()).optional()
22795
22842
  });
22796
- var AppManifestSchema = external_exports.object({
22843
+ var AppManifestFieldsSchema = external_exports.object({
22797
22844
  universalIdentifier: external_exports.string().uuid(),
22798
22845
  slug: external_exports.string().regex(/^[a-z][a-z0-9-]*$/),
22799
22846
  // = contextId for RBAC
@@ -22862,6 +22909,9 @@ var AppManifestSchema = external_exports.object({
22862
22909
  ).optional(),
22863
22910
  /** P7 — Per-app settings schema. Optional; manifests without this field still validate. */
22864
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(),
22865
22915
  /**
22866
22916
  * P3 — Managed prompt definitions seeded to Langfuse on app install/sync.
22867
22917
  * Each entry creates or versions a prompt in Langfuse under the given name.
@@ -22877,6 +22927,39 @@ var AppManifestSchema = external_exports.object({
22877
22927
  */
22878
22928
  emits: external_exports.array(CustomEventNameSchema).optional()
22879
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
+ });
22880
22963
  var ShopifyOrderV1Schema = external_exports.object({
22881
22964
  id: external_exports.string(),
22882
22965
  shopifyId: external_exports.string(),
@@ -22974,7 +23057,7 @@ async function buildApp(projectRoot, tarball) {
22974
23057
  if (tarball && manifest.version) {
22975
23058
  const bundleBuffer = await compileBundleIfExists(projectRoot, outputDir);
22976
23059
  hasBundle = bundleBuffer !== null;
22977
- const uiBuffers = await compileUiPages(projectRoot, outputDir, manifest.pages ?? []);
23060
+ const uiBuffers = await compileUiBundles(projectRoot, outputDir, collectUiTargets(manifest));
22978
23061
  uiPageCount = uiBuffers.size;
22979
23062
  const stamped = stampUiSdkVersion(manifest, projectRoot, uiBuffers.size > 0);
22980
23063
  const serialized2 = JSON.stringify(stamped);
@@ -23044,9 +23127,26 @@ async function compileBundleIfExists(projectRoot, outputDir) {
23044
23127
  }
23045
23128
  return (0, import_fs4.readFileSync)(outFile);
23046
23129
  }
23047
- 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) {
23048
23148
  const result = /* @__PURE__ */ new Map();
23049
- if (pages.length === 0) return result;
23149
+ if (targets.length === 0) return result;
23050
23150
  const UI_EXTERNALS = [
23051
23151
  "react",
23052
23152
  "react-dom",
@@ -23054,11 +23154,18 @@ async function compileUiPages(projectRoot, outputDir, pages) {
23054
23154
  "react/jsx-runtime",
23055
23155
  "@apotech-os/ui-sdk"
23056
23156
  ];
23057
- for (const page of pages) {
23058
- const entryPoint = (0, import_path2.join)(projectRoot, "src", "ui", `${page.path}.tsx`);
23059
- if (!(0, import_fs4.existsSync)(entryPoint)) continue;
23060
- const outFile = (0, import_path2.join)(outputDir, "dist", "ui", `${page.path}.js`);
23061
- (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 });
23062
23169
  const buildResult = await (0, import_esbuild2.build)({
23063
23170
  entryPoints: [entryPoint],
23064
23171
  bundle: true,
@@ -23072,14 +23179,14 @@ async function compileUiPages(projectRoot, outputDir, pages) {
23072
23179
  });
23073
23180
  if (buildResult.errors.length > 0) {
23074
23181
  const msg = buildResult.errors.map((e) => e.text).join("\n");
23075
- throw new ManifestBuildError(`UI page "${page.path}" compilation failed`, msg);
23182
+ throw new ManifestBuildError(`UI ${target.label} compilation failed`, msg);
23076
23183
  }
23077
- result.set(`dist/ui/${page.path}.js`, (0, import_fs4.readFileSync)(outFile));
23184
+ result.set(target.outputPath, (0, import_fs4.readFileSync)(outFile));
23078
23185
  }
23079
23186
  return result;
23080
23187
  }
23081
- function stampUiSdkVersion(manifest, projectRoot, hasUiPages) {
23082
- if (!hasUiPages) return manifest;
23188
+ function stampUiSdkVersion(manifest, projectRoot, hasUiBundles) {
23189
+ if (!hasUiBundles) return manifest;
23083
23190
  const candidates = [
23084
23191
  (0, import_path2.join)(projectRoot, "node_modules", "@apotech-os", "ui-sdk", "package.json"),
23085
23192
  // Monorepo workspaces may hoist to the root node_modules.
@@ -23151,7 +23258,7 @@ function buildBuildCommand() {
23151
23258
  console.log(` bundle : dist/index.js (included)`);
23152
23259
  }
23153
23260
  if (result.uiPageCount) {
23154
- 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)`);
23155
23262
  }
23156
23263
  }
23157
23264
  } catch (err) {
@@ -23200,12 +23307,39 @@ async function syncManifest(opts) {
23200
23307
  }
23201
23308
  return body;
23202
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
+ }
23203
23331
  function extractMessage(body) {
23204
23332
  if (body && typeof body === "object" && "message" in body) {
23205
23333
  return String(body["message"]);
23206
23334
  }
23207
23335
  return void 0;
23208
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
+ }
23209
23343
 
23210
23344
  // src/plan-render.ts
23211
23345
  var OP_SYMBOL = {
@@ -23294,7 +23428,7 @@ function getRemoteUrl(remoteName) {
23294
23428
  function getApiKey(remoteName) {
23295
23429
  return readFile().credentials[remoteName];
23296
23430
  }
23297
- 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/";
23298
23432
  function resolveApiKey(remoteName) {
23299
23433
  if (remoteName) return getApiKey(remoteName);
23300
23434
  return process.env["WOPILO_API_KEY"] ?? void 0;
@@ -23303,11 +23437,14 @@ function resolveApiKey(remoteName) {
23303
23437
  // src/commands/dev.ts
23304
23438
  var DEBOUNCE_MS = 300;
23305
23439
  function buildDevCommand() {
23306
- 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) => {
23307
23441
  const projectRoot = process.cwd();
23308
23442
  const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
23309
23443
  const apiKey = resolveApiKey(opts.remote);
23310
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
+ );
23311
23448
  let debounceTimer = null;
23312
23449
  let syncing = false;
23313
23450
  let pendingSync = false;
@@ -23470,59 +23607,319 @@ function buildPlanCommand() {
23470
23607
  });
23471
23608
  }
23472
23609
 
23473
- // src/commands/apply.ts
23474
- function buildApplyCommand() {
23475
- 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) => {
23476
- const projectRoot = process.cwd();
23477
- let manifest;
23610
+ // src/commands/publish.ts
23611
+ var import_fs7 = require("fs");
23612
+ var import_path5 = require("path");
23613
+
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;
23649
+ }
23650
+
23651
+ // src/commands/publish.ts
23652
+ function readPackageJson(projectRoot) {
23653
+ const path = (0, import_path5.join)(projectRoot, "package.json");
23654
+ if (!(0, import_fs7.existsSync)(path)) {
23655
+ throw new Error(`package.json not found at ${path}`);
23656
+ }
23657
+ return JSON.parse((0, import_fs7.readFileSync)(path, "utf8"));
23658
+ }
23659
+ async function publishMultipart(opts) {
23660
+ const url2 = `${opts.baseUrl.replace(/\/$/, "")}/platform/apps/publish`;
23661
+ const tarballBuffer = (0, import_fs7.readFileSync)(opts.tarballPath);
23662
+ const metadata = JSON.stringify({
23663
+ slug: opts.packageName,
23664
+ version: opts.packageVersion,
23665
+ checksum: opts.tarballChecksum,
23666
+ ...opts.enginesWopilo ? { enginesWopilo: opts.enginesWopilo } : {}
23667
+ });
23668
+ const form = new FormData();
23669
+ form.append("metadata", metadata);
23670
+ form.append(
23671
+ "artifact",
23672
+ new Blob([tarballBuffer], { type: "application/gzip" }),
23673
+ `${opts.packageName}-${opts.packageVersion}.tgz`
23674
+ );
23675
+ const headers = {};
23676
+ if (opts.apiKey) headers["Authorization"] = `Bearer ${opts.apiKey}`;
23677
+ const res = await fetch(url2, { method: "POST", headers, body: form });
23678
+ const body = await res.json().catch(() => ({ message: res.statusText }));
23679
+ if (!res.ok) {
23680
+ const errorCode = extractCode2(body);
23681
+ const message = extractMessage2(body) ?? `HTTP ${res.status}`;
23682
+ throw new ApiError(errorCode ? `[${errorCode}] ${message}` : message, res.status, body);
23683
+ }
23684
+ return body;
23685
+ }
23686
+ function extractMessage2(body) {
23687
+ if (body && typeof body === "object" && "message" in body) {
23688
+ return String(body["message"]);
23689
+ }
23690
+ return void 0;
23691
+ }
23692
+ function extractCode2(body) {
23693
+ if (body && typeof body === "object" && "code" in body) {
23694
+ return String(body["code"]);
23695
+ }
23696
+ return void 0;
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
+ }
23739
+ function buildPublishCommand() {
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);
23478
23743
  try {
23479
- manifest = await buildManifest(projectRoot);
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
+ }
23480
23765
  } catch (err) {
23481
23766
  if (err instanceof ManifestBuildError) {
23482
23767
  if (opts.json) {
23483
- console.log(JSON.stringify({ ok: false, error: err.code, diagnostic: err.diagnostic }));
23768
+ console.log(JSON.stringify({ error: "BUILD_FAILED", message: err.message }));
23484
23769
  } else {
23485
- console.error(`[MANIFEST_BUILD_FAILED] ${err.message}`);
23770
+ console.error(`[BUILD_FAILED] ${err.message}`);
23486
23771
  console.error(err.diagnostic);
23487
23772
  }
23488
23773
  process.exit(1);
23489
23774
  }
23490
- throw err;
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);
23795
+ }
23491
23796
  }
23492
- const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
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();
23831
+ const baseUrl = getRemoteUrl(opts.remote);
23493
23832
  const apiKey = resolveApiKey(opts.remote);
23494
- try {
23495
- const response = await syncManifest({
23496
- baseUrl,
23497
- apiKey,
23498
- manifest,
23499
- mode: "apply",
23500
- force: opts.force
23501
- });
23502
- if (opts.json) {
23503
- console.log(JSON.stringify(response));
23504
- if (!response.applied) {
23505
- process.exit(1);
23506
- }
23507
- } else {
23508
- console.log(renderPlan(response));
23509
- if (response.applied) {
23510
- console.log("\nApply complete.");
23511
- } else if (response.actions.some((a) => a.destructive)) {
23512
- console.log("\nDestructive changes detected. Re-run with --force to apply.");
23513
- process.exit(1);
23514
- }
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);
23515
23841
  }
23516
- } catch (err) {
23517
- if (err instanceof ApiError) {
23518
- if (opts.json) {
23519
- console.log(JSON.stringify({ ok: false, status: err.status, error: err.message }));
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
+ );
23520
23854
  } else {
23521
- console.error(`Server error (${err.status}): ${err.message}`);
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.");
23522
23858
  }
23523
23859
  process.exit(1);
23524
23860
  }
23525
- throw err;
23861
+ }
23862
+ let published;
23863
+ try {
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) {
23870
+ console.log(
23871
+ JSON.stringify({
23872
+ ok: true,
23873
+ slug: published.slug,
23874
+ version: published.version,
23875
+ versionId: published.versionId,
23876
+ installed: false
23877
+ })
23878
+ );
23879
+ } else {
23880
+ console.log(`Published ${published.slug}@${published.version} \u2192 ${published.versionId}`);
23881
+ console.log("--no-install: the artefact is stored but not activated.");
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
+ });
23902
+ } catch (err) {
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}".`);
23526
23923
  }
23527
23924
  });
23528
23925
  }
@@ -23648,143 +24045,80 @@ function buildLoginCommand() {
23648
24045
  });
23649
24046
  }
23650
24047
 
23651
- // src/commands/publish.ts
23652
- var import_fs7 = require("fs");
23653
- var import_path5 = require("path");
23654
- function readPackageJson(projectRoot) {
23655
- const path = (0, import_path5.join)(projectRoot, "package.json");
23656
- if (!(0, import_fs7.existsSync)(path)) {
23657
- throw new Error(`package.json not found at ${path}`);
23658
- }
23659
- return JSON.parse((0, import_fs7.readFileSync)(path, "utf8"));
23660
- }
23661
- async function publishMultipart(opts) {
23662
- const url2 = `${opts.baseUrl.replace(/\/$/, "")}/platform/apps/publish`;
23663
- const tarballBuffer = (0, import_fs7.readFileSync)(opts.tarballPath);
23664
- const metadata = JSON.stringify({
23665
- slug: opts.packageName,
23666
- version: opts.packageVersion,
23667
- checksum: opts.tarballChecksum,
23668
- ...opts.enginesWopilo ? { enginesWopilo: opts.enginesWopilo } : {}
23669
- });
23670
- const form = new FormData();
23671
- form.append("metadata", metadata);
23672
- form.append(
23673
- "artifact",
23674
- new Blob([tarballBuffer], { type: "application/gzip" }),
23675
- `${opts.packageName}-${opts.packageVersion}.tgz`
23676
- );
23677
- const headers = {};
23678
- if (opts.apiKey) headers["Authorization"] = `Bearer ${opts.apiKey}`;
23679
- const res = await fetch(url2, { method: "POST", headers, body: form });
23680
- const body = await res.json().catch(() => ({ message: res.statusText }));
23681
- if (!res.ok) {
23682
- const errorCode = extractCode(body);
23683
- const message = extractMessage2(body) ?? `HTTP ${res.status}`;
23684
- throw new ApiError(errorCode ? `[${errorCode}] ${message}` : message, res.status, body);
23685
- }
23686
- return body;
23687
- }
23688
- function extractMessage2(body) {
23689
- if (body && typeof body === "object" && "message" in body) {
23690
- return String(body["message"]);
23691
- }
23692
- return void 0;
23693
- }
23694
- function extractCode(body) {
23695
- if (body && typeof body === "object" && "code" in body) {
23696
- return String(body["code"]);
23697
- }
23698
- return void 0;
23699
- }
23700
- function buildPublishCommand() {
23701
- 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) => {
23702
- const projectRoot = process.cwd();
23703
- let buildOutput;
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;
23704
24053
  try {
23705
- buildOutput = await buildApp(projectRoot, true);
24054
+ const manifest = await buildManifest(process.cwd());
24055
+ slug = manifest.slug;
24056
+ version2 ??= manifest.version;
23706
24057
  } catch (err) {
23707
24058
  if (err instanceof ManifestBuildError) {
23708
24059
  if (opts.json) {
23709
- console.log(JSON.stringify({ error: "BUILD_FAILED", message: err.message }));
24060
+ console.log(JSON.stringify({ ok: false, error: err.code, diagnostic: err.diagnostic }));
23710
24061
  } else {
23711
- console.error(`[BUILD_FAILED] ${err.message}`);
24062
+ console.error(`[MANIFEST_BUILD_FAILED] ${err.message}`);
23712
24063
  console.error(err.diagnostic);
23713
24064
  }
23714
24065
  process.exit(1);
23715
24066
  }
23716
24067
  throw err;
23717
24068
  }
23718
- if (!buildOutput.tarballPath || !buildOutput.tarballChecksum || !buildOutput.manifest.version) {
23719
- console.error('Build did not produce a tarball \u2014 check manifest has a "version" field');
23720
- process.exit(1);
23721
- }
23722
- const slug = buildOutput.manifest.slug;
23723
- const version2 = buildOutput.manifest.version;
23724
- let enginesWopilo;
23725
- if ((0, import_fs7.existsSync)((0, import_path5.join)(projectRoot, "package.json"))) {
23726
- const pkg = readPackageJson(projectRoot);
23727
- enginesWopilo = pkg.engines?.wopilo;
23728
- if (pkg.version && pkg.version !== version2 && !opts.json) {
23729
- console.warn(
23730
- `Note: package.json version (${pkg.version}) differs from manifest version (${version2}); publishing the manifest version. Bump manifest.version to release a new artefact.`
23731
- );
23732
- }
23733
- }
23734
24069
  const baseUrl = getRemoteUrl(opts.remote);
23735
24070
  const apiKey = resolveApiKey(opts.remote);
23736
- const tarballSize = (0, import_fs7.readFileSync)(buildOutput.tarballPath).length;
23737
24071
  try {
23738
- const result = await publishMultipart({
23739
- baseUrl,
23740
- apiKey,
23741
- tarballPath: buildOutput.tarballPath,
23742
- tarballChecksum: buildOutput.tarballChecksum,
23743
- packageName: slug,
23744
- packageVersion: version2,
23745
- enginesWopilo,
23746
- json: opts.json ?? false
23747
- });
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);
23748
24084
  if (opts.json) {
23749
24085
  console.log(
23750
24086
  JSON.stringify({
23751
- versionId: result.versionId,
23752
- package: slug,
23753
- version: version2,
23754
- tarballSize,
23755
- checksum: buildOutput.tarballChecksum
24087
+ ok: false,
24088
+ ...status !== void 0 ? { status } : {},
24089
+ error: message,
24090
+ ...hint ? { hint } : {}
23756
24091
  })
23757
24092
  );
23758
24093
  } else {
23759
- console.log(`Published ${slug}@${version2} \u2192 ${result.versionId}`);
23760
- console.log(` tarball : ${tarballSize} bytes`);
23761
- console.log(` checksum : ${buildOutput.tarballChecksum}`);
23762
- }
23763
- } catch (err) {
23764
- if (err instanceof ApiError) {
23765
- if (opts.json) {
23766
- console.log(
23767
- JSON.stringify({ error: String(err.status), message: err.message, body: err.body })
23768
- );
23769
- } else {
23770
- console.error(`Server error (${err.status}): ${err.message}`);
23771
- }
23772
- process.exit(1);
24094
+ console.error(
24095
+ status !== void 0 ? `Server error (${status}): ${message}` : `Install failed: ${message}`
24096
+ );
24097
+ if (hint) console.error(hint);
23773
24098
  }
23774
- throw err;
24099
+ process.exit(1);
23775
24100
  }
23776
24101
  });
23777
24102
  }
23778
24103
 
23779
24104
  // src/index.ts
23780
- 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();
23781
24114
  program2.addCommand(buildDevCommand());
23782
24115
  program2.addCommand(buildPlanCommand());
23783
- program2.addCommand(buildApplyCommand());
24116
+ program2.addCommand(buildDeployCommand());
23784
24117
  program2.addCommand(buildRemoteCommand());
23785
24118
  program2.addCommand(buildLoginCommand());
23786
24119
  program2.addCommand(buildBuildCommand());
23787
24120
  program2.addCommand(buildPublishCommand());
24121
+ program2.addCommand(buildInstallCommand());
23788
24122
  program2.parseAsync(process.argv).catch((err) => {
23789
24123
  console.error(err instanceof Error ? err.message : String(err));
23790
24124
  process.exit(1);