@supacloud/cli 0.55.1 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1198 -71
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -206240,6 +206240,19 @@ function schemaProperties(schema) {
206240
206240
  return schema;
206241
206241
  }
206242
206242
 
206243
+ // src/shared/outcome-guidance.ts
206244
+ function outcomeUnknownGuidance(text) {
206245
+ let payload;
206246
+ try {
206247
+ payload = JSON.parse(text);
206248
+ } catch {
206249
+ return null;
206250
+ }
206251
+ if (typeof payload !== "object" || payload === null || !("ok" in payload) || payload.ok !== false || !("error" in payload) || typeof payload.error !== "object" || payload.error === null || !("code" in payload.error) || payload.error.code !== "OUTCOME_UNKNOWN")
206252
+ return null;
206253
+ return "OUTCOME_UNKNOWN:操作结果无法确认,服务端可能已经完成操作,但客户端未收到可验证的最终结果。" + "请先查询当前状态或操作回执,再决定是否重试;不要直接重复提交。";
206254
+ }
206255
+
206243
206256
  // src/shared/cli.ts
206244
206257
  function cliToolResultIsError(toolResult) {
206245
206258
  if (toolResult.isError === true)
@@ -206369,6 +206382,9 @@ async function runCli(cliTools, args, options = {}) {
206369
206382
  for (const c of result.content) {
206370
206383
  if (c.type === "text") {
206371
206384
  console.log(c.text);
206385
+ const guidance = outcomeUnknownGuidance(c.text ?? "");
206386
+ if (guidance)
206387
+ console.error(guidance);
206372
206388
  }
206373
206389
  }
206374
206390
  } else {
@@ -206700,7 +206716,7 @@ var ACTION_POLICY = {
206700
206716
  write: ["send", "receive", "ack", "release", "fail", "retry", "delete_message", "update_settings"]
206701
206717
  },
206702
206718
  ai: { local: ["show_skill", "install_skill"] },
206703
- app: { local: ["init", "generate", "compile", "check", "graph", "explain", "export-tools"] },
206719
+ app: { local: ["init", "generate", "compile", "check", "graph", "explain", "export-tools", "context", "doctor", "fix"] },
206704
206720
  db: { local: ["lint", "explain"], read: ["module_check"] },
206705
206721
  dev: { read: ["status"], write: ["sync", "watch", "migrate"] }
206706
206722
  };
@@ -214520,8 +214536,8 @@ function registerAiTools(server2) {
214520
214536
 
214521
214537
  // src/shared/tools/app-tools.ts
214522
214538
  import { existsSync as existsSync10 } from "node:fs";
214523
- import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
214524
- import { dirname as dirname6, join as join12, resolve as resolve11 } from "node:path";
214539
+ import { mkdir as mkdir3, readFile as readFile3, readdir as readdir2, writeFile as writeFile4 } from "node:fs/promises";
214540
+ import { basename as basename7, dirname as dirname7, join as join12, relative as relative6, resolve as resolve11 } from "node:path";
214525
214541
 
214526
214542
  // node_modules/@supacloud/compiler/dist/index.js
214527
214543
  var ts7 = __toESM(require_typescript(), 1);
@@ -219923,7 +219939,12 @@ import { dirname as dirname32, join as join32, relative as relative32, resolve a
219923
219939
  var ts10 = __toESM(require_typescript(), 1);
219924
219940
  var ts9 = __toESM(require_typescript(), 1);
219925
219941
  var ts11 = __toESM(require_typescript(), 1);
219942
+ import { randomUUID } from "node:crypto";
219943
+ import { lstat as lstat2, readFile as readFile6, realpath as realpath3, rename as rename4, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
219944
+ import { dirname as dirname6, isAbsolute as isAbsolute22, relative as relative7, resolve as resolve82, sep as sep7 } from "node:path";
219926
219945
  var ts12 = __toESM(require_typescript(), 1);
219946
+ import { existsSync as existsSync42 } from "node:fs";
219947
+ import { dirname as dirname8, join as join72, relative as relative11, sep as sep10 } from "node:path";
219927
219948
  import { existsSync as existsSync52 } from "node:fs";
219928
219949
  import { join as join82, resolve as resolve14 } from "node:path";
219929
219950
  import { pathToFileURL as pathToFileURL2 } from "node:url";
@@ -220004,6 +220025,81 @@ function findClosestMatch(target, candidates) {
220004
220025
  }
220005
220026
  var REQUEST_CONTEXT_TOKEN_NAME = "supacloud.request-context";
220006
220027
  var JOB_CONTEXT_TOKEN_NAME = "supacloud.job-context";
220028
+ function buildContractManifest(graph, artifacts) {
220029
+ const commands = [];
220030
+ const queries = [];
220031
+ const routes = [];
220032
+ const permissions = new Set;
220033
+ const rpc = [];
220034
+ const events = [];
220035
+ const fixtures = new Set;
220036
+ for (const module of graph.modules) {
220037
+ for (const command of module.commands) {
220038
+ if (command.permission)
220039
+ permissions.add(command.permission);
220040
+ if (command.rpc)
220041
+ rpc.push({ command: command.name, adapter: command.rpc });
220042
+ if (command.audit)
220043
+ events.push({ name: command.audit, source: "command.audit", command: command.name });
220044
+ commands.push({
220045
+ name: command.name,
220046
+ className: command.className,
220047
+ module: module.name,
220048
+ ...command.permission === undefined ? {} : { permission: command.permission },
220049
+ ...command.rpc === undefined ? {} : { rpc: command.rpc },
220050
+ transaction: command.transaction,
220051
+ idempotency: command.idempotency,
220052
+ ...command.audit === undefined ? {} : { auditEvent: command.audit }
220053
+ });
220054
+ }
220055
+ for (const query of module.queries) {
220056
+ queries.push({ name: query.name, className: query.className, module: module.name });
220057
+ }
220058
+ for (const controller of module.controllers) {
220059
+ for (const route of controller.routes) {
220060
+ const command = route.command ? module.commands.find((candidate) => candidate.className === route.command) : undefined;
220061
+ if (command?.permission)
220062
+ permissions.add(command.permission);
220063
+ if (route.contract?.evidence)
220064
+ fixtures.add(route.contract.evidence);
220065
+ routes.push({
220066
+ method: route.method,
220067
+ path: joinRoutePaths(controller.path, route.path),
220068
+ module: module.name,
220069
+ controller: controller.className,
220070
+ handler: route.handler,
220071
+ ...route.command === undefined ? {} : { command: route.command },
220072
+ ...command?.permission === undefined ? {} : { permission: command.permission },
220073
+ requestSchemas: Object.fromEntries(["body", "params", "query", "headers", "cookie"].flatMap((key) => route[key] === undefined ? [] : [[key, route[key]]])),
220074
+ ...route.response === undefined ? {} : { responseSchema: route.response },
220075
+ ...route.contract?.evidence === undefined ? {} : { evidence: route.contract.evidence }
220076
+ });
220077
+ }
220078
+ }
220079
+ }
220080
+ commands.sort((left, right) => left.name.localeCompare(right.name));
220081
+ queries.sort((left, right) => left.name.localeCompare(right.name));
220082
+ routes.sort((left, right) => `${left.method} ${left.path}`.localeCompare(`${right.method} ${right.path}`));
220083
+ rpc.sort((left, right) => left.command.localeCompare(right.command));
220084
+ events.sort((left, right) => left.name.localeCompare(right.name));
220085
+ return {
220086
+ version: 1,
220087
+ commands,
220088
+ queries,
220089
+ routes,
220090
+ permissions: [...permissions].sort(),
220091
+ rpc,
220092
+ events,
220093
+ fixtures: [...fixtures].sort(),
220094
+ artifacts: {
220095
+ ...artifacts,
220096
+ sdk: "generated-client",
220097
+ openapiDocument: "generated",
220098
+ permissionManifest: "generated"
220099
+ }
220100
+ };
220101
+ }
220102
+ var init_contract_manifest = () => {};
220007
220103
  function normalizedResponseEntries(responses) {
220008
220104
  if (!responses)
220009
220105
  return [];
@@ -220141,9 +220237,16 @@ function renderApplication(graph, options) {
220141
220237
  const clientCode = options.generateClient ? renderClient(graph, options) : undefined;
220142
220238
  const openApiCode = options.generateOpenApi ? renderOpenApi(graph, options) : undefined;
220143
220239
  const permissionsCode = options.generatePermissions ? renderPermissions(graph) : undefined;
220240
+ const contractsManifest = buildContractManifest(graph, {
220241
+ client: clientCode !== undefined,
220242
+ openapi: openApiCode !== undefined,
220243
+ permissions: permissionsCode !== undefined
220244
+ });
220144
220245
  return {
220145
220246
  applicationCode: code,
220146
220247
  manifestJson: JSON.stringify(manifest, null, 2) + `
220248
+ `,
220249
+ contractsManifestJson: JSON.stringify(contractsManifest, null, 2) + `
220147
220250
  `,
220148
220251
  ...clientCode === undefined ? {} : { clientCode },
220149
220252
  ...openApiCode === undefined ? {} : { openApiCode },
@@ -220155,9 +220258,11 @@ async function generateApplication(graph, options) {
220155
220258
  await mkdir(options.outDir, { recursive: true });
220156
220259
  const applicationPath = join22(options.outDir, "application.ts");
220157
220260
  const manifestPath = join22(options.outDir, "app.manifest.json");
220261
+ const contractsManifestPath = join22(options.outDir, "contracts.manifest.json");
220158
220262
  const writeCandidates = [
220159
220263
  { path: applicationPath, content: rendered.applicationCode },
220160
- { path: manifestPath, content: rendered.manifestJson }
220264
+ { path: manifestPath, content: rendered.manifestJson },
220265
+ { path: contractsManifestPath, content: rendered.contractsManifestJson }
220161
220266
  ];
220162
220267
  if (rendered.clientCode) {
220163
220268
  writeCandidates.push({ path: join22(options.outDir, "client.ts"), content: rendered.clientCode });
@@ -222020,7 +222125,9 @@ function destroyScopeInstances(
222020
222125
  scopeDestructions.set(scope, destruction);
222021
222126
  return destruction;
222022
222127
  }`;
222023
- var init_generate = () => {};
222128
+ var init_generate = __esm2(() => {
222129
+ init_contract_manifest();
222130
+ });
222024
222131
  var GRAPHQL_CLIENT_SOURCE = `
222025
222132
  export interface GraphqlClientOptions {
222026
222133
  /** Project base URL, not the management API URL. HTTPS is required outside loopback. */
@@ -226571,6 +226678,7 @@ async function compileProject(options) {
226571
226678
  "client.ts": rendered.clientCode,
226572
226679
  "openapi.ts": rendered.openApiCode,
226573
226680
  "permissions.ts": rendered.permissionsCode,
226681
+ "contracts.manifest.json": rendered.contractsManifestJson,
226574
226682
  "graphql.ts": graphql.files["graphql.ts"],
226575
226683
  "graphql.documents.ts": graphql.files["graphql.documents.ts"]
226576
226684
  }, options.strict ?? false));
@@ -226640,7 +226748,8 @@ async function checkProject(options) {
226640
226748
  const expectedFiles = {
226641
226749
  ...graphql.files,
226642
226750
  "application.ts": rendered.applicationCode,
226643
- "app.manifest.json": rendered.manifestJson
226751
+ "app.manifest.json": rendered.manifestJson,
226752
+ "contracts.manifest.json": rendered.contractsManifestJson
226644
226753
  };
226645
226754
  if (rendered.clientCode) {
226646
226755
  expectedFiles["client.ts"] = rendered.clientCode;
@@ -229744,6 +229853,202 @@ var DeliveryBuildResultSchema = Type2.Union([
229744
229853
  }, closed)
229745
229854
  ]);
229746
229855
  init_generate();
229856
+ async function applyDiagnosticFix(fix, options = {}) {
229857
+ if (!fix || typeof fix.targetFile !== "string")
229858
+ throw new Error("Invalid DiagnosticFix");
229859
+ const root = await realpath3(options.rootDir ?? process.cwd());
229860
+ const file = resolve82(root, fix.targetFile);
229861
+ const stat = await lstat2(file);
229862
+ const resolved = await realpath3(file);
229863
+ const relativePath = relative7(root, resolved);
229864
+ if (stat.isSymbolicLink() || !stat.isFile() || isAbsolute22(relativePath) || relativePath === ".." || relativePath.startsWith(`..${sep7}`)) {
229865
+ throw new Error("Fix target must be a regular file inside rootDir");
229866
+ }
229867
+ const original = await readFile6(file, "utf8");
229868
+ let source = parse32(file, original);
229869
+ let content;
229870
+ switch (fix.type) {
229871
+ case "set_command_mode": {
229872
+ if (fix.property !== "transaction" && fix.property !== "idempotency" || fix.value !== "required" && fix.value !== "none") {
229873
+ throw new Error("Command mode fix requires an explicit property and policy value");
229874
+ }
229875
+ const object = decoratorObject(findClass(source, fix.command), "Command");
229876
+ const current = property(object, fix.property);
229877
+ if (!current || current.initializer.getText(source) !== fix.expectedExpression) {
229878
+ throw new Error("Command mode changed since diagnosis; analyze the project again");
229879
+ }
229880
+ content = replaceProperty(source, object, fix.property, ts11.factory.createStringLiteral(fix.value));
229881
+ break;
229882
+ }
229883
+ case "add_module_import": {
229884
+ if (!fix.importPath || !fix.symbol)
229885
+ throw new Error("Module fix requires importPath and symbol");
229886
+ identifier(fix.symbol);
229887
+ const withImport = importSymbol(source, fix.importPath, fix.symbol);
229888
+ source = parse32(file, withImport);
229889
+ const object = unique2(moduleObjects(source).filter((candidate) => !fix.targetModule || stringProperty(candidate, "name") === fix.targetModule), "target module");
229890
+ const imports = property(object, "imports");
229891
+ if (imports && !ts11.isArrayLiteralExpression(imports.initializer)) {
229892
+ throw new Error("Module imports must be a static array");
229893
+ }
229894
+ const values = imports && ts11.isArrayLiteralExpression(imports.initializer) ? imports.initializer.elements : [];
229895
+ if (values.some(ts11.isSpreadElement))
229896
+ throw new Error("Module imports cannot contain spread elements");
229897
+ content = values.some((value) => ts11.isIdentifier(value) && value.text === fix.symbol) ? withImport : replaceProperty(source, object, "imports", ts11.factory.createArrayLiteralExpression([
229898
+ ...values,
229899
+ ts11.factory.createIdentifier(fix.symbol)
229900
+ ]));
229901
+ break;
229902
+ }
229903
+ case "add_command_permission": {
229904
+ const permission = options.permission ?? fix.permission;
229905
+ if (!permission?.trim()) {
229906
+ throw new Error("Permission fix requires an explicit permission; privileges are never inferred");
229907
+ }
229908
+ const command = findClass(source, fix.command);
229909
+ const object = decoratorObject(command, "Command");
229910
+ const current = property(object, "permission");
229911
+ if (current && (!ts11.isStringLiteral(current.initializer) || current.initializer.text !== permission)) {
229912
+ throw new Error("Command permission already exists with a different value");
229913
+ }
229914
+ content = current ? original : replaceProperty(source, object, "permission", ts11.factory.createStringLiteral(permission));
229915
+ break;
229916
+ }
229917
+ case "add_route_parameter_binding": {
229918
+ const controller = findClass(source, fix.controller);
229919
+ const method = unique2(controller.members.filter((member) => ts11.isMethodDeclaration(member) && nameOf(member.name) === fix.route), "route handler");
229920
+ const parameter = unique2(method.parameters.filter((candidate) => ts11.isIdentifier(candidate.name) && candidate.name.text === fix.parameter), "same-named route parameter");
229921
+ const binding = fix.binding === "param" ? "Param" : fix.binding === "query" ? "Query" : undefined;
229922
+ if (!binding)
229923
+ throw new Error("Invalid route binding");
229924
+ const decorators = ts11.getDecorators(parameter) ?? [];
229925
+ if (decorators.length > 0)
229926
+ throw new Error("Parameter already has a decorator");
229927
+ const framework = unique2(source.statements.filter((statement) => ts11.isImportDeclaration(statement) && statement.importClause?.namedBindings && ts11.isNamedImports(statement.importClause.namedBindings) && statement.importClause.namedBindings.elements.some((element) => ["Controller", "Get", "Post", "Put", "Patch", "Delete", "Head", "Options"].includes(element.name.text))), "framework import");
229928
+ if (!ts11.isImportDeclaration(framework) || !ts11.isStringLiteral(framework.moduleSpecifier)) {
229929
+ throw new Error("Framework import must be static");
229930
+ }
229931
+ const edited = original.slice(0, parameter.getStart(source)) + `@${binding}(${JSON.stringify(fix.parameter)}) ` + original.slice(parameter.getStart(source));
229932
+ content = importSymbol(parse32(file, edited), framework.moduleSpecifier.text, binding);
229933
+ break;
229934
+ }
229935
+ default:
229936
+ throw new Error(`Diagnostic fix '${fix.type}' requires a manual semantic decision; no files changed`);
229937
+ }
229938
+ parse32(file, content);
229939
+ const result = { file, changed: content !== original, content };
229940
+ if (options.dryRun === false && result.changed) {
229941
+ const temporary = `${file}.supacloud-fix-${randomUUID()}`;
229942
+ try {
229943
+ await writeFile3(temporary, content, { encoding: "utf8", flag: "wx", mode: stat.mode });
229944
+ if (await readFile6(file, "utf8") !== original)
229945
+ throw new Error("Target changed while preparing the fix");
229946
+ await rename4(temporary, file);
229947
+ } finally {
229948
+ await unlink2(temporary).catch(() => {});
229949
+ }
229950
+ }
229951
+ return result;
229952
+ }
229953
+ function parse32(file, text) {
229954
+ const result = ts11.transpileModule(text, {
229955
+ fileName: file,
229956
+ reportDiagnostics: true,
229957
+ compilerOptions: { target: ts11.ScriptTarget.ESNext, experimentalDecorators: true }
229958
+ });
229959
+ if (result.diagnostics?.some((item) => item.category === ts11.DiagnosticCategory.Error)) {
229960
+ throw new Error("Cannot fix syntactically invalid TypeScript");
229961
+ }
229962
+ return ts11.createSourceFile(file, text, ts11.ScriptTarget.Latest, true, ts11.ScriptKind.TS);
229963
+ }
229964
+ function unique2(items, description) {
229965
+ if (items.length !== 1)
229966
+ throw new Error(`Expected exactly one ${description}; found ${items.length}`);
229967
+ return items[0];
229968
+ }
229969
+ function identifier(value) {
229970
+ if (!/^[A-Za-z_$][\w$]*$/.test(value))
229971
+ throw new Error(`Invalid identifier '${value}'`);
229972
+ }
229973
+ function nameOf(name) {
229974
+ if (!name)
229975
+ return "";
229976
+ return ts11.isIdentifier(name) || ts11.isStringLiteral(name) || ts11.isNumericLiteral(name) ? name.text : "";
229977
+ }
229978
+ function property(object, key) {
229979
+ if (object.properties.some((item) => !ts11.isPropertyAssignment(item) || ts11.isComputedPropertyName(item.name))) {
229980
+ throw new Error("Fix requires explicit static object properties");
229981
+ }
229982
+ const values = object.properties.filter((item) => ts11.isPropertyAssignment(item) && nameOf(item.name) === key);
229983
+ if (values.length > 1)
229984
+ throw new Error(`Duplicate '${key}' property`);
229985
+ return values[0];
229986
+ }
229987
+ function stringProperty(object, key) {
229988
+ const value = property(object, key)?.initializer;
229989
+ return value && ts11.isStringLiteral(value) ? value.text : undefined;
229990
+ }
229991
+ function replaceProperty(source, object, key, value) {
229992
+ const previous = property(object, key);
229993
+ const replacement = ts11.factory.createPropertyAssignment(key, value);
229994
+ const properties = object.properties.map((item) => item === previous ? replacement : item);
229995
+ if (!previous)
229996
+ properties.push(replacement);
229997
+ const updated = ts11.factory.updateObjectLiteralExpression(object, properties);
229998
+ return source.text.slice(0, object.getStart(source)) + ts11.createPrinter().printNode(ts11.EmitHint.Expression, updated, source) + source.text.slice(object.end);
229999
+ }
230000
+ function findClass(source, name) {
230001
+ return unique2(source.statements.filter((statement) => ts11.isClassDeclaration(statement) && statement.name?.text === name), `class '${name}'`);
230002
+ }
230003
+ function decoratorObject(node, name) {
230004
+ const decorator = unique2((ts11.getDecorators(node) ?? []).filter((item) => ts11.isCallExpression(item.expression) && item.expression.expression.getText() === name), `@${name} decorator`);
230005
+ const argument = ts11.isCallExpression(decorator.expression) ? decorator.expression.arguments[0] : undefined;
230006
+ if (!argument || !ts11.isObjectLiteralExpression(argument))
230007
+ throw new Error(`@${name} requires a static object`);
230008
+ return argument;
230009
+ }
230010
+ function moduleObjects(source) {
230011
+ const result = [];
230012
+ for (const statement of source.statements) {
230013
+ if (ts11.isClassDeclaration(statement) && (ts11.getDecorators(statement) ?? []).some((item) => ts11.isCallExpression(item.expression) && item.expression.expression.getText() === "Module")) {
230014
+ result.push(decoratorObject(statement, "Module"));
230015
+ }
230016
+ if (ts11.isVariableStatement(statement)) {
230017
+ for (const declaration of statement.declarationList.declarations) {
230018
+ const call = declaration.initializer;
230019
+ if (call && ts11.isCallExpression(call) && ["defineModule", "defineFeatureSlice"].includes(call.expression.getText()) && call.arguments[0] && ts11.isObjectLiteralExpression(call.arguments[0])) {
230020
+ result.push(call.arguments[0]);
230021
+ }
230022
+ }
230023
+ }
230024
+ }
230025
+ return result;
230026
+ }
230027
+ function importSymbol(source, path, symbol) {
230028
+ identifier(symbol);
230029
+ const current = resolve82(source.fileName).replace(/\.(tsx?|mts|cts)$/, "");
230030
+ const target = resolve82(dirname6(source.fileName), path).replace(/\.(tsx?|mts|cts)$/, "");
230031
+ if (current === target)
230032
+ return source.text;
230033
+ const matches = source.statements.filter((item) => ts11.isImportDeclaration(item) && ts11.isStringLiteral(item.moduleSpecifier) && item.moduleSpecifier.text === path);
230034
+ if (matches.length > 1)
230035
+ throw new Error(`Ambiguous imports from '${path}'`);
230036
+ const match = matches[0];
230037
+ if (match && ts11.isImportDeclaration(match) && match.importClause?.namedBindings && ts11.isNamedImports(match.importClause.namedBindings) && !match.importClause.isTypeOnly) {
230038
+ if (match.importClause.namedBindings.elements.some((item) => item.name.text === symbol))
230039
+ return source.text;
230040
+ const bindings = match.importClause.namedBindings;
230041
+ const updated = ts11.factory.updateNamedImports(bindings, [
230042
+ ...bindings.elements,
230043
+ ts11.factory.createImportSpecifier(false, undefined, ts11.factory.createIdentifier(symbol))
230044
+ ]);
230045
+ return source.text.slice(0, bindings.getStart(source)) + ts11.createPrinter().printNode(ts11.EmitHint.Unspecified, updated, source) + source.text.slice(bindings.end);
230046
+ }
230047
+ if (match)
230048
+ throw new Error(`Import from '${path}' is not a named value import`);
230049
+ return `import { ${symbol} } from ${JSON.stringify(path)};
230050
+ ${source.text}`;
230051
+ }
229747
230052
  init_graphql_inputs();
229748
230053
  var ROUTE_DECORATORS2 = new Set(["Get", "Post", "Put", "Patch", "Delete", "Head", "Options"]);
229749
230054
  var MIGRATION_COMPILER_OPTIONS = {
@@ -229753,7 +230058,180 @@ var MIGRATION_COMPILER_OPTIONS = {
229753
230058
  noEmit: true,
229754
230059
  skipLibCheck: true
229755
230060
  };
230061
+ function createContextPack(graph, subject) {
230062
+ const subjectModule = graph.modules.find((module) => module.name === subject);
230063
+ if (!subjectModule) {
230064
+ throw new Error(`No module named "${subject}". Context packs require a module name.`);
230065
+ }
230066
+ const byName = new Map(graph.modules.map((module) => [module.name, module]));
230067
+ const selected = new Set([subjectModule.name]);
230068
+ const reverseDependents = new Map;
230069
+ for (const mod of graph.modules) {
230070
+ for (const imp of mod.imports) {
230071
+ const list = reverseDependents.get(imp);
230072
+ if (list)
230073
+ list.push(mod.name);
230074
+ else
230075
+ reverseDependents.set(imp, [mod.name]);
230076
+ }
230077
+ }
230078
+ for (const direction of ["imports", "dependents"]) {
230079
+ const visited = new Set([subjectModule.name]);
230080
+ const queue = [subjectModule.name];
230081
+ let head = 0;
230082
+ while (head < queue.length) {
230083
+ const current = queue[head++];
230084
+ if (!current)
230085
+ continue;
230086
+ const module = byName.get(current);
230087
+ if (!module)
230088
+ continue;
230089
+ const neighbors = direction === "imports" ? module.imports : reverseDependents.get(module.name) ?? [];
230090
+ for (const neighbor of neighbors) {
230091
+ if (!visited.has(neighbor) && byName.has(neighbor)) {
230092
+ visited.add(neighbor);
230093
+ selected.add(neighbor);
230094
+ queue.push(neighbor);
230095
+ }
230096
+ }
230097
+ }
230098
+ }
230099
+ const modules = graph.modules.filter((module) => selected.has(module.name));
230100
+ const queryDocuments = graph.graphql?.documents.filter((file) => modules.some((module) => {
230101
+ const path = relative11(dirname8(module.file), file);
230102
+ return path !== ".." && !path.startsWith(`..${sep10}`);
230103
+ })) ?? [];
230104
+ const graphql = graph.graphql ? {
230105
+ ...graph.graphql,
230106
+ documents: queryDocuments,
230107
+ operations: graph.graphql.operations.filter((operation) => queryDocuments.includes(operation.file))
230108
+ } : undefined;
230109
+ const files = [...new Set(modules.flatMap((module) => [
230110
+ module.file,
230111
+ ...module.providers.map((provider) => provider.file),
230112
+ ...module.controllers.map((controller) => controller.file),
230113
+ ...allAspects(module).flatMap((aspect) => aspect.file ? [aspect.file] : [])
230114
+ ]).concat(graphql ? [graphql.schema, ...queryDocuments] : []))].sort();
230115
+ const referencedTokens = new Set;
230116
+ for (const module of modules) {
230117
+ for (const provider of module.providers) {
230118
+ for (const token of provider.deps)
230119
+ referencedTokens.add(token);
230120
+ }
230121
+ for (const controller of module.controllers) {
230122
+ for (const token of controller.deps)
230123
+ referencedTokens.add(token);
230124
+ }
230125
+ }
230126
+ return {
230127
+ version: 1,
230128
+ subject: subjectModule.name,
230129
+ modules,
230130
+ files,
230131
+ externalTokens: graph.externalTokens.filter((token) => referencedTokens.has(token)),
230132
+ executionPlans: createExecutionPlans({ ...graph, modules }),
230133
+ routeContracts: inspectRouteContracts({ ...graph, modules }),
230134
+ ...graphql ? { graphql } : {},
230135
+ diagnostics: (graph.diagnostics ?? []).filter((diagnostic) => diagnostic.file === undefined || files.includes(diagnostic.file)),
230136
+ relatedModules: {
230137
+ imports: subjectModule.imports.filter((name) => selected.has(name)),
230138
+ importedBy: graph.modules.filter((module) => module.imports.includes(subjectModule.name)).map((module) => module.name).sort()
230139
+ }
230140
+ };
230141
+ }
230142
+ function allAspects(module) {
230143
+ return [
230144
+ ...module.aspects ?? [],
230145
+ ...module.controllers.flatMap((controller) => controller.routes.flatMap((route) => route.aspects ?? [])),
230146
+ ...module.commands.flatMap((command) => command.aspects ?? []),
230147
+ ...(module.jobs ?? []).flatMap((job) => job.aspects ?? [])
230148
+ ];
230149
+ }
230150
+ function createExecutionPlans(graph) {
230151
+ const aspects = (boundary, refs = []) => refs.map((ref, index) => `${boundary}.aspect[${index}]:${ref.name}`);
230152
+ return graph.modules.flatMap((module) => [
230153
+ ...module.controllers.flatMap((controller) => controller.routes.map((route) => {
230154
+ const command = module.commands.find((item) => item.className === route.command);
230155
+ const path = `${controller.path}/${route.path}`.replace(/\/+/g, "/");
230156
+ return {
230157
+ module: module.name,
230158
+ kind: "route",
230159
+ name: `${route.method} ${path.length > 1 ? path.replace(/\/+$/, "") : path}`,
230160
+ ...command ? { command: command.name } : {},
230161
+ stages: [
230162
+ ...aspects(`module:${module.name}`, module.aspects),
230163
+ ...aspects("route", route.aspects),
230164
+ ...aspects("command", command?.aspects),
230165
+ ...command ? [
230166
+ "commandExecutor",
230167
+ "authorize",
230168
+ ...command.rpc ? [`rpc:${command.rpc}`] : [
230169
+ ...command.idempotency === "required" ? ["idempotency"] : [],
230170
+ ...command.transaction === "required" ? ["transaction"] : []
230171
+ ]
230172
+ ] : [],
230173
+ "handler",
230174
+ ...command?.audit && !command.rpc ? ["audit"] : []
230175
+ ]
230176
+ };
230177
+ })),
230178
+ ...module.commands.map((command) => ({
230179
+ module: module.name,
230180
+ kind: "command",
230181
+ name: command.name,
230182
+ command: command.name,
230183
+ stages: [
230184
+ "authorize",
230185
+ ...command.rpc ? [`rpc:${command.rpc}`] : [
230186
+ ...command.idempotency === "required" ? ["idempotency"] : [],
230187
+ ...command.transaction === "required" ? ["transaction"] : []
230188
+ ],
230189
+ ...aspects(`module:${module.name}`, module.aspects),
230190
+ ...aspects("command", command.aspects),
230191
+ "handler",
230192
+ ...command.audit && !command.rpc ? ["audit"] : []
230193
+ ]
230194
+ })),
230195
+ ...(module.jobs ?? []).map((job) => ({
230196
+ module: module.name,
230197
+ kind: "job",
230198
+ name: job.name,
230199
+ stages: [...aspects(`module:${module.name}`, module.aspects), ...aspects("job", job.aspects), "jobExecutor", "handler"]
230200
+ }))
230201
+ ]);
230202
+ }
230203
+ function doctorProject(rootDir, outDir, graph, upToDate, diagnostics = []) {
230204
+ const checks = [
230205
+ {
230206
+ name: "project-root",
230207
+ ok: existsSync42(rootDir),
230208
+ detail: existsSync42(rootDir) ? rootDir : `missing: ${rootDir}`
230209
+ },
230210
+ {
230211
+ name: "tsconfig",
230212
+ ok: existsSync42(join72(rootDir, "tsconfig.json")),
230213
+ detail: existsSync42(join72(rootDir, "tsconfig.json")) ? "tsconfig.json found" : "tsconfig.json missing"
230214
+ },
230215
+ {
230216
+ name: "modules",
230217
+ ok: graph.modules.length > 0,
230218
+ detail: `${graph.modules.length} module(s) discovered`
230219
+ },
230220
+ {
230221
+ name: "generated-artifacts",
230222
+ ok: upToDate,
230223
+ detail: upToDate ? "application.ts and app.manifest.json are up to date" : "generated artifacts are missing or stale"
230224
+ }
230225
+ ];
230226
+ const allDiagnostics = [...graph.diagnostics ?? [], ...diagnostics];
230227
+ return {
230228
+ checks,
230229
+ diagnostics: allDiagnostics,
230230
+ errors: allDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length + checks.filter((check) => !check.ok).length
230231
+ };
230232
+ }
229756
230233
  init_generate();
230234
+ init_contract_manifest();
229757
230235
  init_graphql_options();
229758
230236
  var DEFAULT_SUPACLOUD_CONFIG = {
229759
230237
  graphql: false,
@@ -230139,7 +230617,7 @@ test("partial and untagged inherited remote profiles cannot mix with selected fi
230139
230617
  // ../compiler/package.json
230140
230618
  var package_default = {
230141
230619
  name: "@supacloud/compiler",
230142
- version: "0.23.0",
230620
+ version: "0.24.0",
230143
230621
  description: "Static compiler for @supacloud/app metadata: builds the application graph from AST, validates it, and generates reflection-free factory code",
230144
230622
  type: "module",
230145
230623
  main: "./dist/index.js",
@@ -230204,7 +230682,7 @@ var package_default = {
230204
230682
  // ../app/package.json
230205
230683
  var package_default2 = {
230206
230684
  name: "@supacloud/app",
230207
- version: "0.15.0",
230685
+ version: "0.16.0",
230208
230686
  description: "Angular-style application metadata for SupaCloud: modules, DI tokens, providers, scopes, controllers and commands",
230209
230687
  type: "module",
230210
230688
  main: "./dist/index.js",
@@ -230255,7 +230733,7 @@ var package_default2 = {
230255
230733
  directory: "packages/app"
230256
230734
  },
230257
230735
  dependencies: {
230258
- "@supacloud/contracts": "file:../contracts",
230736
+ "@supacloud/contracts": "0.5.0",
230259
230737
  "@angular/core": "^22.1.5",
230260
230738
  "@sinclair/typebox": "^0.34.52"
230261
230739
  },
@@ -230335,10 +230813,83 @@ var package_default3 = {
230335
230813
  }
230336
230814
  };
230337
230815
 
230338
- // src/shared/tools/app-starter.ts
230816
+ // src/shared/tools/app-starter-templates.ts
230339
230817
  var json = (value) => `${JSON.stringify(value, null, 2)}
230340
230818
  `;
230341
- function appStarterFiles(name) {
230819
+ var DEV_SCRIPT = `import { watchProject, compileOptionsFromConfig, loadSupacloudConfig } from "@supacloud/compiler";
230820
+
230821
+ if (process.env.APP_ENV !== "development") throw new Error("The demo server is development-only");
230822
+ let server: ReturnType<typeof Bun.spawn> | undefined;
230823
+ let restarts = Promise.resolve();
230824
+ let closing = false;
230825
+ const watcher = watchProject({
230826
+ ...compileOptionsFromConfig(await loadSupacloudConfig()),
230827
+ writeOnError: false,
230828
+ onEvent: (event) => {
230829
+ if (event.type === "compile-error") console.error(event.diagnostics);
230830
+ if (event.type !== "compiled") return;
230831
+ restarts = restarts.then(async () => {
230832
+ if (server) { server.kill(); await server.exited; }
230833
+ if (closing) return;
230834
+ server = Bun.spawn([process.execPath, "--no-env-file", "scripts/serve.ts"], {
230835
+ stdin: "inherit", stdout: "inherit", stderr: "inherit", env: process.env,
230836
+ });
230837
+ }).catch((error) => { console.error(error); process.exitCode = 1; });
230838
+ },
230839
+ });
230840
+ const close = async () => {
230841
+ closing = true;
230842
+ await watcher.close();
230843
+ await restarts;
230844
+ if (server) { server.kill(); await server.exited; }
230845
+ process.exit(0);
230846
+ };
230847
+ process.once("SIGINT", close);
230848
+ process.once("SIGTERM", close);
230849
+ await watcher.ready;
230850
+ `;
230851
+ var SERVE_SCRIPT = `import { createDemo } from "./sandbox";
230852
+
230853
+ if (process.env.APP_ENV !== "development") throw new Error("The demo server is development-only");
230854
+ const port = Number(process.env.PORT ?? "3000");
230855
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
230856
+ const sandbox = createDemo();
230857
+ const server = Bun.serve({
230858
+ hostname: "127.0.0.1", port,
230859
+ fetch: (request) => sandbox.app.handle(request),
230860
+ });
230861
+ console.log("Local demo: " + server.url);
230862
+ `;
230863
+ var APPLICATION_SOURCE = (name) => `import { createApplication, createSupAuthRequestContext, type SupAuthContextOptions, type ApplicationOptions, type CommandGovernance } from "@supacloud/elysia";
230864
+ import { createCompiledModules } from "../generated/application";
230865
+
230866
+ export interface AppAdapters {
230867
+ deps: NonNullable<ApplicationOptions["deps"]>;
230868
+ requestContext: NonNullable<ApplicationOptions["requestContext"]>;
230869
+ commandGovernance: CommandGovernance;
230870
+ onExecution?: ApplicationOptions["onExecution"];
230871
+ }
230872
+
230873
+ // The host verifies external identity (SupAuth for unified login) before creating requestContext.
230874
+ export function createApp(adapters: AppAdapters) {
230875
+ return createApplication({
230876
+ ...adapters,
230877
+ name: ${JSON.stringify(name)},
230878
+ modules: createCompiledModules(),
230879
+ });
230880
+ }
230881
+
230882
+ export function createSupAuthApp(identity: SupAuthContextOptions, adapters: Omit<AppAdapters, "requestContext">) {
230883
+ return createApp({ ...adapters, requestContext: createSupAuthRequestContext(identity) });
230884
+ }
230885
+ `;
230886
+ var GENERATED_BOOTSTRAP = `// BOOTSTRAP ARTIFACT: bun run compile replaces this file.
230887
+ // Keeping a typed placeholder lets the first compile resolve the application entrypoint.
230888
+ export function createCompiledModules(): never {
230889
+ throw new Error("Run bun run compile before starting the application");
230890
+ }
230891
+ `;
230892
+ function baseFiles(name) {
230342
230893
  return {
230343
230894
  "package.json": json({
230344
230895
  name,
@@ -230384,6 +230935,283 @@ function appStarterFiles(name) {
230384
230935
  include: ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "generated/**/*.ts", "supacloud.config.ts"]
230385
230936
  }),
230386
230937
  "bunfig.toml": `env = false
230938
+ `,
230939
+ ".gitignore": ["node_modules/", "dist/", ".env", ".env.*", "!.env.*.example", "!.env.test", ""].join(`
230940
+ `),
230941
+ ".env.development.example": `APP_ENV=development
230942
+ PORT=3000
230943
+ `,
230944
+ ".env.test": `APP_ENV=test
230945
+ `,
230946
+ ".env.staging.example": `APP_ENV=staging
230947
+ # Inject credentials using the deployment platform.
230948
+ `,
230949
+ ".env.production.example": `APP_ENV=production
230950
+ # Inject credentials using the deployment platform.
230951
+ `,
230952
+ "supacloud.config.ts": `import { defineSupacloudConfig } from "@supacloud/compiler";
230953
+
230954
+ export default defineSupacloudConfig({
230955
+ root: "src",
230956
+ outDir: "generated",
230957
+ strict: true,
230958
+ moduleBoundaryPreset: "modular-monolith",
230959
+ typeSafety: { scanProductionSource: true, noAnyInGenerated: true },
230960
+ disallowControllerDirectDb: true,
230961
+ detectOrphanModules: true,
230962
+ commandCapabilities: { permission: true, transaction: true, idempotency: true, audit: true },
230963
+ });
230964
+ `,
230965
+ "src/application.ts": APPLICATION_SOURCE(name),
230966
+ "generated/application.ts": GENERATED_BOOTSTRAP,
230967
+ "scripts/environment.ts": STARTER_ENVIRONMENT,
230968
+ "tests/environment.test.ts": STARTER_ENVIRONMENT_TEST,
230969
+ "scripts/dev.ts": DEV_SCRIPT,
230970
+ "scripts/serve.ts": SERVE_SCRIPT
230971
+ };
230972
+ }
230973
+ function httpTemplate(name) {
230974
+ return {
230975
+ ...baseFiles(name),
230976
+ "src/orders/orders.ts": `import { Body, Controller, Get, Param, Post, defineFeatureSlice } from "@supacloud/app";
230977
+ import { status, t } from "elysia";
230978
+
230979
+ export const OrderParams = t.Object({ id: t.String({ minLength: 1 }) });
230980
+ export const CreateOrderBody = t.Object({ name: t.String({ minLength: 1 }) });
230981
+ export const OrderResult = t.Object({ id: t.String(), name: t.String() });
230982
+ export const HealthResult = t.Object({ ok: t.Boolean() });
230983
+
230984
+ @Controller("/orders")
230985
+ export class OrdersController {
230986
+ @Get("/health", { responses: { 200: HealthResult } })
230987
+ health(): { ok: boolean } { return { ok: true }; }
230988
+
230989
+ @Get("/:id", { params: OrderParams, responses: { 200: OrderResult } })
230990
+ get(@Param("id") id: string): { id: string; name: string } { return { id, name: "demo" }; }
230991
+
230992
+ @Post("/", { body: CreateOrderBody, responses: { 201: OrderResult } })
230993
+ create(@Body() body: { name: string }) {
230994
+ return status(201, { id: "demo", name: body.name });
230995
+ }
230996
+ }
230997
+
230998
+ export const OrdersFeature = defineFeatureSlice({
230999
+ name: "orders",
231000
+ tags: ["type:feature"],
231001
+ controllers: [OrdersController],
231002
+ });
231003
+ `,
231004
+ "scripts/sandbox.ts": `import { createMemorySandbox } from "@supacloud/elysia";
231005
+ import { createCompiledModules } from "../generated/application";
231006
+
231007
+ export function createDemo() {
231008
+ if (process.env.APP_ENV !== "development" && process.env.APP_ENV !== "test") {
231009
+ throw new Error("Memory adapters are restricted to development and test");
231010
+ }
231011
+ return createMemorySandbox({
231012
+ modules: createCompiledModules(),
231013
+ identity: { authenticated: true, subject: "local-demo" },
231014
+ });
231015
+ }
231016
+ `,
231017
+ "tests/orders.test.ts": `import { expect, test } from "bun:test";
231018
+ import { createDemo } from "../scripts/sandbox";
231019
+
231020
+ test("health, read and create routes follow the declared HTTP contract", async () => {
231021
+ const sandbox = createDemo();
231022
+ expect((await sandbox.request("/orders/health")).status).toBe(200);
231023
+ expect((await sandbox.request("/orders/1")).status).toBe(200);
231024
+ const created = await sandbox.request("/orders", {
231025
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "first" }),
231026
+ });
231027
+ expect(created.status).toBe(201);
231028
+ expect(await created.json()).toEqual({ id: "demo", name: "first" });
231029
+ const invalid = await sandbox.request("/orders", {
231030
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({}),
231031
+ });
231032
+ expect(invalid.status).toBe(422);
231033
+ });
231034
+ `,
231035
+ "README.md": `# ${name}
231036
+
231037
+ HTTP API golden path.
231038
+
231039
+ ## Local Development
231040
+
231041
+ \`\`\`sh
231042
+ bun install
231043
+ bun run check
231044
+ bun run dev
231045
+ \`\`\`
231046
+
231047
+ The server binds only to 127.0.0.1:3000 by default.
231048
+
231049
+ \`\`\`sh
231050
+ curl http://127.0.0.1:3000/orders/health
231051
+ curl http://127.0.0.1:3000/orders/1
231052
+ curl -X POST http://127.0.0.1:3000/orders \\
231053
+ -H 'Content-Type: application/json' -d '{"name":"first"}'
231054
+ \`\`\`
231055
+
231056
+ The generated feature declares explicit route schemas so the compiler can detect
231057
+ route/schema drift. Keep request and response shapes in \`src/orders/orders.ts\`;
231058
+ do not widen them to \`unknown\` just to accept unvalidated data.
231059
+
231060
+ ## Production Boundary
231061
+
231062
+ \`bun run build\` emits an application factory, not a server. Import \`createApp\`
231063
+ from \`dist/application.js\` in your trusted host and supply real dependency,
231064
+ request-context and command-governance adapters. The memory sandbox is
231065
+ development/test only.
231066
+
231067
+ ## Inspection And Repair
231068
+
231069
+ \`\`\`sh
231070
+ supacloud context --root . --target orders --format json
231071
+ supacloud doctor --root .
231072
+ \`\`\`
231073
+ `
231074
+ };
231075
+ }
231076
+ function edgeTemplate(name) {
231077
+ return {
231078
+ ...baseFiles(name),
231079
+ "src/sync/sync.ts": `import { Injectable, Job, defineFeatureSlice } from "@supacloud/app";
231080
+
231081
+ /**
231082
+ * Worker/edge golden path: a declared, retry-bounded job with an explicit
231083
+ * idempotency requirement. The platform owns scheduling, retry and DLQ; the
231084
+ * handler stays side-effect explicit and must not assume exactly-once execution.
231085
+ */
231086
+ @Injectable()
231087
+ @Job({
231088
+ name: "sync.orders",
231089
+ mode: "task",
231090
+ idempotency: "required",
231091
+ timeoutSec: 60,
231092
+ maxAttempts: 3,
231093
+ })
231094
+ export class SyncOrdersJob {
231095
+ async run(): Promise<{ ok: boolean }> {
231096
+ return { ok: true };
231097
+ }
231098
+ }
231099
+
231100
+ export const SyncFeature = defineFeatureSlice({
231101
+ name: "sync",
231102
+ tags: ["type:feature"],
231103
+ providers: [SyncOrdersJob],
231104
+ jobs: [SyncOrdersJob],
231105
+ });
231106
+ `,
231107
+ "scripts/sandbox.ts": `import { createMemorySandbox } from "@supacloud/elysia";
231108
+ import { createCompiledModules } from "../generated/application";
231109
+
231110
+ export function createDemo() {
231111
+ if (process.env.APP_ENV !== "development" && process.env.APP_ENV !== "test") {
231112
+ throw new Error("Memory adapters are restricted to development and test");
231113
+ }
231114
+ return createMemorySandbox({
231115
+ modules: createCompiledModules(),
231116
+ identity: { authenticated: true, subject: "local-worker" },
231117
+ });
231118
+ }
231119
+ `,
231120
+ "tests/sync.test.ts": `import { expect, test } from "bun:test";
231121
+ import { SyncOrdersJob } from "../src/sync/sync";
231122
+
231123
+ test("the declared job handler is deterministic and idempotent by construction", async () => {
231124
+ const job = new SyncOrdersJob();
231125
+ expect(await job.run()).toEqual({ ok: true });
231126
+ expect(await job.run()).toEqual({ ok: true });
231127
+ });
231128
+ `,
231129
+ "README.md": `# ${name}
231130
+
231131
+ Worker / Edge golden path.
231132
+
231133
+ ## Local Development
231134
+
231135
+ \`\`\`sh
231136
+ bun install
231137
+ bun run check
231138
+ bun run test
231139
+ \`\`\`
231140
+
231141
+ \`src/sync/sync.ts\` declares a platform job with an explicit mode, timeout,
231142
+ attempt bound and idempotency requirement. The platform schedules and retries;
231143
+ the handler must be safe to run more than once and must not assume exactly-once
231144
+ execution.
231145
+
231146
+ ## Production Boundary
231147
+
231148
+ The job runs through the platform worker/edge adapter, not the local memory
231149
+ sandbox. Bind persistence, authorization and audit to durable adapters before
231150
+ invoking it in production. Do not schedule destructive work without an
231151
+ idempotency key.
231152
+
231153
+ ## Inspection And Repair
231154
+
231155
+ \`\`\`sh
231156
+ supacloud context --root . --target sync --format json
231157
+ supacloud doctor --root .
231158
+ \`\`\`
231159
+ `
231160
+ };
231161
+ }
231162
+ function appTemplateFiles(name, template) {
231163
+ return template === "http" ? httpTemplate(name) : edgeTemplate(name);
231164
+ }
231165
+
231166
+ // src/shared/tools/app-starter.ts
231167
+ var json2 = (value) => `${JSON.stringify(value, null, 2)}
231168
+ `;
231169
+ function appStarterFiles(name) {
231170
+ return {
231171
+ "package.json": json2({
231172
+ name,
231173
+ version: "0.0.0",
231174
+ private: true,
231175
+ type: "module",
231176
+ engines: { bun: ">=1.4.2" },
231177
+ scripts: {
231178
+ compile: "bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js compile",
231179
+ "check:generated": "bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js check",
231180
+ typecheck: "tsc --noEmit",
231181
+ check: "bun run compile && bun run check:generated && bun run typecheck && bun run test",
231182
+ test: "bun run compile && bun --no-env-file scripts/environment.ts test bun test",
231183
+ dev: "bun --no-env-file scripts/environment.ts development bun scripts/dev.ts",
231184
+ build: "bun run compile && bun run typecheck && bun build src/application.ts --target bun --minify --outdir dist",
231185
+ "env:development": "bun --no-env-file scripts/environment.ts development",
231186
+ "env:test": "bun --no-env-file scripts/environment.ts test",
231187
+ "env:staging": "bun --no-env-file scripts/environment.ts staging",
231188
+ "env:production": "bun --no-env-file scripts/environment.ts production"
231189
+ },
231190
+ dependencies: {
231191
+ "@supacloud/app": `^${package_default2.version}`,
231192
+ "@supacloud/elysia": `^${package_default3.version}`,
231193
+ elysia: "^1.4.30"
231194
+ },
231195
+ devDependencies: {
231196
+ "@supacloud/compiler": `^${package_default.version}`,
231197
+ "@types/bun": "^1.4.2",
231198
+ typescript: "^7.0.2"
231199
+ }
231200
+ }),
231201
+ "tsconfig.json": json2({
231202
+ compilerOptions: {
231203
+ target: "ES2022",
231204
+ module: "ESNext",
231205
+ moduleResolution: "bundler",
231206
+ strict: true,
231207
+ experimentalDecorators: true,
231208
+ skipLibCheck: true,
231209
+ noEmit: true,
231210
+ types: ["bun"]
231211
+ },
231212
+ include: ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "generated/**/*.ts", "supacloud.config.ts"]
231213
+ }),
231214
+ "bunfig.toml": `env = false
230387
231215
  `,
230388
231216
  ".gitignore": [
230389
231217
  "node_modules/",
@@ -230880,7 +231708,8 @@ async function initializeAppProject(options) {
230880
231708
  if ((await readdir(root)).some((entry) => entry !== ".git")) {
230881
231709
  throw new Error("app init requires an empty directory (an existing .git directory is allowed)");
230882
231710
  }
230883
- const files = appStarterFiles(name);
231711
+ const template = options.template ?? "command";
231712
+ const files = template === "command" ? appStarterFiles(name) : appTemplateFiles(name, template);
230884
231713
  for (const [relativePath, content] of Object.entries(files)) {
230885
231714
  const path = join11(root, relativePath);
230886
231715
  await mkdir2(dirname5(path), { recursive: true });
@@ -230893,9 +231722,10 @@ async function initializeAppProject(options) {
230893
231722
  async function initProject(args) {
230894
231723
  if (args.force)
230895
231724
  throw new Error("app init never overwrites files; choose an empty directory");
230896
- const { root, name, files } = await initializeAppProject(args);
231725
+ const template = args.template ?? "command";
231726
+ const { root, name, files } = await initializeAppProject({ root: args.root, name: args.name, template });
230897
231727
  return textResult([
230898
- `Initialized ${name} in ${root} (${files.length} files).`,
231728
+ `Initialized ${name} in ${root} (${files.length} files, template: ${template}).`,
230899
231729
  `cd '${root.replaceAll("'", "'\\''")}'`,
230900
231730
  "bun install",
230901
231731
  "bun run check",
@@ -230929,11 +231759,11 @@ async function writeScaffold(path, content, force) {
230929
231759
  if (!force) {
230930
231760
  throw new Error(`File already exists: ${path}(使用 --force 覆盖)`);
230931
231761
  }
230932
- await writeFile3(path, content, "utf8");
231762
+ await writeFile4(path, content, "utf8");
230933
231763
  return "overwritten";
230934
231764
  }
230935
- await mkdir3(dirname6(path), { recursive: true });
230936
- await writeFile3(path, content, "utf8");
231765
+ await mkdir3(dirname7(path), { recursive: true });
231766
+ await writeFile4(path, content, "utf8");
230937
231767
  return "created";
230938
231768
  }
230939
231769
  function moduleScaffold(name) {
@@ -230977,10 +231807,39 @@ function controllerScaffold(moduleName) {
230977
231807
  export class ${pascalName2(moduleName)}Controller {}
230978
231808
  `;
230979
231809
  }
231810
+ function jobScaffold(moduleName, name) {
231811
+ return `import { Injectable, Job } from "@supacloud/app";
231812
+
231813
+ @Injectable()
231814
+ @Job({
231815
+ name: ${JSON.stringify(`${moduleName}.${camelName2(name)}`)},
231816
+ mode: "task",
231817
+ // Optional: declare input/output TypeBox schemas for a validated, typed job boundary.
231818
+ })
231819
+ export class ${pascalName2(name)}Job {
231820
+ run(): Promise<void> {
231821
+ throw new Error("Implement ${pascalName2(name)}Job.run before dispatching this job");
231822
+ }
231823
+ }
231824
+ `;
231825
+ }
231826
+ function contractScaffold(moduleName, name) {
231827
+ const prefix = pascalName2(name);
231828
+ return `import { t } from "elysia";
231829
+
231830
+ /**
231831
+ * Input/output contract for ${moduleName}.${camelName2(name)}.
231832
+ * Keep these shapes explicit and reuse them in route schemas and command decoders;
231833
+ * never widen them to unknown just to accept unvalidated request data.
231834
+ */
231835
+ export const ${prefix}Body = t.Object({});
231836
+ export const ${prefix}Response = t.Object({});
231837
+ `;
231838
+ }
230980
231839
  async function generateScaffold(args) {
230981
231840
  const kind = args.kind;
230982
231841
  if (!kind)
230983
- throw new Error("app generate requires --kind (module|command|query|controller)");
231842
+ throw new Error("app generate requires --kind (module|command|query|controller|job|contract)");
230984
231843
  const root = resolve11(args.root || process.cwd());
230985
231844
  const dir = args.dir || "src/features";
230986
231845
  if (kind === "module") {
@@ -230992,18 +231851,39 @@ async function generateScaffold(args) {
230992
231851
  const moduleName = requireIdentifier(args.module, "module");
230993
231852
  const name = kind === "controller" ? moduleName : requireIdentifier(args.name, "name");
230994
231853
  const fileName = kind === "controller" ? `${moduleName}.controller.ts` : `${name}.${kind}.ts`;
230995
- const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : "";
231854
+ const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : "";
230996
231855
  const path = join12(root, dir, moduleName, subdir, fileName);
230997
231856
  if (kind === "controller" && existsSync10(path)) {
230998
231857
  throw new Error(`Controller already exists: ${path}(请手工合并路由到现有 controller)`);
230999
231858
  }
231000
- const content = kind === "command" ? commandScaffold(moduleName, name) : kind === "query" ? queryScaffold(moduleName, name) : controllerScaffold(moduleName);
231859
+ const content = kind === "command" ? commandScaffold(moduleName, name) : kind === "query" ? queryScaffold(moduleName, name) : kind === "job" ? jobScaffold(moduleName, name) : kind === "contract" ? contractScaffold(moduleName, name) : controllerScaffold(moduleName);
231001
231860
  const status = await writeScaffold(path, content, args.force === true);
231861
+ if (kind === "contract") {
231862
+ const prefix = pascalName2(name);
231863
+ return textResult([
231864
+ `✅ ${status}: ${path}`,
231865
+ "",
231866
+ "Next, bind the contract to a route so the compiler can check route/schema drift:",
231867
+ ` import { ${prefix}Body, ${prefix}Response } from "./contracts/${name}.contract";`,
231868
+ ` @Post("/", { body: ${prefix}Body, responses: { 200: ${prefix}Response } })`,
231869
+ "Fill in the schema fields and reuse them in command decoders; never widen them to unknown."
231870
+ ].join(`
231871
+ `));
231872
+ }
231002
231873
  return textResult(`✅ ${status}: ${path}`);
231003
231874
  }
231004
231875
  function formatDiagnostic(diagnostic) {
231876
+ const code = diagnostic.errorCode && diagnostic.errorCode !== diagnostic.code ? `${diagnostic.code} (${diagnostic.errorCode})` : diagnostic.code;
231005
231877
  const location = diagnostic.file ? ` ${diagnostic.file}${diagnostic.line ? `:${diagnostic.line}` : ""}` : "";
231006
- return `${diagnostic.severity} ${diagnostic.code}${location} ${diagnostic.message}`;
231878
+ const lines = [`${diagnostic.severity} ${code}${location} ${diagnostic.message}`];
231879
+ if (diagnostic.suggestion)
231880
+ lines.push(` hint: ${diagnostic.suggestion}`);
231881
+ if (diagnostic.docsUrl)
231882
+ lines.push(` docs: ${diagnostic.docsUrl}`);
231883
+ if (diagnostic.fix)
231884
+ lines.push(` fixable: ${diagnostic.fix.type}; apply with \`supacloud app fix --fix <file.json> --write\``);
231885
+ return lines.join(`
231886
+ `);
231007
231887
  }
231008
231888
  function formatDiagnostics(diagnostics) {
231009
231889
  if (diagnostics.length === 0)
@@ -231019,6 +231899,181 @@ function sourceRoot(args, root, configured) {
231019
231899
  const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync10(join12(root, `supacloud.config.${extension}`)));
231020
231900
  return args.root && !hasConfig ? "." : configured;
231021
231901
  }
231902
+ async function projectCompileConfig(args) {
231903
+ const root = resolve11(args.root || process.cwd());
231904
+ const configFile = ["ts", "mts", "js", "mjs"].map((extension) => join12(root, `supacloud.config.${extension}`)).find((candidate) => existsSync10(candidate)) ?? null;
231905
+ const loadedConfig = await loadSupacloudConfig(root);
231906
+ const defaults = resolveSupacloudConfig(loadedConfig, root);
231907
+ const configuredRoot = sourceRoot(args, root, loadedConfig.root);
231908
+ const include = parseInclude(args.include) ?? loadedConfig.include;
231909
+ const outDir = args.out_dir ? resolve11(root, args.out_dir) : defaults.outDir;
231910
+ const result = await checkProject(compileOptionsFromConfig({
231911
+ ...loadedConfig,
231912
+ ...configuredRoot === undefined ? {} : { root: configuredRoot },
231913
+ outDir,
231914
+ ...include === undefined ? {} : { include },
231915
+ strict: args.strict ?? loadedConfig.strict ?? false
231916
+ }, root));
231917
+ return { root, configFile, outDir, result };
231918
+ }
231919
+ async function readAllowedDependencies(root) {
231920
+ const path = join12(root, "package.json");
231921
+ if (!existsSync10(path))
231922
+ return { dependencies: [], devDependencies: [] };
231923
+ try {
231924
+ const parsed = JSON.parse(await readFile3(path, "utf8"));
231925
+ return {
231926
+ dependencies: Object.keys(parsed.dependencies ?? {}).sort(),
231927
+ devDependencies: Object.keys(parsed.devDependencies ?? {}).sort()
231928
+ };
231929
+ } catch {
231930
+ return { dependencies: [], devDependencies: [] };
231931
+ }
231932
+ }
231933
+ function formatModuleContextPack(pack) {
231934
+ return [
231935
+ `CONTEXT ${pack.subject}`,
231936
+ ` modules: ${pack.modules.map((module) => module.name).join(", ") || "-"}`,
231937
+ ` files: ${pack.files.join(", ") || "-"}`,
231938
+ ` external tokens: ${pack.externalTokens.join(", ") || "-"}`,
231939
+ ` imports: ${pack.relatedModules.imports.join(", ") || "-"}`,
231940
+ ` imported by: ${pack.relatedModules.importedBy.join(", ") || "-"}`,
231941
+ ...pack.graphql ? [
231942
+ ` graphql schema: ${pack.graphql.schema}`,
231943
+ ` graphql queries: ${pack.graphql.operations.map((operation) => operation.name).join(", ") || "-"}`
231944
+ ] : [],
231945
+ ...pack.executionPlans.map((plan) => ` execution ${plan.name}: ${plan.stages.join(" -> ")}`),
231946
+ ...pack.diagnostics.map(formatDiagnostic)
231947
+ ].join(`
231948
+ `);
231949
+ }
231950
+ async function runContext(args) {
231951
+ const { root, configFile, outDir, result } = await projectCompileConfig(args);
231952
+ const subject = args.target?.trim();
231953
+ if (subject) {
231954
+ const pack = createContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject);
231955
+ return textResult(args.format === "json" ? JSON.stringify(pack, null, 2) : formatModuleContextPack(pack));
231956
+ }
231957
+ const project = {
231958
+ version: 1,
231959
+ root,
231960
+ configFile,
231961
+ generatedDir: outDir,
231962
+ modules: result.graph.modules,
231963
+ externalTokens: result.graph.externalTokens,
231964
+ diagnostics: result.diagnostics,
231965
+ allowedDependencies: await readAllowedDependencies(root),
231966
+ commands: {
231967
+ check: "supacloud app check",
231968
+ compile: "supacloud app compile",
231969
+ context: "supacloud app context --format json",
231970
+ doctor: "supacloud app doctor",
231971
+ fix: "supacloud app fix --fix <fix.json> --write",
231972
+ graph: "supacloud app graph --format json",
231973
+ explain: "supacloud app explain --target <name>"
231974
+ }
231975
+ };
231976
+ if (args.format === "json")
231977
+ return textResult(JSON.stringify(project, null, 2));
231978
+ return textResult([
231979
+ `CONTEXT ${root}`,
231980
+ ` config: ${configFile ?? "(none)"}`,
231981
+ ` generated: ${outDir}`,
231982
+ ` modules: ${project.modules.map((module) => module.name).join(", ") || "-"}`,
231983
+ ` external tokens: ${project.externalTokens.join(", ") || "-"}`,
231984
+ ` dependencies: ${project.allowedDependencies.dependencies.join(", ") || "-"}`,
231985
+ ...project.diagnostics.map(formatDiagnostic)
231986
+ ].join(`
231987
+ `));
231988
+ }
231989
+ function doctorFixPlan(doctor) {
231990
+ return (doctor.diagnostics ?? []).filter((diagnostic) => diagnostic.fix !== undefined).map((diagnostic) => ({
231991
+ code: diagnostic.code,
231992
+ ...diagnostic.errorCode === undefined ? {} : { errorCode: diagnostic.errorCode },
231993
+ ...diagnostic.file === undefined ? {} : { file: diagnostic.file },
231994
+ ...diagnostic.line === undefined ? {} : { line: diagnostic.line },
231995
+ type: diagnostic.fix.type,
231996
+ targetFile: diagnostic.fix.targetFile,
231997
+ command: "supacloud app fix --fix <fix.json> --write"
231998
+ }));
231999
+ }
232000
+ async function findUnwiredContracts(rootDir) {
232001
+ const files = [];
232002
+ const skip = new Set(["node_modules", "dist", "generated", ".git", ".svelte-kit", "coverage"]);
232003
+ async function walk(directory) {
232004
+ let entries;
232005
+ try {
232006
+ entries = await readdir2(directory, { withFileTypes: true });
232007
+ } catch {
232008
+ return;
232009
+ }
232010
+ for (const entry of entries) {
232011
+ if (skip.has(entry.name))
232012
+ continue;
232013
+ const path = join12(directory, entry.name);
232014
+ if (entry.isDirectory())
232015
+ await walk(path);
232016
+ else if (entry.isFile() && entry.name.endsWith(".ts"))
232017
+ files.push(path);
232018
+ }
232019
+ }
232020
+ await walk(rootDir);
232021
+ const contracts = files.filter((file) => file.endsWith(".contract.ts"));
232022
+ if (contracts.length === 0)
232023
+ return [];
232024
+ const otherSources = await Promise.all(files.filter((file) => !contracts.includes(file)).map(async (file) => await readFile3(file, "utf8").catch(() => "")));
232025
+ const unwired = [];
232026
+ for (const contract of contracts) {
232027
+ const source = await readFile3(contract, "utf8").catch(() => "");
232028
+ const symbols = [...source.matchAll(/export\s+const\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)].map((match) => match[1]);
232029
+ if (symbols.length === 0)
232030
+ continue;
232031
+ const moduleName = basename7(contract).replace(/\.ts$/, "");
232032
+ const wired = otherSources.some((text) => text.includes(moduleName) || symbols.some((symbol) => new RegExp(`\\b${symbol}\\b`).test(text)));
232033
+ if (!wired)
232034
+ unwired.push({ file: relative6(rootDir, contract), symbols });
232035
+ }
232036
+ return unwired;
232037
+ }
232038
+ async function runDoctor(args) {
232039
+ const { root, outDir, result } = await projectCompileConfig(args);
232040
+ const doctor = doctorProject(root, outDir, result.graph, result.upToDate, result.diagnostics);
232041
+ const fixPlan = doctorFixPlan(doctor);
232042
+ const unwiredContracts = await findUnwiredContracts(root);
232043
+ if (args.format === "json") {
232044
+ return textResult(JSON.stringify({ ok: doctor.errors === 0, autoFixable: fixPlan.length, fixPlan, unwiredContracts, ...doctor }, null, 2), doctor.errors > 0);
232045
+ }
232046
+ const lines = doctor.checks.map((check) => `${check.ok ? "OK" : "FAIL"} ${check.name}: ${check.detail}`);
232047
+ for (const diagnostic of doctor.diagnostics ?? []) {
232048
+ lines.push(formatDiagnostic(diagnostic));
232049
+ }
232050
+ lines.push("");
232051
+ lines.push(doctor.errors === 0 ? "No blocking issues. Run `supacloud app compile` to refresh generated artifacts." : `${doctor.errors} blocking issue(s). Run \`supacloud app check\` for the full diagnostic list.`);
232052
+ if (fixPlan.length > 0) {
232053
+ lines.push(`${fixPlan.length} auto-fixable diagnostic(s): run \`supacloud app doctor --format json\`, save each \`fix\`, then \`supacloud app fix --fix <fix.json> --write\`.`);
232054
+ }
232055
+ if (unwiredContracts.length > 0) {
232056
+ lines.push(`${unwiredContracts.length} unwired contract file(s): ${unwiredContracts.map((contract) => contract.file).join(", ")}. Import their schemas into a controller route or remove them.`);
232057
+ }
232058
+ return textResult(lines.join(`
232059
+ `), doctor.errors > 0);
232060
+ }
232061
+ async function runFix(args) {
232062
+ const root = resolve11(args.root || process.cwd());
232063
+ const fixPath = args.fix?.trim();
232064
+ if (!fixPath)
232065
+ throw new Error("app fix requires --fix <path-to-diagnostic-fix.json>");
232066
+ const parsed = JSON.parse(await readFile3(resolve11(root, fixPath), "utf8"));
232067
+ const write = args.write === true;
232068
+ const applied = await applyDiagnosticFix(parsed, { rootDir: root, dryRun: !write });
232069
+ return textResult(JSON.stringify({
232070
+ ok: true,
232071
+ written: write,
232072
+ file: applied.file,
232073
+ changed: applied.changed,
232074
+ ...write ? {} : { preview: applied.content }
232075
+ }, null, 2));
232076
+ }
231022
232077
  async function runCompile(args) {
231023
232078
  const root = resolve11(args.root || process.cwd());
231024
232079
  const loadedConfig = await loadSupacloudConfig(root);
@@ -231101,6 +232156,9 @@ function formatGraphText(manifest) {
231101
232156
  for (const query of module.queries) {
231102
232157
  lines.push(` query: ${query.name} (${query.className})`);
231103
232158
  }
232159
+ for (const job of module.jobs ?? []) {
232160
+ lines.push(` job: ${job.name} (${job.className})`);
232161
+ }
231104
232162
  if (module.exports.length > 0)
231105
232163
  lines.push(` exports: ${module.exports.join(", ")}`);
231106
232164
  }
@@ -231178,10 +232236,32 @@ function explainController(manifest, module, index) {
231178
232236
  async function runExplain(args) {
231179
232237
  const target = args.target?.trim();
231180
232238
  if (!target)
231181
- throw new Error("app explain requires --target(provider 类名 / token 名 / command 名)");
232239
+ throw new Error("app explain requires --target(provider 类名 / token 名 / command 名 / job 名)");
231182
232240
  const root = resolve11(args.root || process.cwd());
231183
232241
  const manifest = await readManifest(root);
231184
232242
  for (const module of manifest.modules) {
232243
+ const job = module.jobs?.find((entry) => entry.name === target || entry.className === target);
232244
+ if (job) {
232245
+ const lines = [
232246
+ `对象: ${job.name}`,
232247
+ "类型: job",
232248
+ `所属模块: ${module.name}`,
232249
+ `类: ${job.className}`,
232250
+ `scope: ${job.scope}`
232251
+ ];
232252
+ if (job.mode)
232253
+ lines.push(`mode: ${job.mode}`);
232254
+ if (job.timeoutSec !== undefined)
232255
+ lines.push(`timeoutSec: ${job.timeoutSec}`);
232256
+ if (job.maxAttempts !== undefined)
232257
+ lines.push(`maxAttempts: ${job.maxAttempts}`);
232258
+ if (job.idempotency)
232259
+ lines.push(`idempotency: ${job.idempotency}`);
232260
+ const dependents = reverseDependencies(manifest, job.className);
232261
+ lines.push(`被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`);
232262
+ return textResult(lines.join(`
232263
+ `));
232264
+ }
231185
232265
  const providerIndex = module.providers.findIndex((provider) => provider.token === target || provider.useClass === target);
231186
232266
  if (providerIndex >= 0)
231187
232267
  return textResult(explainProvider(manifest, module, providerIndex));
@@ -231242,8 +232322,8 @@ async function runExportTools(args) {
231242
232322
  }
231243
232323
  const openaiPath = join12(outDir, "tool-definitions.openai.json");
231244
232324
  const mcpPath = join12(outDir, "tool-definitions.mcp.json");
231245
- await writeFile3(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
231246
- await writeFile3(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
232325
+ await writeFile4(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
232326
+ await writeFile4(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
231247
232327
  const summary = [
231248
232328
  `exported ${definitions.openai.length} tool(s):`,
231249
232329
  ` openai → ${openaiPath}`,
@@ -231255,10 +232335,37 @@ async function runExportTools(args) {
231255
232335
  `);
231256
232336
  return textResult(summary);
231257
232337
  }
232338
+ async function runAppTool(request) {
232339
+ switch (request.action) {
232340
+ case "init":
232341
+ return initProject(request);
232342
+ case "generate":
232343
+ return generateScaffold(request);
232344
+ case "compile":
232345
+ return runCompile(request);
232346
+ case "check":
232347
+ return runCheck(request);
232348
+ case "graph":
232349
+ return runGraph(request);
232350
+ case "explain":
232351
+ return runExplain(request);
232352
+ case "export-tools":
232353
+ return runExportTools(request);
232354
+ case "context":
232355
+ return runContext(request);
232356
+ case "doctor":
232357
+ return runDoctor(request);
232358
+ case "fix":
232359
+ return runFix(request);
232360
+ default:
232361
+ return textResult(`Unknown app action: ${String(request.action)}`, true);
232362
+ }
232363
+ }
231258
232364
  function registerAppTools(server2) {
231259
- server2.tool("app", "Local @supacloud/app framework commands: init, scaffold, compile, check, graph, explain and export-tools. Actions: init, generate, compile, check, graph, explain, export-tools", {
231260
- action: withDescription(stringEnum(["init", "generate", "compile", "check", "graph", "explain", "export-tools"]), "App action"),
231261
- kind: optional(stringEnum(["module", "command", "query", "controller"]), "[generate] Scaffold kind"),
232365
+ server2.tool("app", "Local @supacloud/app framework commands: init, scaffold, compile, check, graph, explain, export-tools, AI context/doctor and fix. Actions: init, generate, compile, check, graph, explain, export-tools, context, doctor, fix", {
232366
+ action: withDescription(stringEnum(["init", "generate", "compile", "check", "graph", "explain", "export-tools", "context", "doctor", "fix"]), "App action"),
232367
+ kind: optional(stringEnum(["module", "command", "query", "controller", "job", "contract"]), "[generate] Scaffold kind"),
232368
+ template: optional(stringEnum(["http", "command", "edge"]), "[init] Golden-path template (default: command)"),
231262
232369
  name: optional(Type.String(), "[init/generate] Project or object name"),
231263
232370
  module: optional(Type.String(), "[generate] Target feature module (required for command/query/controller)"),
231264
232371
  dir: optional(Type.String(), "[generate] Feature root directory (default: src/features)"),
@@ -231268,27 +232375,31 @@ function registerAppTools(server2) {
231268
232375
  out_dir: optional(Type.String(), "[compile/export-tools] Output directory (default: <root>/generated)"),
231269
232376
  strict: optional(Type.Boolean(), "[compile/check] Promote warnings to errors"),
231270
232377
  format: optional(stringEnum(["text", "json"]), "[graph/export-tools] Output format (default: text)"),
231271
- target: optional(Type.String(), "[explain] Provider class name / token name / command name")
231272
- }, async (request) => {
231273
- switch (request.action) {
231274
- case "init":
231275
- return initProject(request);
231276
- case "generate":
231277
- return generateScaffold(request);
231278
- case "compile":
231279
- return runCompile(request);
231280
- case "check":
231281
- return runCheck(request);
231282
- case "graph":
231283
- return runGraph(request);
231284
- case "explain":
231285
- return runExplain(request);
231286
- case "export-tools":
231287
- return runExportTools(request);
231288
- default:
231289
- return textResult(`Unknown app action: ${String(request.action)}`, true);
231290
- }
231291
- });
232378
+ target: optional(Type.String(), "[explain/context] Provider class name / token name / command name / job name / module name"),
232379
+ fix: optional(Type.String(), "[fix] Path to a DiagnosticFix JSON file produced by `doctor --format json`"),
232380
+ write: optional(Type.Boolean(), "[fix] Write the fix to disk (default: preview only)")
232381
+ }, runAppTool);
232382
+ }
232383
+ var APP_ALIAS_ACTIONS = ["generate", "compile", "check", "graph", "explain", "context", "doctor", "fix"];
232384
+ function registerAppAliases(server2) {
232385
+ const schema = {
232386
+ kind: optional(stringEnum(["module", "command", "query", "controller", "job", "contract"]), "[generate] Scaffold kind"),
232387
+ name: optional(Type.String(), "[generate] Object name"),
232388
+ module: optional(Type.String(), "[generate] Target feature module"),
232389
+ dir: optional(Type.String(), "[generate] Feature root directory (default: src/features)"),
232390
+ force: optional(Type.Boolean(), "[generate] Overwrite existing files"),
232391
+ root: optional(Type.String(), "Project directory containing supacloud.config.ts (default: current directory)"),
232392
+ include: optional(Type.String(), "[compile/check] Comma-separated glob patterns for source files"),
232393
+ out_dir: optional(Type.String(), "[compile/export-tools] Output directory (default: <root>/generated)"),
232394
+ strict: optional(Type.Boolean(), "[compile/check] Promote warnings to errors"),
232395
+ format: optional(stringEnum(["text", "json"]), "Output format (default: text)"),
232396
+ target: optional(Type.String(), "[explain/context] Provider class name / token name / command name / job name / module name"),
232397
+ fix: optional(Type.String(), "[fix] Path to a DiagnosticFix JSON file produced by `doctor --format json`"),
232398
+ write: optional(Type.Boolean(), "[fix] Write the fix to disk (default: preview only)")
232399
+ };
232400
+ for (const action of APP_ALIAS_ACTIONS) {
232401
+ server2.tool(action, `Top-level alias of \`app ${action}\`.`, schema, (request) => runAppTool({ ...request, action }));
232402
+ }
231292
232403
  }
231293
232404
 
231294
232405
  // src/shared/tools/db-governance-tools.ts
@@ -231903,7 +233014,7 @@ function registerDbGovernanceTools(server2, options = {}) {
231903
233014
  }
231904
233015
 
231905
233016
  // src/shared/tools/scheduled-function-tools.ts
231906
- import { randomUUID } from "node:crypto";
233017
+ import { randomUUID as randomUUID2 } from "node:crypto";
231907
233018
  import { readFileSync as readFileSync8, statSync as statSync6 } from "node:fs";
231908
233019
  import { resolve as resolve13 } from "node:path";
231909
233020
  import { isDeepStrictEqual } from "node:util";
@@ -232213,7 +233324,7 @@ function readOnlyResult2() {
232213
233324
  }
232214
233325
  function createRequest(args, environment) {
232215
233326
  return {
232216
- request_id: randomUUID(),
233327
+ request_id: randomUUID2(),
232217
233328
  name: requiredName(args, "create"),
232218
233329
  slug: requiredSlug(args, "create"),
232219
233330
  cron: requiredCron(args, "create"),
@@ -232275,7 +233386,7 @@ function updateRequest(args, environment) {
232275
233386
  throw new Error("Scheduled Function update requires at least one field");
232276
233387
  }
232277
233388
  return {
232278
- request_id: randomUUID(),
233389
+ request_id: randomUUID2(),
232279
233390
  expected_updated_at: expectedUpdatedAt,
232280
233391
  ...mutationFields
232281
233392
  };
@@ -232573,7 +233684,7 @@ var MUTATION_TOOL_SCHEMA = {
232573
233684
  import { execFileSync } from "node:child_process";
232574
233685
  import { createHash as createHash7 } from "node:crypto";
232575
233686
  import { existsSync as existsSync12, mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync3 } from "node:fs";
232576
- import { dirname as dirname7, join as join14, relative as relative6, resolve as resolve15 } from "node:path";
233687
+ import { dirname as dirname9, join as join14, relative as relative8, resolve as resolve15 } from "node:path";
232577
233688
  var SAFE_PROJECT_REF = /^[A-Za-z0-9_-]{1,64}$/;
232578
233689
  var BACKUP_ID = /^logical-full_[A-Za-z0-9_-]{1,64}_[a-f0-9]{32}$/;
232579
233690
  var SHA256 = /^[a-f0-9]{64}$/;
@@ -232967,7 +234078,7 @@ function handleScopeRebind(args) {
232967
234078
  writeFileSync3(filePath, formatted, "utf8");
232968
234079
  }
232969
234080
  scopes.push({
232970
- file: relative6(cwd, filePath),
234081
+ file: relative8(cwd, filePath),
232971
234082
  task_id: typeof parsed.taskId === "string" ? parsed.taskId : "",
232972
234083
  target_project_ref: typeof parsed.targetProjectRef === "string" ? parsed.targetProjectRef : "",
232973
234084
  previous_base_commit: previousBaseCommit,
@@ -233021,7 +234132,7 @@ function handleScopeInspect(args) {
233021
234132
  const scopeSha256 = genericScopedReleaseScopeSha256(parsed);
233022
234133
  const git = gitCommitInfo(cwd);
233023
234134
  return releaseControlSuccess("release.scope_inspect", {
233024
- file: relative6(cwd, filePath),
234135
+ file: relative8(cwd, filePath),
233025
234136
  scope: {
233026
234137
  task_id: parsed.taskId,
233027
234138
  target_project_ref: parsed.targetProjectRef,
@@ -233071,7 +234182,7 @@ function handleScopeCreate(args, fallbackRef) {
233071
234182
  }
233072
234183
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
233073
234184
  const filePath = resolve15(cwd, args.file.trim());
233074
- mkdirSync4(dirname7(filePath), { recursive: true });
234185
+ mkdirSync4(dirname9(filePath), { recursive: true });
233075
234186
  const scope = {
233076
234187
  baseCommit: targetBaseCommit,
233077
234188
  excludedFunctions: parseCommaList(args.excluded_functions),
@@ -233087,7 +234198,7 @@ function handleScopeCreate(args, fallbackRef) {
233087
234198
  `;
233088
234199
  writeFileSync3(filePath, formatted, "utf8");
233089
234200
  return releaseControlSuccess("release.scope_create", {
233090
- file: relative6(cwd, filePath),
234201
+ file: relative8(cwd, filePath),
233091
234202
  task_id: scope.taskId,
233092
234203
  target_project_ref: projectRef,
233093
234204
  base_commit: targetBaseCommit,
@@ -233292,10 +234403,10 @@ function registerReleaseTools(server2, http, options = {}) {
233292
234403
  }
233293
234404
 
233294
234405
  // src/shared/tools/deploy-tools.ts
233295
- import { access as access3, lstat as lstat2, mkdtemp, opendir, readFile as readFile4, rm, writeFile as writeFile4 } from "node:fs/promises";
234406
+ import { access as access3, lstat as lstat3, mkdtemp, opendir, readFile as readFile4, rm, writeFile as writeFile5 } from "node:fs/promises";
233296
234407
  import { createHash as createHash8 } from "node:crypto";
233297
234408
  import { tmpdir as tmpdir2 } from "node:os";
233298
- import { basename as basename7, dirname as dirname8, join as join15, relative as relative7, resolve as resolve16, sep as sep5 } from "node:path";
234409
+ import { basename as basename8, dirname as dirname10, join as join15, relative as relative9, resolve as resolve16, sep as sep5 } from "node:path";
233299
234410
  import { spawn as spawn3 } from "node:child_process";
233300
234411
 
233301
234412
  // node_modules/fflate/esm/index.mjs
@@ -233991,7 +235102,7 @@ async function findDeployConfigRoot(startDirectory) {
233991
235102
  while (true) {
233992
235103
  if (await pathExists(join15(directory, "supacloud.json")))
233993
235104
  return directory;
233994
- const parent = dirname8(directory);
235105
+ const parent = dirname10(directory);
233995
235106
  if (parent === directory)
233996
235107
  return resolve16(startDirectory);
233997
235108
  directory = parent;
@@ -234080,7 +235191,7 @@ async function defaultBuildCommand(projectDirectory, configRoot) {
234080
235191
  return "yarn build";
234081
235192
  if (directory === configRoot)
234082
235193
  break;
234083
- const parent = dirname8(directory);
235194
+ const parent = dirname10(directory);
234084
235195
  if (parent === directory || !directory.startsWith(`${configRoot}${sep5}`))
234085
235196
  break;
234086
235197
  directory = parent;
@@ -234185,7 +235296,7 @@ async function runBuild(command, cwd) {
234185
235296
  });
234186
235297
  }
234187
235298
  async function collectArchiveFiles(root) {
234188
- const rootStat = await lstat2(root).catch(() => null);
235299
+ const rootStat = await lstat3(root).catch(() => null);
234189
235300
  if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) {
234190
235301
  throw new Error(`Frontend output directory does not exist or is not a regular directory: ${root}`);
234191
235302
  }
@@ -234197,7 +235308,7 @@ async function collectArchiveFiles(root) {
234197
235308
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
234198
235309
  for (const entry of entries) {
234199
235310
  const path = join15(directory, entry.name);
234200
- const stats = await lstat2(path);
235311
+ const stats = await lstat3(path);
234201
235312
  if (stats.isSymbolicLink())
234202
235313
  throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
234203
235314
  if (stats.isDirectory())
@@ -234218,7 +235329,7 @@ async function collectArchiveFiles(root) {
234218
235329
  bytes += data.byteLength;
234219
235330
  if (bytes > MAX_SOURCE_BYTES)
234220
235331
  throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
234221
- const archivePath = relative7(root, path).split(sep5).join("/");
235332
+ const archivePath = relative9(root, path).split(sep5).join("/");
234222
235333
  files[archivePath] = [data, { mtime: FIXED_ZIP_MTIME }];
234223
235334
  }
234224
235335
  return { files, bytes, count: paths.length };
@@ -234226,10 +235337,10 @@ async function collectArchiveFiles(root) {
234226
235337
  async function createFrontendArchive(outputDirectory) {
234227
235338
  const collected = await collectArchiveFiles(outputDirectory);
234228
235339
  const temporaryDirectory = await mkdtemp(join15(tmpdir2(), "supacloud-deploy-"));
234229
- const archivePath = join15(temporaryDirectory, `${basename7(outputDirectory)}.zip`);
235340
+ const archivePath = join15(temporaryDirectory, `${basename8(outputDirectory)}.zip`);
234230
235341
  try {
234231
235342
  const archiveBytes = zipSync(collected.files, { level: 6, mtime: FIXED_ZIP_MTIME });
234232
- await writeFile4(archivePath, archiveBytes);
235343
+ await writeFile5(archivePath, archiveBytes);
234233
235344
  const sha256 = createHash8("sha256").update(archiveBytes).digest("hex");
234234
235345
  return {
234235
235346
  archivePath,
@@ -234284,7 +235395,7 @@ function registerDeployTools(server2, http, options = {}) {
234284
235395
  const config = await readDeployConfig(configRoot);
234285
235396
  const target = selectTarget(configRoot, invocationDirectory, config, String(args.target || "").trim() || undefined);
234286
235397
  const projectDirectory = target.root;
234287
- const targetState = await lstat2(projectDirectory).catch(() => null);
235398
+ const targetState = await lstat3(projectDirectory).catch(() => null);
234288
235399
  if (!targetState?.isDirectory() || targetState.isSymbolicLink()) {
234289
235400
  throw new Error(`Deploy target '${target.name}' root is not a regular directory: ${projectDirectory}`);
234290
235401
  }
@@ -234390,7 +235501,7 @@ function registerDeployTools(server2, http, options = {}) {
234390
235501
  } else {
234391
235502
  report("build", "skipped");
234392
235503
  }
234393
- report("package", relative7(projectDirectory, outputDirectory) || ".");
235504
+ report("package", relative9(projectDirectory, outputDirectory) || ".");
234394
235505
  const archive = await createFrontendArchive(outputDirectory);
234395
235506
  try {
234396
235507
  const inventory = payload(await listFrontendReleases(http, projectRef, selected.id, undefined, 100));
@@ -234451,7 +235562,7 @@ function registerDeployTools(server2, http, options = {}) {
234451
235562
  import { spawn as spawn4 } from "node:child_process";
234452
235563
  import { existsSync as existsSync13 } from "node:fs";
234453
235564
  import { readFile as readFile5 } from "node:fs/promises";
234454
- import { readdir as readdir2 } from "node:fs/promises";
235565
+ import { readdir as readdir3 } from "node:fs/promises";
234455
235566
  import { createHash as createHash9 } from "node:crypto";
234456
235567
  import { join as join16, resolve as resolve17 } from "node:path";
234457
235568
  var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
@@ -234544,7 +235655,7 @@ async function readDevConfig(root) {
234544
235655
  async function sourceFingerprint(root) {
234545
235656
  const files = [];
234546
235657
  const visit = async (directory) => {
234547
- const entries = await readdir2(directory, { withFileTypes: true });
235658
+ const entries = await readdir3(directory, { withFileTypes: true });
234548
235659
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
234549
235660
  const path = join16(directory, entry.name);
234550
235661
  if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
@@ -234721,7 +235832,7 @@ function registerRemoteDevTools(server2, options = {}) {
234721
235832
  // package.json
234722
235833
  var package_default4 = {
234723
235834
  name: "@supacloud/cli",
234724
- version: "0.55.1",
235835
+ version: "0.56.0",
234725
235836
  description: "Project-scoped CLI for SupaCloud users",
234726
235837
  type: "module",
234727
235838
  main: "./dist/index.js",
@@ -234754,7 +235865,7 @@ var package_default4 = {
234754
235865
  },
234755
235866
  dependencies: {
234756
235867
  "@sinclair/typebox": "^0.34.52",
234757
- "@supacloud/compiler": "^0.23.0",
235868
+ "@supacloud/compiler": "^0.24.0",
234758
235869
  "@supacloud/db": "^0.2.0",
234759
235870
  fflate: "^0.8.3"
234760
235871
  },
@@ -235011,12 +236122,27 @@ EXAMPLES
235011
236122
  ${preferredCommand} ai show_skill
235012
236123
  ${preferredCommand} ai install_skill --dry_run
235013
236124
  ${preferredCommand} app init --name my-service
236125
+ ${preferredCommand} app init --name my-api --template http
236126
+ ${preferredCommand} app init --name my-worker --template edge
235014
236127
  ${preferredCommand} app generate --kind module --name billing
235015
236128
  ${preferredCommand} app generate --kind command --module billing --name issue-invoice
236129
+ ${preferredCommand} app generate --kind job --module billing --name sync-orders
236130
+ ${preferredCommand} app generate --kind contract --module billing --name issue-invoice
235016
236131
  ${preferredCommand} app compile --root .
235017
236132
  ${preferredCommand} app check --root . --strict
235018
236133
  ${preferredCommand} app graph --root . --format json
235019
236134
  ${preferredCommand} app explain --target CaseService
236135
+ ${preferredCommand} app context --root . --format json
236136
+ ${preferredCommand} app context --root . --target CaseModule --format json
236137
+ ${preferredCommand} app doctor --root .
236138
+ ${preferredCommand} app fix --root . --fix fix.json --write
236139
+ ${preferredCommand} generate --kind module --name billing
236140
+ ${preferredCommand} generate --kind job --module billing --name sync-orders
236141
+ ${preferredCommand} generate --kind contract --module billing --name issue-invoice
236142
+ ${preferredCommand} check --root . --strict
236143
+ ${preferredCommand} context --format json
236144
+ ${preferredCommand} context --target CaseModule --format json
236145
+ ${preferredCommand} doctor
235020
236146
  ${preferredCommand} db lint --root . --module_file db/modules.ts
235021
236147
  ${preferredCommand} db explain --target public.cases --module_file db/modules.ts
235022
236148
  ${preferredCommand} db module_check --module_file db/modules.ts --database_url "postgresql://..."
@@ -235071,6 +236197,7 @@ function createCliTools(context, confirmProduction) {
235071
236197
  Object.assign(tools, captureTools((server2) => registerLiteCliTools(server2)));
235072
236198
  Object.assign(tools, captureTools((server2) => registerAiTools(server2)));
235073
236199
  Object.assign(tools, captureTools((server2) => registerAppTools(server2)));
236200
+ Object.assign(tools, captureTools((server2) => registerAppAliases(server2)));
235074
236201
  Object.assign(tools, captureTools((server2) => registerDbGovernanceTools(server2)));
235075
236202
  const registerContextAwareHelp = () => {
235076
236203
  tools.project = {