@rebasepro/cli 0.33.2 → 0.34.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 (95) hide show
  1. package/dist/{agent-setup-Cg_zBWoW.js → agent-setup-CGeAuP0Q.js} +2 -2
  2. package/dist/{agent-setup-Cg_zBWoW.js.map → agent-setup-CGeAuP0Q.js.map} +1 -1
  3. package/dist/{api-keys-fPQ55DCm.js → api-keys-DaWN8dyI.js} +3 -3
  4. package/dist/{api-keys-fPQ55DCm.js.map → api-keys-DaWN8dyI.js.map} +1 -1
  5. package/dist/{api-TbmW33D7.js → api-zx1wSK5a.js} +2 -2
  6. package/dist/{api-TbmW33D7.js.map → api-zx1wSK5a.js.map} +1 -1
  7. package/dist/{apps-DBTRoOeP.js → apps-D6vtDrkJ.js} +3 -3
  8. package/dist/{apps-DBTRoOeP.js.map → apps-D6vtDrkJ.js.map} +1 -1
  9. package/dist/{auth-BpyYLEFY.js → auth-DY7kU0z-.js} +8 -8
  10. package/dist/{auth-BpyYLEFY.js.map → auth-DY7kU0z-.js.map} +1 -1
  11. package/dist/{auth-session-B6aT0Dyj.js → auth-session-DCG96UGH.js} +4 -4
  12. package/dist/{auth-session-B6aT0Dyj.js.map → auth-session-DCG96UGH.js.map} +1 -1
  13. package/dist/{build-E5hfEWKj.js → build-D0egCUfU.js} +4 -4
  14. package/dist/{build-E5hfEWKj.js.map → build-D0egCUfU.js.map} +1 -1
  15. package/dist/{bundle-CIiKGrte.js → bundle-DhdhtD8K.js} +3 -3
  16. package/dist/{bundle-CIiKGrte.js.map → bundle-DhdhtD8K.js.map} +1 -1
  17. package/dist/{cloud-DNJyUU0T.js → cloud-DOR7bxDw.js} +218 -27
  18. package/dist/cloud-DOR7bxDw.js.map +1 -0
  19. package/dist/{command-Bks5xkrQ.js → command-BzSP5gBh.js} +2 -2
  20. package/dist/{command-Bks5xkrQ.js.map → command-BzSP5gBh.js.map} +1 -1
  21. package/dist/commands/cloud/db-connect.d.ts +31 -1
  22. package/dist/commands/cloud/db-query.d.ts +16 -0
  23. package/dist/commands/cloud/index.d.ts +1 -0
  24. package/dist/commands/cloud/resources.d.ts +19 -1
  25. package/dist/commands/dev.d.ts +15 -0
  26. package/dist/commands/users.d.ts +1 -0
  27. package/dist/{context-BOMEoKxn.js → context-xt20FMFA.js} +5 -1
  28. package/dist/{context-BOMEoKxn.js.map → context-xt20FMFA.js.map} +1 -1
  29. package/dist/{cron-CpUsQ739.js → cron-BGkXIB1N.js} +4 -4
  30. package/dist/{cron-CpUsQ739.js.map → cron-BGkXIB1N.js.map} +1 -1
  31. package/dist/{cron-ZRXsla0v.js → cron-CJ6Xk42E.js} +3 -3
  32. package/dist/{cron-ZRXsla0v.js.map → cron-CJ6Xk42E.js.map} +1 -1
  33. package/dist/{data-BJ9AZFUC.js → data-BpkvtCUe.js} +3 -3
  34. package/dist/{data-BJ9AZFUC.js.map → data-BpkvtCUe.js.map} +1 -1
  35. package/dist/{debug-nNbbxAeo.js → debug-C7Ss34XB.js} +2 -2
  36. package/dist/{debug-nNbbxAeo.js.map → debug-C7Ss34XB.js.map} +1 -1
  37. package/dist/{derive-Mky_u59_.js → derive-ChP6vgfi.js} +2 -2
  38. package/dist/{derive-Mky_u59_.js.map → derive-ChP6vgfi.js.map} +1 -1
  39. package/dist/{dev-bj6dEeSQ.js → dev-C7n36E6f.js} +23 -2
  40. package/dist/dev-C7n36E6f.js.map +1 -0
  41. package/dist/{doctor-FaBObSlb.js → doctor-D0o54XSQ.js} +2 -2
  42. package/dist/{doctor-FaBObSlb.js.map → doctor-D0o54XSQ.js.map} +1 -1
  43. package/dist/{fold-static-2t3UUX4z.js → fold-static-DTpaqbB0.js} +2 -2
  44. package/dist/{fold-static-2t3UUX4z.js.map → fold-static-DTpaqbB0.js.map} +1 -1
  45. package/dist/{function-portability-BIvlvR9q.js → function-portability-Dppl6uqg.js} +24 -5
  46. package/dist/{function-portability-BIvlvR9q.js.map → function-portability-Dppl6uqg.js.map} +1 -1
  47. package/dist/function-portability.d.ts +9 -0
  48. package/dist/{functions-B4JR6EZL.js → functions-DLuuldt2.js} +4 -4
  49. package/dist/{functions-B4JR6EZL.js.map → functions-DLuuldt2.js.map} +1 -1
  50. package/dist/{generate_sdk-ByD-gTsK.js → generate_sdk-UT1lwwRT.js} +2 -2
  51. package/dist/{generate_sdk-ByD-gTsK.js.map → generate_sdk-UT1lwwRT.js.map} +1 -1
  52. package/dist/index.es.js +39 -39
  53. package/dist/{init-DHCe5mJ5.js → init-u5Xmr1Ct.js} +4 -4
  54. package/dist/{init-DHCe5mJ5.js.map → init-u5Xmr1Ct.js.map} +1 -1
  55. package/dist/{logs-DpuMukJe.js → logs-DBYRSs6W.js} +4 -4
  56. package/dist/{logs-DpuMukJe.js.map → logs-DBYRSs6W.js.map} +1 -1
  57. package/dist/{migrate-CSY9ZDKy.js → migrate-Cw1FkvUK.js} +3 -3
  58. package/dist/{migrate-CSY9ZDKy.js.map → migrate-Cw1FkvUK.js.map} +1 -1
  59. package/dist/{normalize-imports-P86NVfpo.js → normalize-imports-E4yA1HfW.js} +2 -2
  60. package/dist/{normalize-imports-P86NVfpo.js.map → normalize-imports-E4yA1HfW.js.map} +1 -1
  61. package/dist/{project-command-Cl9EZzjr.js → project-command-7EGMemEy.js} +5 -5
  62. package/dist/{project-command-Cl9EZzjr.js.map → project-command-7EGMemEy.js.map} +1 -1
  63. package/dist/{resources-Db3USuPO.js → resources-CE6BeL94.js} +2 -2
  64. package/dist/{resources-Db3USuPO.js.map → resources-CE6BeL94.js.map} +1 -1
  65. package/dist/{rls-BxrQ0P50.js → rls-BxWLfEKl.js} +3 -3
  66. package/dist/{rls-BxrQ0P50.js.map → rls-BxWLfEKl.js.map} +1 -1
  67. package/dist/{schema-_FzZEoB8.js → schema-D8xFSBbN.js} +7 -6
  68. package/dist/{schema-_FzZEoB8.js.map → schema-D8xFSBbN.js.map} +1 -1
  69. package/dist/schema-reconcile-D_wvZY91.js +2 -0
  70. package/dist/{schema-show-h72UJ9zH.js → schema-show-C7bY7SgE.js} +3 -3
  71. package/dist/{schema-show-h72UJ9zH.js.map → schema-show-C7bY7SgE.js.map} +1 -1
  72. package/dist/{skills-DQ2bZGkj.js → skills-C8WdRTFg.js} +4 -4
  73. package/dist/{skills-DQ2bZGkj.js.map → skills-C8WdRTFg.js.map} +1 -1
  74. package/dist/{start-Cjx4W0bJ.js → start-CN_9C205.js} +2 -2
  75. package/dist/{start-Cjx4W0bJ.js.map → start-CN_9C205.js.map} +1 -1
  76. package/dist/{status-CDBk25VO.js → status-HWlZbY1E.js} +2 -2
  77. package/dist/{status-CDBk25VO.js.map → status-HWlZbY1E.js.map} +1 -1
  78. package/dist/{storage-Clc8dLG8.js → storage-DBE8lgH-.js} +9 -9
  79. package/dist/{storage-Clc8dLG8.js.map → storage-DBE8lgH-.js.map} +1 -1
  80. package/dist/{storage-objects-CfRKlTDe.js → storage-objects-ljDmtuH7.js} +3 -3
  81. package/dist/{storage-objects-CfRKlTDe.js.map → storage-objects-ljDmtuH7.js.map} +1 -1
  82. package/dist/{users-5PkqBY6R.js → users-DrJEtL9k.js} +9 -6
  83. package/dist/users-DrJEtL9k.js.map +1 -0
  84. package/package.json +10 -10
  85. package/templates/template/.cursorrules +2 -1
  86. package/templates/template/.github/copilot-instructions.md +2 -1
  87. package/templates/template/.windsurfrules +2 -1
  88. package/templates/template/AGENTS.md +2 -1
  89. package/templates/template/CLAUDE.md +2 -1
  90. package/templates/template/ai-instructions.md +5 -2
  91. package/templates/template/frontend/src/index.css +13 -0
  92. package/dist/cloud-DNJyUU0T.js.map +0 -1
  93. package/dist/dev-bj6dEeSQ.js.map +0 -1
  94. package/dist/schema-reconcile-DV14XY4o.js +0 -2
  95. package/dist/users-5PkqBY6R.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"derive-Mky_u59_.js","names":[],"sources":["../src/resources/derive.ts"],"sourcesContent":["/**\n * Deriving the resource graph from a project's backend, and recording it.\n *\n * ## Why the graph is derived rather than authored\n *\n * A resource is declared once, in code. But a host has to know what a project\n * needs *before* it runs anything — that is how a console can say \"this project\n * wants a `media` bucket and has none\" on a first deploy, and it is the reason\n * storage topology used to be hand-written into `rebase.json` in the first\n * place. A `custom` runtime makes it sharper still: it emits no bundle\n * manifest, so without a committed artifact there is nothing to read at all.\n *\n * So the graph is derived by evaluating `backend/resources.ts` and the tables\n * in `backend/schema`, and written to\n * `rebase.resources.json`, which is committed. Same arrangement as\n * `schema.generated.ts`: authored in one place, generated into another, and a\n * gate fails if the two disagree. The file is an *output*, never an input —\n * which is what removes the old silent merge, because there is no longer a\n * second declaration for anything to be merged with.\n *\n * ## Why evaluation rather than static analysis\n *\n * Encore parses the source and builds the graph from the AST. Rebase already\n * evaluates `backend/schema` to load the tables, and evaluation is exact where a parser\n * is approximate — a resource declared in a loop, or behind a helper, is\n * invisible to a parser and obvious to an interpreter. The cost is running user\n * code at build time, which this project already accepts everywhere else.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport {\n DEFAULT_RESOURCE_KEY,\n buildResourceGraph,\n declareFunction,\n declaredQueueConsumers,\n declaredResources,\n declaredSubscriptions,\n findEnvSuffixCollision,\n isResourceHandle,\n resetDeclaredQueueConsumers,\n resetDeclaredResources,\n resetDeclaredSubscriptions,\n resourceId,\n type ColumnStorage,\n type JsonShape,\n type RebaseBackendAppConfig,\n type ResourceDeclaration,\n type ResourceGraph,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { analyseFunctionsDirectory } from \"../function-portability\";\nimport { resolveBackendPaths } from \"../manifest\";\nimport { createSchemaModuleImporter } from \"../utils/import-schema-module\";\nimport type { ModuleAliases } from \"../utils/project-schema\";\nimport type { SchemaModuleImporter } from \"@rebasepro/server\";\nimport { cliVersion } from \"../utils/version\";\n\n/** The committed, generated record of what a project needs. */\nexport const RESOURCE_GRAPH_FILENAME = \"rebase.resources.json\";\n\n/** A problem found while deriving, reported with the rest rather than thrown one at a time. */\nexport interface ResourceIssue {\n path: string;\n message: string;\n}\n\n/**\n * Which `@rebasepro/*` package a module error is about, when it is about one.\n *\n * Both directions of a version skew arrive as an error about the *user's* file:\n * `resources.ts The requested module '@rebasepro/types' does not provide an\n * export named 'queue'`. Nothing in that says which copy of `@rebasepro/types`\n * is installed, what version this CLI is, or that the two disagree — so the\n * reader goes looking for a typo in code they just copied out of the docs.\n *\n * Two shapes, because the two directions produce different errors: a named\n * export the installed copy is too old for, and a package the installed tree\n * does not have at all.\n */\nconst NAMED_EXPORT_MISSING = /does not provide an export named ['\"]([^'\"]+)['\"]/;\nconst SPECIFIER = /(@rebasepro\\/[a-z0-9-]+)/;\n\n/** The version of a package as resolved from the project, or null. */\nfunction installedVersion(specifier: string, from: string): string | null {\n try {\n const require = createRequire(path.join(from, \"noop.js\"));\n const manifest = require.resolve(`${specifier}/package.json`);\n const version: unknown = JSON.parse(fs.readFileSync(manifest, \"utf-8\")).version;\n return typeof version === \"string\" ? version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The message an issue carries, with the skew named when there is one.\n *\n * `main` runs 497 commits ahead of npm `latest` and the docs site publishes from\n * `main`, so the shape this exists for is routine: a scaffold pinned to the\n * published version, backend code written against today's documentation, and an\n * error about the project's file. The fix is one command and the error named none\n * of it — the same failure as `404 No PUT route on collection 'projects'`, one\n * layer down.\n *\n * Says nothing extra when the two versions agree, or when either is unreadable:\n * a sentence naming one version twice is worse than no sentence.\n */\nexport function describeIssue(err: unknown, projectRoot: string, ownVersion = cliVersion()): string {\n const message = err instanceof Error ? err.message : String(err);\n const code = (err as { code?: unknown } | null)?.code;\n const missingExport = NAMED_EXPORT_MISSING.exec(message);\n const isSkewShaped = missingExport !== null || code === \"ERR_MODULE_NOT_FOUND\";\n if (!isSkewShaped) return message;\n\n const specifier = SPECIFIER.exec(message)?.[1];\n if (!specifier) return message;\n\n // One line, not two: every caller renders an issue as `path message` on a\n // single row, so a newline here would land the useful half unindented under\n // the file name.\n const lead = /[.!?]$/.test(message.trim()) ? message.trim() : `${message.trim()}.`;\n\n const installed = installedVersion(specifier, projectRoot);\n if (installed === null) {\n return `${lead} ${specifier} is not installed in this project; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`;\n }\n if (ownVersion === \"unknown\" || installed === ownVersion) return message;\n\n // Which side to move is the question the reader actually has, and it has a\n // right answer: the CLI is what evaluates this file, so the packages follow\n // it — unless the CLI is the older one, in which case following it would\n // move the project backwards.\n const cliIsNewer = compareVersions(ownVersion, installed) > 0;\n return cliIsNewer\n ? `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`\n : `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}, which is older. `\n + `Update the CLI to ${installed}, or pin ${specifier} back to ${ownVersion}`;\n}\n\n/** -1 / 0 / 1 on the numeric parts, ignoring any prerelease tail. */\nfunction compareVersions(a: string, b: string): number {\n const parts = (v: string): number[] => v.split(\"-\")[0].split(\".\").map(n => Number(n) || 0);\n const [x, y] = [parts(a), parts(b)];\n for (let i = 0; i < 3; i++) {\n if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0) ? -1 : 1;\n }\n return 0;\n}\n\n/** The spellings of the resources module, tried in order, after its path without extension. */\nconst RESOURCE_MODULE_SUFFIXES = [\".ts\", \".mts\", \".js\", \".mjs\", \"/index.ts\", \"/index.js\"];\n\n/** The resources module under `base` (a path without extension), or undefined. */\nfunction findResourcesModule(base: string): string | undefined {\n return RESOURCE_MODULE_SUFFIXES.map(suffix => `${base}${suffix}`)\n .find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile());\n}\n\nexport interface DeriveOptions {\n /** The project root, absolute: what the importer is rooted at and every recorded path is relative to. */\n projectRoot: string;\n /**\n * The resources module, absolute, without or with its extension:\n * `<root>/backend/resources`. Its `database()` / `bucket()` / `topic()` /\n * `queue()` declarations are the graph's nodes.\n */\n resources?: string;\n /**\n * The schema directory, absolute. Its tables are evaluated too: a table\n * reaches its database and every bucket a storage column stores into, and a\n * bucket may be declared beside the table that stores into it.\n */\n schemaDir?: string;\n /**\n * Absolute path to the crons directory. Each file is evaluated through the\n * same loader the runtime uses, which declares the cron under the same id\n * the scheduler runs it as. Absent, or missing on disk: no crons.\n */\n cronsDir?: string;\n /**\n * Absolute path to the functions directory. Read statically — the\n * bundler's portability analysis — never evaluated: a function's module\n * scope belongs to a running backend, not a build.\n */\n functionsDir?: string;\n /** Module specifiers mapped to files when importing (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n}\n\n/** The derive options for a backend app, from its manifest entry. */\nexport function deriveOptionsFor(projectRoot: string, app: RebaseBackendAppConfig): DeriveOptions {\n const paths = resolveBackendPaths(app, projectRoot);\n return {\n projectRoot,\n resources: path.join(projectRoot, paths.resources).replace(/\\.[mc]?[jt]s$/, \"\"),\n schemaDir: path.join(projectRoot, paths.tables),\n cronsDir: path.join(projectRoot, paths.crons),\n functionsDir: path.join(projectRoot, paths.functions)\n };\n}\n\n/** Every storage setting in a JSON shape, with its dotted path below the column. */\nfunction jsonStorage(shape: JsonShape, prefix: string): Array<[string, ColumnStorage]> {\n switch (shape.kind) {\n case \"string\":\n return shape.storage ? [[prefix, shape.storage]] : [];\n case \"object\":\n return Object.entries(shape.fields).flatMap(([name, field]) => jsonStorage(field, `${prefix}.${name}`));\n case \"array\":\n return jsonStorage(shape.of, prefix);\n case \"oneOf\":\n return Object.entries(shape.variants).flatMap(([name, variant]) => jsonStorage(variant, `${prefix}.${name}`));\n default:\n return [];\n }\n}\n\n/**\n * Every storage setting a table's columns carry, keyed by the dotted path to\n * it: a storage column, the items of a storage array, a file inside a JSON\n * document.\n */\nfunction tableStorage(table: TableDescriptor): Array<[string, ColumnStorage]> {\n return table.columns.flatMap((column): Array<[string, ColumnStorage]> => [\n ...(column.storage ? [[column.key, column.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.element?.storage ? [[column.key, column.element.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.json ? jsonStorage(column.json, column.key) : [])\n ]);\n}\n\n/**\n * The resources a table reaches: its database, and every bucket a storage\n * column stores into. Only resources the graph declares get an edge — the\n * implicit default database is not in the graph, so a table that names no\n * `database` records nothing.\n *\n * The ids are `table:<slug>` and `column:<slug>.<path>`; a host's topology\n * view parses them.\n */\nfunction tableEdges(table: TableDescriptor, declared: Set<string>): Array<[string, string]> {\n const edges: Array<[string, string]> = [];\n const databaseId = resourceId(\"database\", table.database ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(databaseId)) edges.push([databaseId, `table:${table.slug}`]);\n for (const [where, storage] of tableStorage(table)) {\n const bucketId = resourceId(\"bucket\", storage.source ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(bucketId)) edges.push([bucketId, `column:${table.slug}.${where}`]);\n }\n return edges;\n}\n\n/**\n * A cron file that would not import, said in terms somebody can act on.\n *\n * The graph is derived by evaluating each cron module, in a process with none\n * of the deployment's environment — so a cron that reaches a module validating\n * `DATABASE_URL` at import fails here and works perfectly at boot. The raw\n * message is a Zod error about a variable, which reads as \"the environment is\n * wrong\" when the environment is not the point.\n */\nfunction cronLoadIssue(problem: string): string {\n return `${summariseCronProblem(problem)}\\n` +\n \" `rebase resources` evaluates each cron file to read its schedule, and it is a build \" +\n \"step: no .env, no secrets. Move work that needs the deployment's environment inside the \" +\n \"handler — `const { x } = await import(\\\"…\\\")` — so the module scope imports nothing that \" +\n \"reads configuration.\";\n}\n\n/**\n * The cron loader's `<file> (threw: <message>)`, as one line.\n *\n * The message is whatever the module threw, and the common case is a schema\n * validator: `loadEnv()` at module scope with no `.env` present throws a\n * `ZodError`, whose `.message` is the JSON array of its issues. That arrived\n * here verbatim — ten lines of `{ \"expected\": \"string\", \"code\":\n * \"invalid_type\", … }` — with the sentence that says what to do underneath it,\n * so the reader met \"Invalid input: expected string, received undefined\" twice\n * before reaching the explanation.\n *\n * A validator's own sentences are the useful half of that object, so they are\n * kept and the serialisation is dropped.\n */\nfunction summariseCronProblem(problem: string): string {\n const match = problem.match(/^(.*) \\(threw: ([\\s\\S]*)\\)$/);\n if (!match) return problem.split(\"\\n\")[0];\n const [, file, thrown] = match;\n return `${file}: ${summariseThrownMessage(thrown)}`;\n}\n\n/** One sentence out of a thrown message, whatever shape it arrived in. */\nfunction summariseThrownMessage(message: string): string {\n const trimmed = message.trim();\n if (trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n const issues = Array.isArray(parsed) ? parsed : [parsed];\n const sentences = [...new Set(\n issues\n .map(issue => (issue as { message?: unknown } | null)?.message)\n .filter((m): m is string => typeof m === \"string\" && m.length > 0)\n )];\n if (sentences.length > 0) return sentences.join(\"; \");\n } catch {\n // Not JSON after all — fall through to the first line.\n }\n }\n return trimmed.split(\"\\n\")[0];\n}\n\n/**\n * Evaluate a project's resources and tables and return the graph they declare.\n *\n * Clears any previously registered declarations first, so deriving twice in one\n * process — a watch mode, a test — describes the project rather than the union\n * of every project seen so far.\n */\nexport async function deriveResourceGraph(options: DeriveOptions): Promise<{ graph: ResourceGraph; issues: ResourceIssue[] }> {\n const { projectRoot, cronsDir, functionsDir } = options;\n // One importer for everything evaluated here: the resources module, the\n // tables that import its handles and the crons see one copy of each module,\n // so a handle a table imports is the handle the graph declared. A new\n // importer reads every file as it is now, so deriving again in one process\n // evaluates the declarations again. Created on first use: a project with\n // nothing to evaluate pays nothing for it.\n let importer: SchemaModuleImporter | undefined;\n const importModule: SchemaModuleImporter = async (file) => {\n importer ??= await createSchemaModuleImporter(projectRoot, options.moduleAliases);\n return importer(file);\n };\n\n // All three registries, and the side lists are the easy ones to forget:\n // resetting only the resources leaves one project's handlers attached\n // while its topics are gone — every one of them then reads as orphaned\n // against the *next* project. Caught by deriving twice in one process,\n // which is what a watch mode does.\n resetDeclaredResources();\n resetDeclaredSubscriptions();\n resetDeclaredQueueConsumers();\n\n const issues: ResourceIssue[] = [];\n const usedBy = new Map<string, string[]>();\n // `recordUse`, not `use`: React 19 made `use` a hook name, and\n // `react-hooks/rules-of-hooks` refuses a call to one from a plain function\n // — a lint error on a file with no React in it.\n const recordUse = (resource: string, by: string): void => {\n const list = usedBy.get(resource) ?? [];\n if (!list.includes(by)) list.push(by);\n usedBy.set(resource, list);\n };\n\n // ── Declarations ─────────────────────────────────────────────────────\n // Which export name is which resource, so a function's `import { media }`\n // can be recorded as reaching `bucket:media` without evaluating the\n // function. The export name and the key are usually the same word and\n // nothing requires them to be.\n const handleExports = new Map<string, string>();\n const resourcesModule = options.resources ? findResourcesModule(options.resources.replace(/\\.[mc]?[jt]s$/, \"\")) : undefined;\n if (resourcesModule) {\n try {\n const mod = await importModule(resourcesModule);\n for (const [exportName, value] of Object.entries(mod)) {\n if (isResourceHandle(value)) handleExports.set(exportName, resourceId(value.kind, value.key));\n }\n } catch (err) {\n issues.push({ path: path.relative(projectRoot, resourcesModule), message: describeIssue(err, projectRoot) });\n }\n }\n\n // ── Tables ───────────────────────────────────────────────────────────\n // Through the loader the runtime boots from, so a table that would not\n // load at boot is an issue here too, named by its file and table.\n let tables: TableDescriptor[] = [];\n if (options.schemaDir) {\n try {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const loaded = await loadBackendSchema(options.schemaDir, { projectRoot, importModule });\n tables = compileLoadedSchema(loaded).descriptors;\n } catch (err) {\n // Imported here: `@rebasepro/common` is the whole compiler, and a\n // derivation that never reads a schema has no use for it.\n const { isSchemaDefinitionError } = await import(\"@rebasepro/common\");\n if (isSchemaDefinitionError(err)) {\n for (const problem of err.problems) {\n issues.push({\n path: `table.${problem.key ? `${problem.table}.${problem.key}` : problem.table}`,\n message: problem.message\n });\n }\n } else {\n const file = typeof err === \"object\" && err !== null && \"file\" in err && typeof err.file === \"string\"\n ? err.file\n : options.schemaDir;\n issues.push({ path: path.relative(projectRoot, file), message: describeIssue(err, projectRoot) });\n }\n }\n }\n\n // ── Crons ────────────────────────────────────────────────────────────\n // Through the runtime's own loader, so the id the graph records is the id\n // the scheduler runs — the filename — and a cron that would not load at\n // boot does not load here either.\n //\n // Which means the module is EVALUATED, in a build step that has none of the\n // deployment's environment. A cron whose module scope reaches something that\n // validates `DATABASE_URL` at import therefore derives on a laptop with a\n // `.env` and nowhere else. That is worth an explicit sentence rather than a\n // stack, so `cronLoadIssue` adds one.\n if (cronsDir && fs.existsSync(cronsDir)) {\n // The runtime's loader logs each job as it loads, to stdout, as JSON\n // — which is also where `rebase resources --json` writes the graph.\n // Its problems come back as a list, so the log adds nothing here.\n const previousLevel = process.env.LOG_LEVEL;\n process.env.LOG_LEVEL = \"error\";\n try {\n const { loadCrons, declareCrons } = await import(\"@rebasepro/server\");\n const reportProblem = (problem: string) => {\n issues.push({ path: path.relative(projectRoot, cronsDir), message: cronLoadIssue(problem) });\n };\n // The importer above, not the loader's `new Function` import: plain\n // Node cannot import TypeScript, and a test runner's module sandbox\n // answers that one with \"a dynamic import callback was not\n // specified\" — the same trap the split-roles e2e records.\n const crons = await loadCrons(cronsDir, {\n importModule: url => importModule(url.startsWith(\"file:\") ? fileURLToPath(url) : url),\n onSkip: reportProblem\n });\n // One at a time, so a cron the graph refuses is reported by name\n // and the others are still declared.\n for (const [id, definition] of Object.entries(crons)) {\n try {\n declareCrons({ [id]: definition });\n } catch (err) {\n reportProblem(`${id} (threw: ${err instanceof Error ? err.message : String(err)})`);\n }\n }\n } catch (err) {\n issues.push({\n path: path.relative(projectRoot, cronsDir),\n message: cronLoadIssue(err instanceof Error ? err.message : String(err))\n });\n } finally {\n if (previousLevel === undefined) delete process.env.LOG_LEVEL;\n else process.env.LOG_LEVEL = previousLevel;\n }\n }\n\n // ── Functions ────────────────────────────────────────────────────────\n if (functionsDir && fs.existsSync(functionsDir)) {\n for (const report of analyseFunctionsDirectory(functionsDir, projectRoot)) {\n const requires = [...new Set(\n report.issues\n .filter(issue => issue.kind === \"node-builtin\" || issue.kind === \"node-only-package\")\n .map(issue => issue.message)\n )];\n try {\n declareFunction(report.name, {\n file: report.file,\n portable: report.portable,\n ...(requires.length > 0 ? { requires } : {})\n });\n } catch (err) {\n issues.push({ path: report.file, message: describeIssue(err, projectRoot) });\n }\n for (const imported of report.resourceImports) {\n const resource = handleExports.get(imported);\n if (resource) recordUse(resource, `function:${report.name}`);\n }\n }\n }\n\n // ── Edges ────────────────────────────────────────────────────────────\n const declared = new Set(declaredResources().map(r => resourceId(r.kind, r.key)));\n for (const table of tables) {\n for (const [resource, by] of tableEdges(table, declared)) recordUse(resource, by);\n }\n for (const sub of declaredSubscriptions()) {\n const id = resourceId(\"topic\", sub.topic);\n if (declared.has(id)) recordUse(id, `subscription:${sub.topic}.${sub.name}`);\n }\n for (const consumer of declaredQueueConsumers()) {\n const id = resourceId(\"queue\", consumer.queue);\n if (declared.has(id)) recordUse(id, `handler:${consumer.queue}`);\n }\n\n const graph = buildResourceGraph(usedBy);\n\n // Two resources of a kind whose env suffixes collide would silently read\n // each other's configuration, which is indistinguishable from a\n // misconfigured deployment.\n const byKind = new Map<string, string[]>();\n for (const r of graph.resources) {\n byKind.set(r.kind, [...(byKind.get(r.kind) ?? []), r.key]);\n }\n for (const [kind, keys] of byKind) {\n const collision = findEnvSuffixCollision(keys);\n if (collision) {\n issues.push({\n path: `${kind}.${collision.b}`,\n message:\n `\"${collision.a}\" and \"${collision.b}\" both bind from ${collision.suffix}, so one would ` +\n \"read the other's configuration. Rename one.\"\n });\n }\n }\n\n // A subscription on a topic nobody declared is a handler that will never\n // run, and nothing else would ever say so.\n const topics = new Set(graph.resources.filter(r => r.kind === \"topic\").map(r => r.key));\n for (const sub of declaredSubscriptions()) {\n if (!topics.has(sub.topic)) {\n issues.push({\n path: `topic.${sub.topic}`,\n message:\n `Subscription \"${sub.name}\" is declared on topic \"${sub.topic}\", which nothing declares. ` +\n \"The handler would never run.\"\n });\n }\n }\n\n // A table routed to a database nothing declares boots into a refusal, and\n // a column stored in a bucket nothing declares answers 501 on its first\n // upload. Both are cheaper to hear about here.\n const databases = new Set(graph.resources.filter(r => r.kind === \"database\").map(r => r.key));\n const buckets = new Set(graph.resources.filter(r => r.kind === \"bucket\").map(r => r.key));\n for (const table of tables) {\n if (table.database && table.database !== DEFAULT_RESOURCE_KEY && !databases.has(table.database)) {\n issues.push({\n path: `table.${table.slug}`,\n message:\n `lives in database \"${table.database}\", which nothing declares. ` +\n `Add database(\"${table.database}\") to backend/resources.ts, or import the handle and use it here.`\n });\n }\n for (const [where, storage] of tableStorage(table)) {\n const key = storage.source;\n if (key !== undefined && key !== DEFAULT_RESOURCE_KEY && buckets.size > 0 && !buckets.has(key)) {\n issues.push({\n path: `table.${table.slug}.${where}`,\n message: `stores into bucket \"${key}\", which nothing declares. Add bucket(\"${key}\") to backend/resources.ts.`\n });\n }\n }\n }\n\n return { graph, issues };\n}\n\n/** The graph as it is written to disk: stable key order, trailing newline. */\nexport function serializeResourceGraph(graph: ResourceGraph): string {\n const resources = graph.resources.map(r => ({\n kind: r.kind,\n key: r.key,\n engine: r.engine,\n transport: r.transport,\n ...(r.label !== undefined ? { label: r.label } : {}),\n ...(Object.keys(r.options).length > 0 ? { options: r.options } : {}),\n ...(r.usedBy && r.usedBy.length > 0 ? { usedBy: r.usedBy } : {})\n }));\n return JSON.stringify({\n $generated: `Generated from backend/resources.ts and backend/schema by \\`rebase resources\\`. Edit the declarations, not this file.`,\n version: graph.version,\n resources\n }, null, 4) + \"\\n\";\n}\n\n/** Read the committed graph, or null when a project has none yet. */\nexport function readResourceGraphFile(projectRoot: string): string | null {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n}\n\n/**\n * Write the graph, and say whether the file changed.\n *\n * The boolean is what a `--check` mode reports on: a project whose committed\n * graph disagrees with its declarations has a host reading one thing and a runtime\n * doing another.\n */\nexport function writeResourceGraphFile(projectRoot: string, graph: ResourceGraph): { changed: boolean; file: string } {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n const next = serializeResourceGraph(graph);\n const previous = fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n if (previous === next) return { changed: false, file };\n fs.writeFileSync(file, next);\n return { changed: true, file };\n}\n\n/** Parse a committed graph file, tolerating the `$generated` banner. */\nexport function parseResourceGraph(contents: string): ResourceGraph {\n const raw = JSON.parse(contents) as { version?: number; resources?: unknown };\n if (raw.version !== 1) {\n throw new Error(\n `Unsupported resource graph version ${String(raw.version)}. ` +\n \"This project was generated by a newer Rebase; upgrade rather than provisioning half of it.\"\n );\n }\n const entries = Array.isArray(raw.resources) ? raw.resources as Record<string, unknown>[] : [];\n // `options` is omitted from the file when empty; a reader of the graph\n // expects it present, so it is restored here.\n return { version: 1, resources: entries.map(r => ({ options: {}, ...r })) as ResourceGraph[\"resources\"] };\n}\n\n/**\n * Add the resources a project has without declaring them.\n *\n * A backend has a database whether or not anyone said so, and a project that\n * declares no buckets still gets one default storage source from the plain\n * unsuffixed variables. Both are load-bearing defaults and both are invisible\n * in the graph, so a status view built only from declarations would show an\n * empty screen to the majority of projects — the ones that most need to be told\n * which variable their one database reads.\n *\n * Declaring a *named* one leaves the default where it is, as the server does\n * (`resolveDataSources` and `resolveStorageSources` in `@rebasepro/server`):\n * `bucket(\"media\")` adds a source and never moves the files the default holds,\n * so both are listed. The default is displaced only by declaring it — or, for a\n * bucket, by marking exactly one server-side bucket `default: true`, which then\n * serves the uploads that name no `storageSource`. This used to drop the\n * default once a bucket was declared, and `rebase status` and `rebase\n * resources` stopped listing a source the server was still serving.\n */\nexport function withImplicitDefaults(graph: ResourceGraph): {\n declaration: ResourceDeclaration;\n implicit: boolean;\n}[] {\n const entries = graph.resources.map(declaration => ({ declaration, implicit: false }));\n const declaresDefault = (kind: string) => graph.resources.some(r => r.kind === kind && r.key === DEFAULT_RESOURCE_KEY);\n const markedDefault = graph.resources.filter(r =>\n r.kind === \"bucket\" && (r.transport ?? \"server\") === \"server\" && r.options.default === true);\n\n if (!declaresDefault(\"database\")) {\n entries.unshift({\n declaration: {\n kind: \"database\",\n key: DEFAULT_RESOURCE_KEY,\n engine: \"postgres\",\n transport: \"server\",\n options: {}\n },\n implicit: true\n });\n }\n if (!declaresDefault(\"bucket\") && markedDefault.length !== 1) {\n const implicitBucket = {\n declaration: {\n kind: \"bucket\",\n key: DEFAULT_RESOURCE_KEY,\n // `local` is what an unconfigured default source resolves to,\n // and naming it here keeps the row honest about what a project\n // with no S3 variables actually gets: a directory that a\n // container erases on restart, which production then drops.\n engine: \"local\",\n transport: \"server\" as const,\n options: {}\n },\n implicit: true\n };\n // First among the buckets, as the database default is first among the\n // databases; last when there are none.\n const firstBucket = entries.findIndex(entry => entry.declaration.kind === \"bucket\");\n if (firstBucket === -1) entries.push(implicitBucket);\n else entries.splice(firstBucket, 0, implicitBucket);\n }\n return entries;\n}\n\n/**\n * The resources a project *has*, which is what a person is asking about.\n *\n * One projection, because two of them disagreed. `rebase status` built its\n * rows from {@link withImplicitDefaults} and listed `buckets ✓ (default) local\n * · implicit`; `rebase resources` and `rebase resources --json` built theirs\n * from the raw graph and listed only the database and the function. Two\n * commands whose whole job is to answer \"what does this project need\", on the\n * same stock scaffold, giving different answers.\n *\n * The implicit entries are marked rather than hidden, because the distinction\n * is real and load-bearing: a declared resource is recorded in\n * `rebase.resources.json` for a host to provision, and an implicit one is a\n * default the runtime supplies whether or not anyone wrote it down. That file\n * still holds declarations only — it is a wire contract a host reads, and\n * putting defaults in it would ask for something to be provisioned that\n * nobody declared.\n */\nexport type ProjectedResource = ResourceDeclaration & { implicit?: true };\n\nexport function projectResourceGraph(graph: ResourceGraph): ProjectedResource[] {\n return withImplicitDefaults(graph).map(({ declaration, implicit }) =>\n (implicit ? { ...declaration, implicit: true as const } : declaration));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IAAa,0BAA0B;;;;;;;;;;;;;;AA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eAClD,WAAW;EAAE,GAAG;EAAa,UAAU;CAAc,IAAI,WAAY;AAC9E"}
1
+ {"version":3,"file":"derive-ChP6vgfi.js","names":[],"sources":["../src/resources/derive.ts"],"sourcesContent":["/**\n * Deriving the resource graph from a project's backend, and recording it.\n *\n * ## Why the graph is derived rather than authored\n *\n * A resource is declared once, in code. But a host has to know what a project\n * needs *before* it runs anything — that is how a console can say \"this project\n * wants a `media` bucket and has none\" on a first deploy, and it is the reason\n * storage topology used to be hand-written into `rebase.json` in the first\n * place. A `custom` runtime makes it sharper still: it emits no bundle\n * manifest, so without a committed artifact there is nothing to read at all.\n *\n * So the graph is derived by evaluating `backend/resources.ts` and the tables\n * in `backend/schema`, and written to\n * `rebase.resources.json`, which is committed. Same arrangement as\n * `schema.generated.ts`: authored in one place, generated into another, and a\n * gate fails if the two disagree. The file is an *output*, never an input —\n * which is what removes the old silent merge, because there is no longer a\n * second declaration for anything to be merged with.\n *\n * ## Why evaluation rather than static analysis\n *\n * Encore parses the source and builds the graph from the AST. Rebase already\n * evaluates `backend/schema` to load the tables, and evaluation is exact where a parser\n * is approximate — a resource declared in a loop, or behind a helper, is\n * invisible to a parser and obvious to an interpreter. The cost is running user\n * code at build time, which this project already accepts everywhere else.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport {\n DEFAULT_RESOURCE_KEY,\n buildResourceGraph,\n declareFunction,\n declaredQueueConsumers,\n declaredResources,\n declaredSubscriptions,\n findEnvSuffixCollision,\n isResourceHandle,\n resetDeclaredQueueConsumers,\n resetDeclaredResources,\n resetDeclaredSubscriptions,\n resourceId,\n type ColumnStorage,\n type JsonShape,\n type RebaseBackendAppConfig,\n type ResourceDeclaration,\n type ResourceGraph,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { analyseFunctionsDirectory } from \"../function-portability\";\nimport { resolveBackendPaths } from \"../manifest\";\nimport { createSchemaModuleImporter } from \"../utils/import-schema-module\";\nimport type { ModuleAliases } from \"../utils/project-schema\";\nimport type { SchemaModuleImporter } from \"@rebasepro/server\";\nimport { cliVersion } from \"../utils/version\";\n\n/** The committed, generated record of what a project needs. */\nexport const RESOURCE_GRAPH_FILENAME = \"rebase.resources.json\";\n\n/** A problem found while deriving, reported with the rest rather than thrown one at a time. */\nexport interface ResourceIssue {\n path: string;\n message: string;\n}\n\n/**\n * Which `@rebasepro/*` package a module error is about, when it is about one.\n *\n * Both directions of a version skew arrive as an error about the *user's* file:\n * `resources.ts The requested module '@rebasepro/types' does not provide an\n * export named 'queue'`. Nothing in that says which copy of `@rebasepro/types`\n * is installed, what version this CLI is, or that the two disagree — so the\n * reader goes looking for a typo in code they just copied out of the docs.\n *\n * Two shapes, because the two directions produce different errors: a named\n * export the installed copy is too old for, and a package the installed tree\n * does not have at all.\n */\nconst NAMED_EXPORT_MISSING = /does not provide an export named ['\"]([^'\"]+)['\"]/;\nconst SPECIFIER = /(@rebasepro\\/[a-z0-9-]+)/;\n\n/** The version of a package as resolved from the project, or null. */\nfunction installedVersion(specifier: string, from: string): string | null {\n try {\n const require = createRequire(path.join(from, \"noop.js\"));\n const manifest = require.resolve(`${specifier}/package.json`);\n const version: unknown = JSON.parse(fs.readFileSync(manifest, \"utf-8\")).version;\n return typeof version === \"string\" ? version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The message an issue carries, with the skew named when there is one.\n *\n * `main` runs 497 commits ahead of npm `latest` and the docs site publishes from\n * `main`, so the shape this exists for is routine: a scaffold pinned to the\n * published version, backend code written against today's documentation, and an\n * error about the project's file. The fix is one command and the error named none\n * of it — the same failure as `404 No PUT route on collection 'projects'`, one\n * layer down.\n *\n * Says nothing extra when the two versions agree, or when either is unreadable:\n * a sentence naming one version twice is worse than no sentence.\n */\nexport function describeIssue(err: unknown, projectRoot: string, ownVersion = cliVersion()): string {\n const message = err instanceof Error ? err.message : String(err);\n const code = (err as { code?: unknown } | null)?.code;\n const missingExport = NAMED_EXPORT_MISSING.exec(message);\n const isSkewShaped = missingExport !== null || code === \"ERR_MODULE_NOT_FOUND\";\n if (!isSkewShaped) return message;\n\n const specifier = SPECIFIER.exec(message)?.[1];\n if (!specifier) return message;\n\n // One line, not two: every caller renders an issue as `path message` on a\n // single row, so a newline here would land the useful half unindented under\n // the file name.\n const lead = /[.!?]$/.test(message.trim()) ? message.trim() : `${message.trim()}.`;\n\n const installed = installedVersion(specifier, projectRoot);\n if (installed === null) {\n return `${lead} ${specifier} is not installed in this project; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`;\n }\n if (ownVersion === \"unknown\" || installed === ownVersion) return message;\n\n // Which side to move is the question the reader actually has, and it has a\n // right answer: the CLI is what evaluates this file, so the packages follow\n // it — unless the CLI is the older one, in which case following it would\n // move the project backwards.\n const cliIsNewer = compareVersions(ownVersion, installed) > 0;\n return cliIsNewer\n ? `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`\n : `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}, which is older. `\n + `Update the CLI to ${installed}, or pin ${specifier} back to ${ownVersion}`;\n}\n\n/** -1 / 0 / 1 on the numeric parts, ignoring any prerelease tail. */\nfunction compareVersions(a: string, b: string): number {\n const parts = (v: string): number[] => v.split(\"-\")[0].split(\".\").map(n => Number(n) || 0);\n const [x, y] = [parts(a), parts(b)];\n for (let i = 0; i < 3; i++) {\n if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0) ? -1 : 1;\n }\n return 0;\n}\n\n/** The spellings of the resources module, tried in order, after its path without extension. */\nconst RESOURCE_MODULE_SUFFIXES = [\".ts\", \".mts\", \".js\", \".mjs\", \"/index.ts\", \"/index.js\"];\n\n/** The resources module under `base` (a path without extension), or undefined. */\nfunction findResourcesModule(base: string): string | undefined {\n return RESOURCE_MODULE_SUFFIXES.map(suffix => `${base}${suffix}`)\n .find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile());\n}\n\nexport interface DeriveOptions {\n /** The project root, absolute: what the importer is rooted at and every recorded path is relative to. */\n projectRoot: string;\n /**\n * The resources module, absolute, without or with its extension:\n * `<root>/backend/resources`. Its `database()` / `bucket()` / `topic()` /\n * `queue()` declarations are the graph's nodes.\n */\n resources?: string;\n /**\n * The schema directory, absolute. Its tables are evaluated too: a table\n * reaches its database and every bucket a storage column stores into, and a\n * bucket may be declared beside the table that stores into it.\n */\n schemaDir?: string;\n /**\n * Absolute path to the crons directory. Each file is evaluated through the\n * same loader the runtime uses, which declares the cron under the same id\n * the scheduler runs it as. Absent, or missing on disk: no crons.\n */\n cronsDir?: string;\n /**\n * Absolute path to the functions directory. Read statically — the\n * bundler's portability analysis — never evaluated: a function's module\n * scope belongs to a running backend, not a build.\n */\n functionsDir?: string;\n /** Module specifiers mapped to files when importing (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n}\n\n/** The derive options for a backend app, from its manifest entry. */\nexport function deriveOptionsFor(projectRoot: string, app: RebaseBackendAppConfig): DeriveOptions {\n const paths = resolveBackendPaths(app, projectRoot);\n return {\n projectRoot,\n resources: path.join(projectRoot, paths.resources).replace(/\\.[mc]?[jt]s$/, \"\"),\n schemaDir: path.join(projectRoot, paths.tables),\n cronsDir: path.join(projectRoot, paths.crons),\n functionsDir: path.join(projectRoot, paths.functions)\n };\n}\n\n/** Every storage setting in a JSON shape, with its dotted path below the column. */\nfunction jsonStorage(shape: JsonShape, prefix: string): Array<[string, ColumnStorage]> {\n switch (shape.kind) {\n case \"string\":\n return shape.storage ? [[prefix, shape.storage]] : [];\n case \"object\":\n return Object.entries(shape.fields).flatMap(([name, field]) => jsonStorage(field, `${prefix}.${name}`));\n case \"array\":\n return jsonStorage(shape.of, prefix);\n case \"oneOf\":\n return Object.entries(shape.variants).flatMap(([name, variant]) => jsonStorage(variant, `${prefix}.${name}`));\n default:\n return [];\n }\n}\n\n/**\n * Every storage setting a table's columns carry, keyed by the dotted path to\n * it: a storage column, the items of a storage array, a file inside a JSON\n * document.\n */\nfunction tableStorage(table: TableDescriptor): Array<[string, ColumnStorage]> {\n return table.columns.flatMap((column): Array<[string, ColumnStorage]> => [\n ...(column.storage ? [[column.key, column.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.element?.storage ? [[column.key, column.element.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.json ? jsonStorage(column.json, column.key) : [])\n ]);\n}\n\n/**\n * The resources a table reaches: its database, and every bucket a storage\n * column stores into. Only resources the graph declares get an edge — the\n * implicit default database is not in the graph, so a table that names no\n * `database` records nothing.\n *\n * The ids are `table:<slug>` and `column:<slug>.<path>`; a host's topology\n * view parses them.\n */\nfunction tableEdges(table: TableDescriptor, declared: Set<string>): Array<[string, string]> {\n const edges: Array<[string, string]> = [];\n const databaseId = resourceId(\"database\", table.database ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(databaseId)) edges.push([databaseId, `table:${table.slug}`]);\n for (const [where, storage] of tableStorage(table)) {\n const bucketId = resourceId(\"bucket\", storage.source ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(bucketId)) edges.push([bucketId, `column:${table.slug}.${where}`]);\n }\n return edges;\n}\n\n/**\n * A cron file that would not import, said in terms somebody can act on.\n *\n * The graph is derived by evaluating each cron module, in a process with none\n * of the deployment's environment — so a cron that reaches a module validating\n * `DATABASE_URL` at import fails here and works perfectly at boot. The raw\n * message is a Zod error about a variable, which reads as \"the environment is\n * wrong\" when the environment is not the point.\n */\nfunction cronLoadIssue(problem: string): string {\n return `${summariseCronProblem(problem)}\\n` +\n \" `rebase resources` evaluates each cron file to read its schedule, and it is a build \" +\n \"step: no .env, no secrets. Move work that needs the deployment's environment inside the \" +\n \"handler — `const { x } = await import(\\\"…\\\")` — so the module scope imports nothing that \" +\n \"reads configuration.\";\n}\n\n/**\n * The cron loader's `<file> (threw: <message>)`, as one line.\n *\n * The message is whatever the module threw, and the common case is a schema\n * validator: `loadEnv()` at module scope with no `.env` present throws a\n * `ZodError`, whose `.message` is the JSON array of its issues. That arrived\n * here verbatim — ten lines of `{ \"expected\": \"string\", \"code\":\n * \"invalid_type\", … }` — with the sentence that says what to do underneath it,\n * so the reader met \"Invalid input: expected string, received undefined\" twice\n * before reaching the explanation.\n *\n * A validator's own sentences are the useful half of that object, so they are\n * kept and the serialisation is dropped.\n */\nfunction summariseCronProblem(problem: string): string {\n const match = problem.match(/^(.*) \\(threw: ([\\s\\S]*)\\)$/);\n if (!match) return problem.split(\"\\n\")[0];\n const [, file, thrown] = match;\n return `${file}: ${summariseThrownMessage(thrown)}`;\n}\n\n/** One sentence out of a thrown message, whatever shape it arrived in. */\nfunction summariseThrownMessage(message: string): string {\n const trimmed = message.trim();\n if (trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n const issues = Array.isArray(parsed) ? parsed : [parsed];\n const sentences = [...new Set(\n issues\n .map(issue => (issue as { message?: unknown } | null)?.message)\n .filter((m): m is string => typeof m === \"string\" && m.length > 0)\n )];\n if (sentences.length > 0) return sentences.join(\"; \");\n } catch {\n // Not JSON after all — fall through to the first line.\n }\n }\n return trimmed.split(\"\\n\")[0];\n}\n\n/**\n * Evaluate a project's resources and tables and return the graph they declare.\n *\n * Clears any previously registered declarations first, so deriving twice in one\n * process — a watch mode, a test — describes the project rather than the union\n * of every project seen so far.\n */\nexport async function deriveResourceGraph(options: DeriveOptions): Promise<{ graph: ResourceGraph; issues: ResourceIssue[] }> {\n const { projectRoot, cronsDir, functionsDir } = options;\n // One importer for everything evaluated here: the resources module, the\n // tables that import its handles and the crons see one copy of each module,\n // so a handle a table imports is the handle the graph declared. A new\n // importer reads every file as it is now, so deriving again in one process\n // evaluates the declarations again. Created on first use: a project with\n // nothing to evaluate pays nothing for it.\n let importer: SchemaModuleImporter | undefined;\n const importModule: SchemaModuleImporter = async (file) => {\n importer ??= await createSchemaModuleImporter(projectRoot, options.moduleAliases);\n return importer(file);\n };\n\n // All three registries, and the side lists are the easy ones to forget:\n // resetting only the resources leaves one project's handlers attached\n // while its topics are gone — every one of them then reads as orphaned\n // against the *next* project. Caught by deriving twice in one process,\n // which is what a watch mode does.\n resetDeclaredResources();\n resetDeclaredSubscriptions();\n resetDeclaredQueueConsumers();\n\n const issues: ResourceIssue[] = [];\n const usedBy = new Map<string, string[]>();\n // `recordUse`, not `use`: React 19 made `use` a hook name, and\n // `react-hooks/rules-of-hooks` refuses a call to one from a plain function\n // — a lint error on a file with no React in it.\n const recordUse = (resource: string, by: string): void => {\n const list = usedBy.get(resource) ?? [];\n if (!list.includes(by)) list.push(by);\n usedBy.set(resource, list);\n };\n\n // ── Declarations ─────────────────────────────────────────────────────\n // Which export name is which resource, so a function's `import { media }`\n // can be recorded as reaching `bucket:media` without evaluating the\n // function. The export name and the key are usually the same word and\n // nothing requires them to be.\n const handleExports = new Map<string, string>();\n const resourcesModule = options.resources ? findResourcesModule(options.resources.replace(/\\.[mc]?[jt]s$/, \"\")) : undefined;\n if (resourcesModule) {\n try {\n const mod = await importModule(resourcesModule);\n for (const [exportName, value] of Object.entries(mod)) {\n if (isResourceHandle(value)) handleExports.set(exportName, resourceId(value.kind, value.key));\n }\n } catch (err) {\n issues.push({ path: path.relative(projectRoot, resourcesModule), message: describeIssue(err, projectRoot) });\n }\n }\n\n // ── Tables ───────────────────────────────────────────────────────────\n // Through the loader the runtime boots from, so a table that would not\n // load at boot is an issue here too, named by its file and table.\n let tables: TableDescriptor[] = [];\n if (options.schemaDir) {\n try {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const loaded = await loadBackendSchema(options.schemaDir, { projectRoot, importModule });\n tables = compileLoadedSchema(loaded).descriptors;\n } catch (err) {\n // Imported here: `@rebasepro/common` is the whole compiler, and a\n // derivation that never reads a schema has no use for it.\n const { isSchemaDefinitionError } = await import(\"@rebasepro/common\");\n if (isSchemaDefinitionError(err)) {\n for (const problem of err.problems) {\n issues.push({\n path: `table.${problem.key ? `${problem.table}.${problem.key}` : problem.table}`,\n message: problem.message\n });\n }\n } else {\n const file = typeof err === \"object\" && err !== null && \"file\" in err && typeof err.file === \"string\"\n ? err.file\n : options.schemaDir;\n issues.push({ path: path.relative(projectRoot, file), message: describeIssue(err, projectRoot) });\n }\n }\n }\n\n // ── Crons ────────────────────────────────────────────────────────────\n // Through the runtime's own loader, so the id the graph records is the id\n // the scheduler runs — the filename — and a cron that would not load at\n // boot does not load here either.\n //\n // Which means the module is EVALUATED, in a build step that has none of the\n // deployment's environment. A cron whose module scope reaches something that\n // validates `DATABASE_URL` at import therefore derives on a laptop with a\n // `.env` and nowhere else. That is worth an explicit sentence rather than a\n // stack, so `cronLoadIssue` adds one.\n if (cronsDir && fs.existsSync(cronsDir)) {\n // The runtime's loader logs each job as it loads, to stdout, as JSON\n // — which is also where `rebase resources --json` writes the graph.\n // Its problems come back as a list, so the log adds nothing here.\n const previousLevel = process.env.LOG_LEVEL;\n process.env.LOG_LEVEL = \"error\";\n try {\n const { loadCrons, declareCrons } = await import(\"@rebasepro/server\");\n const reportProblem = (problem: string) => {\n issues.push({ path: path.relative(projectRoot, cronsDir), message: cronLoadIssue(problem) });\n };\n // The importer above, not the loader's `new Function` import: plain\n // Node cannot import TypeScript, and a test runner's module sandbox\n // answers that one with \"a dynamic import callback was not\n // specified\" — the same trap the split-roles e2e records.\n const crons = await loadCrons(cronsDir, {\n importModule: url => importModule(url.startsWith(\"file:\") ? fileURLToPath(url) : url),\n onSkip: reportProblem\n });\n // One at a time, so a cron the graph refuses is reported by name\n // and the others are still declared.\n for (const [id, definition] of Object.entries(crons)) {\n try {\n declareCrons({ [id]: definition });\n } catch (err) {\n reportProblem(`${id} (threw: ${err instanceof Error ? err.message : String(err)})`);\n }\n }\n } catch (err) {\n issues.push({\n path: path.relative(projectRoot, cronsDir),\n message: cronLoadIssue(err instanceof Error ? err.message : String(err))\n });\n } finally {\n if (previousLevel === undefined) delete process.env.LOG_LEVEL;\n else process.env.LOG_LEVEL = previousLevel;\n }\n }\n\n // ── Functions ────────────────────────────────────────────────────────\n if (functionsDir && fs.existsSync(functionsDir)) {\n for (const report of analyseFunctionsDirectory(functionsDir, projectRoot)) {\n const requires = [...new Set(\n report.issues\n .filter(issue => issue.kind === \"node-builtin\" || issue.kind === \"node-only-package\")\n .map(issue => issue.message)\n )];\n try {\n declareFunction(report.name, {\n file: report.file,\n portable: report.portable,\n ...(requires.length > 0 ? { requires } : {})\n });\n } catch (err) {\n issues.push({ path: report.file, message: describeIssue(err, projectRoot) });\n }\n for (const imported of report.resourceImports) {\n const resource = handleExports.get(imported);\n if (resource) recordUse(resource, `function:${report.name}`);\n }\n }\n }\n\n // ── Edges ────────────────────────────────────────────────────────────\n const declared = new Set(declaredResources().map(r => resourceId(r.kind, r.key)));\n for (const table of tables) {\n for (const [resource, by] of tableEdges(table, declared)) recordUse(resource, by);\n }\n for (const sub of declaredSubscriptions()) {\n const id = resourceId(\"topic\", sub.topic);\n if (declared.has(id)) recordUse(id, `subscription:${sub.topic}.${sub.name}`);\n }\n for (const consumer of declaredQueueConsumers()) {\n const id = resourceId(\"queue\", consumer.queue);\n if (declared.has(id)) recordUse(id, `handler:${consumer.queue}`);\n }\n\n const graph = buildResourceGraph(usedBy);\n\n // Two resources of a kind whose env suffixes collide would silently read\n // each other's configuration, which is indistinguishable from a\n // misconfigured deployment.\n const byKind = new Map<string, string[]>();\n for (const r of graph.resources) {\n byKind.set(r.kind, [...(byKind.get(r.kind) ?? []), r.key]);\n }\n for (const [kind, keys] of byKind) {\n const collision = findEnvSuffixCollision(keys);\n if (collision) {\n issues.push({\n path: `${kind}.${collision.b}`,\n message:\n `\"${collision.a}\" and \"${collision.b}\" both bind from ${collision.suffix}, so one would ` +\n \"read the other's configuration. Rename one.\"\n });\n }\n }\n\n // A subscription on a topic nobody declared is a handler that will never\n // run, and nothing else would ever say so.\n const topics = new Set(graph.resources.filter(r => r.kind === \"topic\").map(r => r.key));\n for (const sub of declaredSubscriptions()) {\n if (!topics.has(sub.topic)) {\n issues.push({\n path: `topic.${sub.topic}`,\n message:\n `Subscription \"${sub.name}\" is declared on topic \"${sub.topic}\", which nothing declares. ` +\n \"The handler would never run.\"\n });\n }\n }\n\n // A table routed to a database nothing declares boots into a refusal, and\n // a column stored in a bucket nothing declares answers 501 on its first\n // upload. Both are cheaper to hear about here.\n const databases = new Set(graph.resources.filter(r => r.kind === \"database\").map(r => r.key));\n const buckets = new Set(graph.resources.filter(r => r.kind === \"bucket\").map(r => r.key));\n for (const table of tables) {\n if (table.database && table.database !== DEFAULT_RESOURCE_KEY && !databases.has(table.database)) {\n issues.push({\n path: `table.${table.slug}`,\n message:\n `lives in database \"${table.database}\", which nothing declares. ` +\n `Add database(\"${table.database}\") to backend/resources.ts, or import the handle and use it here.`\n });\n }\n for (const [where, storage] of tableStorage(table)) {\n const key = storage.source;\n if (key !== undefined && key !== DEFAULT_RESOURCE_KEY && buckets.size > 0 && !buckets.has(key)) {\n issues.push({\n path: `table.${table.slug}.${where}`,\n message: `stores into bucket \"${key}\", which nothing declares. Add bucket(\"${key}\") to backend/resources.ts.`\n });\n }\n }\n }\n\n return { graph, issues };\n}\n\n/** The graph as it is written to disk: stable key order, trailing newline. */\nexport function serializeResourceGraph(graph: ResourceGraph): string {\n const resources = graph.resources.map(r => ({\n kind: r.kind,\n key: r.key,\n engine: r.engine,\n transport: r.transport,\n ...(r.label !== undefined ? { label: r.label } : {}),\n ...(Object.keys(r.options).length > 0 ? { options: r.options } : {}),\n ...(r.usedBy && r.usedBy.length > 0 ? { usedBy: r.usedBy } : {})\n }));\n return JSON.stringify({\n $generated: `Generated from backend/resources.ts and backend/schema by \\`rebase resources\\`. Edit the declarations, not this file.`,\n version: graph.version,\n resources\n }, null, 4) + \"\\n\";\n}\n\n/** Read the committed graph, or null when a project has none yet. */\nexport function readResourceGraphFile(projectRoot: string): string | null {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n}\n\n/**\n * Write the graph, and say whether the file changed.\n *\n * The boolean is what a `--check` mode reports on: a project whose committed\n * graph disagrees with its declarations has a host reading one thing and a runtime\n * doing another.\n */\nexport function writeResourceGraphFile(projectRoot: string, graph: ResourceGraph): { changed: boolean; file: string } {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n const next = serializeResourceGraph(graph);\n const previous = fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n if (previous === next) return { changed: false, file };\n fs.writeFileSync(file, next);\n return { changed: true, file };\n}\n\n/** Parse a committed graph file, tolerating the `$generated` banner. */\nexport function parseResourceGraph(contents: string): ResourceGraph {\n const raw = JSON.parse(contents) as { version?: number; resources?: unknown };\n if (raw.version !== 1) {\n throw new Error(\n `Unsupported resource graph version ${String(raw.version)}. ` +\n \"This project was generated by a newer Rebase; upgrade rather than provisioning half of it.\"\n );\n }\n const entries = Array.isArray(raw.resources) ? raw.resources as Record<string, unknown>[] : [];\n // `options` is omitted from the file when empty; a reader of the graph\n // expects it present, so it is restored here.\n return { version: 1, resources: entries.map(r => ({ options: {}, ...r })) as ResourceGraph[\"resources\"] };\n}\n\n/**\n * Add the resources a project has without declaring them.\n *\n * A backend has a database whether or not anyone said so, and a project that\n * declares no buckets still gets one default storage source from the plain\n * unsuffixed variables. Both are load-bearing defaults and both are invisible\n * in the graph, so a status view built only from declarations would show an\n * empty screen to the majority of projects — the ones that most need to be told\n * which variable their one database reads.\n *\n * Declaring a *named* one leaves the default where it is, as the server does\n * (`resolveDataSources` and `resolveStorageSources` in `@rebasepro/server`):\n * `bucket(\"media\")` adds a source and never moves the files the default holds,\n * so both are listed. The default is displaced only by declaring it — or, for a\n * bucket, by marking exactly one server-side bucket `default: true`, which then\n * serves the uploads that name no `storageSource`. This used to drop the\n * default once a bucket was declared, and `rebase status` and `rebase\n * resources` stopped listing a source the server was still serving.\n */\nexport function withImplicitDefaults(graph: ResourceGraph): {\n declaration: ResourceDeclaration;\n implicit: boolean;\n}[] {\n const entries = graph.resources.map(declaration => ({ declaration, implicit: false }));\n const declaresDefault = (kind: string) => graph.resources.some(r => r.kind === kind && r.key === DEFAULT_RESOURCE_KEY);\n const markedDefault = graph.resources.filter(r =>\n r.kind === \"bucket\" && (r.transport ?? \"server\") === \"server\" && r.options.default === true);\n\n if (!declaresDefault(\"database\")) {\n entries.unshift({\n declaration: {\n kind: \"database\",\n key: DEFAULT_RESOURCE_KEY,\n engine: \"postgres\",\n transport: \"server\",\n options: {}\n },\n implicit: true\n });\n }\n if (!declaresDefault(\"bucket\") && markedDefault.length !== 1) {\n const implicitBucket = {\n declaration: {\n kind: \"bucket\",\n key: DEFAULT_RESOURCE_KEY,\n // `local` is what an unconfigured default source resolves to,\n // and naming it here keeps the row honest about what a project\n // with no S3 variables actually gets: a directory that a\n // container erases on restart, which production then drops.\n engine: \"local\",\n transport: \"server\" as const,\n options: {}\n },\n implicit: true\n };\n // First among the buckets, as the database default is first among the\n // databases; last when there are none.\n const firstBucket = entries.findIndex(entry => entry.declaration.kind === \"bucket\");\n if (firstBucket === -1) entries.push(implicitBucket);\n else entries.splice(firstBucket, 0, implicitBucket);\n }\n return entries;\n}\n\n/**\n * The resources a project *has*, which is what a person is asking about.\n *\n * One projection, because two of them disagreed. `rebase status` built its\n * rows from {@link withImplicitDefaults} and listed `buckets ✓ (default) local\n * · implicit`; `rebase resources` and `rebase resources --json` built theirs\n * from the raw graph and listed only the database and the function. Two\n * commands whose whole job is to answer \"what does this project need\", on the\n * same stock scaffold, giving different answers.\n *\n * The implicit entries are marked rather than hidden, because the distinction\n * is real and load-bearing: a declared resource is recorded in\n * `rebase.resources.json` for a host to provision, and an implicit one is a\n * default the runtime supplies whether or not anyone wrote it down. That file\n * still holds declarations only — it is a wire contract a host reads, and\n * putting defaults in it would ask for something to be provisioned that\n * nobody declared.\n */\nexport type ProjectedResource = ResourceDeclaration & { implicit?: true };\n\nexport function projectResourceGraph(graph: ResourceGraph): ProjectedResource[] {\n return withImplicitD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B,IAAI,QAAQ,KAAK,cAAc;OAC9C,QAAQ,OAAO,aAAa,GAAG,cAAc;CACtD;CACA,OAAO;AACX;AAsBA,SAAgB,qBAAqB,OAA2C;CAC5E,OAAO,qBAAqB,KAAK,CAAC,CAAC,KAAK,EAAE,aAAa,eAClD,WAAW;EAAE,GAAG;EAAa,UAAU;CAAc,IAAI,WAAY;AAC9E"}
@@ -504,7 +504,7 @@ async function declaredAdditionalDatabases(projectRoot) {
504
504
  try {
505
505
  const backend = findBackendApp(loadManifest(projectRoot).manifest);
506
506
  if (!backend) return [];
507
- const { deriveResourceGraph, deriveOptionsFor } = await import("./derive-Mky_u59_.js").then((n) => n.i);
507
+ const { deriveResourceGraph, deriveOptionsFor } = await import("./derive-ChP6vgfi.js").then((n) => n.i);
508
508
  const { graph } = await deriveResourceGraph({
509
509
  ...deriveOptionsFor(projectRoot, backend.app),
510
510
  schemaDir: void 0,
@@ -626,6 +626,17 @@ function databaseEndpoint(url) {
626
626
  return `${host}${parsed.port ? `:${parsed.port}` : ""}${name ? `/${name}` : ""}`;
627
627
  }
628
628
  /**
629
+ * Where the site the dev backend serves itself is, for `FRONTEND_URL`, or
630
+ * `undefined` when it serves none: the app at `/` when there is one, else the
631
+ * first. Exported for its test.
632
+ */
633
+ function devServedSiteUrl(shape, backendPort) {
634
+ const apps = shape.servedByBackend ?? [];
635
+ const app = apps.find((candidate) => candidate.path === "/") ?? apps[0];
636
+ if (!app || /^https?:\/\//i.test(app.path)) return void 0;
637
+ return `http://localhost:${backendPort}${app.path === "/" ? "" : app.path.replace(/\/+$/, "")}`;
638
+ }
639
+ /**
629
640
  * Read {@link DevStaticShape} out of a loaded manifest. Exported for its test.
630
641
  *
631
642
  * Which declared app is running is decided by its `root` being `frontend/`,
@@ -647,8 +658,13 @@ function devStaticShape(manifest, projectRoot, frontendDir) {
647
658
  };
648
659
  }
649
660
  const mount = cmsMountOf(manifest);
661
+ const servedByBackend = statics.filter(([, app]) => !app.build && path.resolve(projectRoot, app.root) === path.resolve(projectRoot, app.output)).map(([appName, app]) => ({
662
+ appName,
663
+ path: app.path ?? "/"
664
+ }));
650
665
  return {
651
666
  declaresStaticApp: statics.length > 0,
667
+ ...servedByBackend.length > 0 ? { servedByBackend } : {},
652
668
  ...served ? { served } : {},
653
669
  ...mount ? { cms: {
654
670
  appName: mount.appName,
@@ -1496,6 +1512,10 @@ async function devCommand(rawArgs) {
1496
1512
  env.PORT = String(startPort);
1497
1513
  env.REBASE_DEV_PORT_EXPLICIT = String(portIsPinned);
1498
1514
  if (!backendOnly && frontendDir) env.FRONTEND_URL = `http://localhost:${frontendPort}`;
1515
+ else {
1516
+ const served = devServedSiteUrl(staticShape, startPort);
1517
+ if (served) env.FRONTEND_URL = served;
1518
+ }
1499
1519
  console.log(` ${chalk.cyan("▶")} Backend: ${chalk.gray(backendDir)}`);
1500
1520
  console.log(` ${chalk.gray("↳ PORT")} = ${chalk.white(String(startPort))} ${chalk.gray(`(${START_PORT_SOURCE_LABELS[startPortSource]})`)}`);
1501
1521
  console.log(` ${chalk.gray("↳ Database")} = ${chalk.white(databaseBannerValue(prepared))}`);
@@ -1849,6 +1869,7 @@ async function devCommand(rawArgs) {
1849
1869
  children.push(backendChild);
1850
1870
  } else if (!frontendOnly && !backendDir) console.warn(chalk.yellow(" ⚠ No backend/ directory found, skipping backend."));
1851
1871
  if (!backendOnly && frontendDir && (frontendOnly || !backendDir)) startFrontend(null);
1872
+ else if (!backendOnly && !frontendDir && staticShape.servedByBackend?.length) for (const app of staticShape.servedByBackend) console.log(chalk.gray(` Static app "${app.appName}" has no build step: the backend serves it at ${app.path}.`));
1852
1873
  else if (!backendOnly && !frontendDir && declaresStaticApp) console.warn(chalk.yellow(" ⚠ No frontend/ directory found, skipping frontend."));
1853
1874
  if (children.length === 0) {
1854
1875
  console.error(chalk.red(" ✗ Nothing to start. Check your project structure."));
@@ -1949,4 +1970,4 @@ ${chalk.green.bold("Description")}
1949
1970
  //#endregion
1950
1971
  export { devCommand };
1951
1972
 
1952
- //# sourceMappingURL=dev-bj6dEeSQ.js.map
1973
+ //# sourceMappingURL=dev-C7n36E6f.js.map