From c5ef8d2b41b8cc8c10826defe8fb248e6a0a781b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 02:01:26 -0500 Subject: [PATCH 1/9] =?UTF-8?q?feat(packs):=20the=20config=20pack=20?= =?UTF-8?q?=E2=80=94=20settings,=20secrets=20and=20vaults=20(ADR-0069)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first independent pack, packs/config (metaobjects-config, 0.1.0 preview, unpublished, TypeScript only): - object.settings: a settings group whose fields are the settings (scalar field subtypes only); no source, so no table, query or route. - @secret, @envName and @phase (runtime | build): optional attributes on every field subtype, read on settings. - vault.infisical at the document root, with scope.env children (@project, @env) and an optional @defaultScope. - Generators: envExampleFile (.env.example), keyManifestFile (keys.manifest.json) and keysAxiTomlFile (.keys-axi.toml). Names only: the model holds no secret value. Problems the loader cannot see (a variable name used twice, a malformed @envName, a secret with a default, an array setting, a bad default scope, two scopes on one store environment, a vault with no scope) fail the run, all listed. The provider registers metamodel/config.json through the public provider contract; a test holds that lowering to core's own. Pinned vocabulary leaves core alone; five load fixtures run through the TypeScript pack-conformance entry point. check-pack-boundary: a pack id followed by a file extension is a file name, not the id (core's metaobjects-config.ts is not the config pack), with a test. --- bun.lock | 18 + packs/README.md | 2 +- packs/config/CHANGELOG.md | 16 + packs/config/README.md | 93 +++ .../expected-errors.json | 15 + .../input/meta.app.json | 5 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.app.json | 5 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.app.json | 3 + .../providers.json | 1 + .../expected.json | 56 ++ .../input/meta.app.json | 11 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.app.json | 6 + .../providers.json | 1 + .../config/fixtures/expected-vocabulary.json | 717 ++++++++++++++++++ packs/config/metamodel/config.json | 122 +++ packs/config/pack.json | 10 + packs/config/typescript/package.json | 51 ++ .../typescript/scripts/embed-definition.ts | 43 ++ .../src/config-definition.embedded.ts | 145 ++++ packs/config/typescript/src/constants.ts | 27 + packs/config/typescript/src/definition.ts | 114 +++ packs/config/typescript/src/generators.ts | 154 ++++ packs/config/typescript/src/index.ts | 30 + packs/config/typescript/src/nodes.ts | 24 + packs/config/typescript/src/provider.ts | 30 + packs/config/typescript/src/settings.ts | 171 +++++ .../config/typescript/test/definition.test.ts | 44 ++ .../config/typescript/test/generators.test.ts | 125 +++ packs/config/typescript/test/model.ts | 68 ++ packs/config/typescript/test/settings.test.ts | 92 +++ packs/config/typescript/tsconfig.json | 26 + .../config/typescript/tsconfig.typecheck.json | 9 + scripts/check-pack-boundary.ts | 4 +- scripts/packs.test.ts | 12 + 40 files changed, 2296 insertions(+), 2 deletions(-) create mode 100644 packs/config/CHANGELOG.md create mode 100644 packs/config/README.md create mode 100644 packs/config/fixtures/conformance/config-phase-unknown-value-fails/expected-errors.json create mode 100644 packs/config/fixtures/conformance/config-phase-unknown-value-fails/input/meta.app.json create mode 100644 packs/config/fixtures/conformance/config-phase-unknown-value-fails/providers.json create mode 100644 packs/config/fixtures/conformance/config-scope-missing-project-fails/expected-errors.json create mode 100644 packs/config/fixtures/conformance/config-scope-missing-project-fails/input/meta.app.json create mode 100644 packs/config/fixtures/conformance/config-scope-missing-project-fails/providers.json create mode 100644 packs/config/fixtures/conformance/config-scope-outside-vault-fails/expected-errors.json create mode 100644 packs/config/fixtures/conformance/config-scope-outside-vault-fails/input/meta.app.json create mode 100644 packs/config/fixtures/conformance/config-scope-outside-vault-fails/providers.json create mode 100644 packs/config/fixtures/conformance/config-settings-and-vault-success/expected.json create mode 100644 packs/config/fixtures/conformance/config-settings-and-vault-success/input/meta.app.json create mode 100644 packs/config/fixtures/conformance/config-settings-and-vault-success/providers.json create mode 100644 packs/config/fixtures/conformance/config-settings-object-field-fails/expected-errors.json create mode 100644 packs/config/fixtures/conformance/config-settings-object-field-fails/input/meta.app.json create mode 100644 packs/config/fixtures/conformance/config-settings-object-field-fails/providers.json create mode 100644 packs/config/fixtures/expected-vocabulary.json create mode 100644 packs/config/metamodel/config.json create mode 100644 packs/config/pack.json create mode 100644 packs/config/typescript/package.json create mode 100644 packs/config/typescript/scripts/embed-definition.ts create mode 100644 packs/config/typescript/src/config-definition.embedded.ts create mode 100644 packs/config/typescript/src/constants.ts create mode 100644 packs/config/typescript/src/definition.ts create mode 100644 packs/config/typescript/src/generators.ts create mode 100644 packs/config/typescript/src/index.ts create mode 100644 packs/config/typescript/src/nodes.ts create mode 100644 packs/config/typescript/src/provider.ts create mode 100644 packs/config/typescript/src/settings.ts create mode 100644 packs/config/typescript/test/definition.test.ts create mode 100644 packs/config/typescript/test/generators.test.ts create mode 100644 packs/config/typescript/test/model.ts create mode 100644 packs/config/typescript/test/settings.test.ts create mode 100644 packs/config/typescript/tsconfig.json create mode 100644 packs/config/typescript/tsconfig.typecheck.json diff --git a/bun.lock b/bun.lock index fa652b6f2..3489a65dd 100644 --- a/bun.lock +++ b/bun.lock @@ -150,6 +150,20 @@ "typescript": "^5.6.0", }, }, + "packs/config/typescript": { + "name": "@metaobjectsdev/pack-config", + "version": "0.1.0", + "devDependencies": { + "@metaobjectsdev/codegen-ts": "workspace:*", + "@metaobjectsdev/metadata": "workspace:*", + "bun-types": "latest", + "typescript": "^5.6.0", + }, + "peerDependencies": { + "@metaobjectsdev/codegen-ts": ">=1.3.0 <2.0.0", + "@metaobjectsdev/metadata": ">=1.3.0 <2.0.0", + }, + }, "server/typescript/packages/ai-runtime": { "name": "@metaobjectsdev/ai-runtime", "version": "1.3.0", @@ -752,6 +766,8 @@ "@metaobjectsdev/migrate-ts": ["@metaobjectsdev/migrate-ts@workspace:server/typescript/packages/migrate-ts"], + "@metaobjectsdev/pack-config": ["@metaobjectsdev/pack-config@workspace:packs/config/typescript"], + "@metaobjectsdev/react": ["@metaobjectsdev/react@workspace:client/web/packages/react"], "@metaobjectsdev/render": ["@metaobjectsdev/render@workspace:server/typescript/packages/render"], @@ -1578,6 +1594,8 @@ "@metaobjectsdev/migrate-ts/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@metaobjectsdev/pack-config/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@metaobjectsdev/react/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], "@metaobjectsdev/render/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], diff --git a/packs/README.md b/packs/README.md index ca3ae1e3a..f7774c4d1 100644 --- a/packs/README.md +++ b/packs/README.md @@ -2,7 +2,7 @@ A directory here is an **independent pack**: vocabulary, generators and runtime for a capability that is not part of core, built and versioned as if it were its own repository -([ADR-0069](../spec/decisions/ADR-0069-independent-packs.md)). None exists yet. +([ADR-0069](../spec/decisions/ADR-0069-independent-packs.md)). The first is `config` (settings and secrets). An independent pack is not in the default bundle. A project opts in by naming its provider. It is never in `fixtures/registry-conformance/expected-registry.json` and never moves diff --git a/packs/config/CHANGELOG.md b/packs/config/CHANGELOG.md new file mode 100644 index 000000000..69add7625 --- /dev/null +++ b/packs/config/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog — config pack (`metaobjects-config`) + +This pack's own changelog (ADR-0069). Its versions are its own; they never move core's +`metamodelVersion` or package versions. + +## [0.1.0] — unreleased (preview, unpublished) + +First version. TypeScript only. + +- `object.settings`: a settings group whose fields are the settings, scalar field subtypes only. +- `@secret`, `@envName` and `@phase` (`runtime` | `build`), optional attributes on every field + subtype, read on settings. +- `vault.infisical`, admitted at the document root, with `scope.env` children (`@project`, + `@env`) and an optional `@defaultScope`. +- Generators: `envExampleFile()` (`.env.example`), `keyManifestFile()` (`keys.manifest.json`) + and `keysAxiTomlFile()` (`.keys-axi.toml`). diff --git a/packs/config/README.md b/packs/config/README.md new file mode 100644 index 000000000..7cfe9405d --- /dev/null +++ b/packs/config/README.md @@ -0,0 +1,93 @@ +# The config pack (`metaobjects-config`) + +Settings, secrets and where secrets live, declared in the model, and the files a project +needs from them. An **independent pack** ([ADR-0069](../../spec/decisions/ADR-0069-independent-packs.md)): +version `0.1.0`, `preview`, unpublished, outside the default bundle and outside +`metamodelVersion`. A project opts in by naming its provider. + +| | | +|---|---| +| Provider id | `metaobjects-config` | +| Ports | **TypeScript** (`@metaobjectsdev/pack-config`). No other port carries it yet; there, a model that uses it fails to load with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR` naming what it does not know (ADR-0069, the port rule). | +| Requires | core `>=1.3.0 <2.0.0`; no other pack | + +It answers one question: *what does this application need to be told, and which of it is +secret?* It holds vocabulary and generators only, never the facts of an estate. Deployment +vocabulary (environments, deployments, platforms) belongs to the `systems` and `delivery` +packs, which refer to this pack's nodes by name. + +## Vocabulary + +| Node | What it is | +|---|---| +| `object.settings` | A settings group. Each field is one setting: its type, `@required`, `@default`, `@description` and validators work as on any field. Scalar field subtypes only (an environment variable holds one value). It has no source, so it generates no table, query or route. | +| `@secret` (field, boolean) | The value is a secret: it lives in a vault, never in the model or in generated output. A secret setting may not declare `@default`. | +| `@envName` (field, string) | The environment variable name, when the derived one is wrong. Derived: `_` in upper snake case, so `Database.url` is `DATABASE_URL` and `Database.poolSize` is `DATABASE_POOL_SIZE`. | +| `@phase` (field, `runtime` \| `build`) | When the setting is read. Absent means `runtime`; `build` is a build-time variable, such as a Docker build argument. | +| `vault.infisical` | An Infisical secret store, at the document root. `@defaultScope` names the scope used when no environment is given. | +| `scope.env` | Where the vault keeps one environment's secrets. Its name is the model's environment name; `@project` is the Infisical project; `@env` is Infisical's environment slug (absent: the scope's name). | + +The three field attributes are registered on every field subtype (a pack may add optional +attributes to a type it does not own, ADR-0050); the generators read them on settings only. +A secret is never referenced by value or by a separate node: it is read under its +environment name, in the scope the vault maps to the environment being deployed. + +```json +{ "metadata.root": { "package": "acme::app", "children": [ + { "object.settings": { "name": "Database", "children": [ + { "field.string": { "name": "url", "@required": true, "@secret": true } }, + { "field.int": { "name": "poolSize", "@default": 10, "@envName": "DB_POOL_SIZE" } } + ]}}, + { "vault.infisical": { "name": "keys", "@defaultScope": "dev", "children": [ + { "scope.env": { "name": "dev", "@project": "acme-app" } }, + { "scope.env": { "name": "production", "@project": "acme-app-prod", "@env": "prod" } } + ]}} +]}} +``` + +## Generators + +| Generator | Writes | Holds | +|---|---|---| +| `envExampleFile()` | `.env.example` | Every setting by name, grouped; the default of a non-secret setting; a comment line with type, required, secret and build-time | +| `keyManifestFile()` | `keys.manifest.json` | Every setting's name, model name, type, required, secret, phase and default, sorted by name; each vault and its scopes. What a deploy or doctor script compares a vault and a platform against | +| `keysAxiTomlFile({ vault? })` | `.keys-axi.toml` | The vault's backend, default scope and one `[environments.]` table per scope, the file `keys-axi` reads so `keys-axi run` needs no project flag. Name the vault when the model declares more than one | + +Each takes `path` and `target`. No value of a secret ever reaches their output: the model +holds none. A problem the loader cannot see (two settings on one variable name, a malformed +`@envName`, a secret with a default, an array setting, a `@defaultScope` naming no scope, two +scopes on one Infisical environment, a vault with no scope) fails the run with every such +problem listed, each naming its node. + +### Wiring + +These files belong at the project root, so give them a target whose `outDir` is `"."`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { configProvider, envExampleFile, keyManifestFile, keysAxiTomlFile } from "@metaobjectsdev/pack-config"; + +export default defineConfig({ + providers: [configProvider], + targets: { root: { outDir: "." } }, + generators: [ + envExampleFile({ target: "root" }), + keyManifestFile({ target: "root" }), + keysAxiTomlFile({ target: "root" }), + ], +}); +``` + +`meta gen` runs no generator over a model with no object at all, so a model that declares a +vault and no settings group writes nothing. + +## Checks + +``` +bun scripts/pack-vocabulary.ts config # the pinned vocabulary; leaves core alone +bun scripts/pack-conformance.ts config # fixtures/conformance/ through the TypeScript port +(cd packs/config/typescript && bun run typecheck && bun test) +``` + +`metamodel/config.json` is the vocabulary's definition; `typescript/src/config-definition.embedded.ts` +is a copy of it (`bun run embed` in `typescript/` rewrites it, and a test fails while it is stale). diff --git a/packs/config/fixtures/conformance/config-phase-unknown-value-fails/expected-errors.json b/packs/config/fixtures/conformance/config-phase-unknown-value-fails/expected-errors.json new file mode 100644 index 000000000..354131b94 --- /dev/null +++ b/packs/config/fixtures/conformance/config-phase-unknown-value-fails/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.app.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.settings'].children[0]['field.string']" + } + } + ], + "warnings": [] +} diff --git a/packs/config/fixtures/conformance/config-phase-unknown-value-fails/input/meta.app.json b/packs/config/fixtures/conformance/config-phase-unknown-value-fails/input/meta.app.json new file mode 100644 index 000000000..352355a12 --- /dev/null +++ b/packs/config/fixtures/conformance/config-phase-unknown-value-fails/input/meta.app.json @@ -0,0 +1,5 @@ +{ "metadata.root": { "package": "acme::app", "children": [ + { "object.settings": { "name": "Build", "children": [ + { "field.string": { "name": "commitSha", "@phase": "deploy" } } + ]}} +]}} diff --git a/packs/config/fixtures/conformance/config-phase-unknown-value-fails/providers.json b/packs/config/fixtures/conformance/config-phase-unknown-value-fails/providers.json new file mode 100644 index 000000000..e29456341 --- /dev/null +++ b/packs/config/fixtures/conformance/config-phase-unknown-value-fails/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-config"] diff --git a/packs/config/fixtures/conformance/config-scope-missing-project-fails/expected-errors.json b/packs/config/fixtures/conformance/config-scope-missing-project-fails/expected-errors.json new file mode 100644 index 000000000..dacab6d79 --- /dev/null +++ b/packs/config/fixtures/conformance/config-scope-missing-project-fails/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_MISSING_REQUIRED_ATTR", + "source": { + "format": "json", + "files": [ + "meta.app.json" + ], + "jsonPath": "$['metadata.root'].children[0]['vault.infisical'].children[0]['scope.env']" + } + } + ], + "warnings": [] +} diff --git a/packs/config/fixtures/conformance/config-scope-missing-project-fails/input/meta.app.json b/packs/config/fixtures/conformance/config-scope-missing-project-fails/input/meta.app.json new file mode 100644 index 000000000..234e44b49 --- /dev/null +++ b/packs/config/fixtures/conformance/config-scope-missing-project-fails/input/meta.app.json @@ -0,0 +1,5 @@ +{ "metadata.root": { "package": "acme::app", "children": [ + { "vault.infisical": { "name": "keys", "children": [ + { "scope.env": { "name": "dev" } } + ]}} +]}} diff --git a/packs/config/fixtures/conformance/config-scope-missing-project-fails/providers.json b/packs/config/fixtures/conformance/config-scope-missing-project-fails/providers.json new file mode 100644 index 000000000..e29456341 --- /dev/null +++ b/packs/config/fixtures/conformance/config-scope-missing-project-fails/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-config"] diff --git a/packs/config/fixtures/conformance/config-scope-outside-vault-fails/expected-errors.json b/packs/config/fixtures/conformance/config-scope-outside-vault-fails/expected-errors.json new file mode 100644 index 000000000..671f89ada --- /dev/null +++ b/packs/config/fixtures/conformance/config-scope-outside-vault-fails/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_CHILD_NOT_ALLOWED", + "source": { + "format": "json", + "files": [ + "meta.app.json" + ], + "jsonPath": "$['metadata.root']" + } + } + ], + "warnings": [] +} diff --git a/packs/config/fixtures/conformance/config-scope-outside-vault-fails/input/meta.app.json b/packs/config/fixtures/conformance/config-scope-outside-vault-fails/input/meta.app.json new file mode 100644 index 000000000..ea0ff3ff9 --- /dev/null +++ b/packs/config/fixtures/conformance/config-scope-outside-vault-fails/input/meta.app.json @@ -0,0 +1,3 @@ +{ "metadata.root": { "package": "acme::app", "children": [ + { "scope.env": { "name": "dev", "@project": "acme-app" } } +]}} diff --git a/packs/config/fixtures/conformance/config-scope-outside-vault-fails/providers.json b/packs/config/fixtures/conformance/config-scope-outside-vault-fails/providers.json new file mode 100644 index 000000000..e29456341 --- /dev/null +++ b/packs/config/fixtures/conformance/config-scope-outside-vault-fails/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-config"] diff --git a/packs/config/fixtures/conformance/config-settings-and-vault-success/expected.json b/packs/config/fixtures/conformance/config-settings-and-vault-success/expected.json new file mode 100644 index 000000000..99add2204 --- /dev/null +++ b/packs/config/fixtures/conformance/config-settings-and-vault-success/expected.json @@ -0,0 +1,56 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.settings": { + "name": "Database", + "@description": "The primary database.", + "children": [ + { + "field.string": { + "name": "url", + "@required": true, + "@secret": true + } + }, + { + "field.int": { + "name": "poolSize", + "@default": 10, + "@envName": "DB_POOL_SIZE" + } + }, + { + "field.string": { + "name": "commitSha", + "@phase": "build" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "keys", + "@defaultScope": "dev", + "children": [ + { + "scope.env": { + "name": "dev", + "@project": "acme-app" + } + }, + { + "scope.env": { + "name": "production", + "@env": "prod", + "@project": "acme-app-prod" + } + } + ] + } + } + ] + } +} diff --git a/packs/config/fixtures/conformance/config-settings-and-vault-success/input/meta.app.json b/packs/config/fixtures/conformance/config-settings-and-vault-success/input/meta.app.json new file mode 100644 index 000000000..2e9aa827f --- /dev/null +++ b/packs/config/fixtures/conformance/config-settings-and-vault-success/input/meta.app.json @@ -0,0 +1,11 @@ +{ "metadata.root": { "package": "acme::app", "children": [ + { "object.settings": { "name": "Database", "@description": "The primary database.", "children": [ + { "field.string": { "name": "url", "@required": true, "@secret": true } }, + { "field.int": { "name": "poolSize", "@default": 10, "@envName": "DB_POOL_SIZE" } }, + { "field.string": { "name": "commitSha", "@phase": "build" } } + ]}}, + { "vault.infisical": { "name": "keys", "@defaultScope": "dev", "children": [ + { "scope.env": { "name": "dev", "@project": "acme-app" } }, + { "scope.env": { "name": "production", "@project": "acme-app-prod", "@env": "prod" } } + ]}} +]}} diff --git a/packs/config/fixtures/conformance/config-settings-and-vault-success/providers.json b/packs/config/fixtures/conformance/config-settings-and-vault-success/providers.json new file mode 100644 index 000000000..e29456341 --- /dev/null +++ b/packs/config/fixtures/conformance/config-settings-and-vault-success/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-config"] diff --git a/packs/config/fixtures/conformance/config-settings-object-field-fails/expected-errors.json b/packs/config/fixtures/conformance/config-settings-object-field-fails/expected-errors.json new file mode 100644 index 000000000..972f13246 --- /dev/null +++ b/packs/config/fixtures/conformance/config-settings-object-field-fails/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_CHILD_NOT_ALLOWED", + "source": { + "format": "json", + "files": [ + "meta.app.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.settings']" + } + } + ], + "warnings": [] +} diff --git a/packs/config/fixtures/conformance/config-settings-object-field-fails/input/meta.app.json b/packs/config/fixtures/conformance/config-settings-object-field-fails/input/meta.app.json new file mode 100644 index 000000000..6f7bb2c8a --- /dev/null +++ b/packs/config/fixtures/conformance/config-settings-object-field-fails/input/meta.app.json @@ -0,0 +1,6 @@ +{ "metadata.root": { "package": "acme::app", "children": [ + { "object.value": { "name": "Endpoint", "children": [ { "field.string": { "name": "host" } } ]}}, + { "object.settings": { "name": "Api", "children": [ + { "field.object": { "name": "endpoint", "@objectRef": "Endpoint" } } + ]}} +]}} diff --git a/packs/config/fixtures/conformance/config-settings-object-field-fails/providers.json b/packs/config/fixtures/conformance/config-settings-object-field-fails/providers.json new file mode 100644 index 000000000..e29456341 --- /dev/null +++ b/packs/config/fixtures/conformance/config-settings-object-field-fails/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-config"] diff --git a/packs/config/fixtures/expected-vocabulary.json b/packs/config/fixtures/expected-vocabulary.json new file mode 100644 index 000000000..aadfd7af9 --- /dev/null +++ b/packs/config/fixtures/expected-vocabulary.json @@ -0,0 +1,717 @@ +{ + "pack": "metaobjects-config", + "types": [ + { + "type": "object", + "subType": "settings", + "description": "A settings group: one thing an application must be told to run (a database connection, an LLM provider, a payment account). Each field is one setting, named in the environment as _ in upper snake case (Database.url is DATABASE_URL) unless the field's @envName says otherwise. A field marked @secret has its value in a vault and never in the model, the repository or generated output. A settings group has no source, so it generates no table, query or route (core's entity generator types it as it does a value object); the configuration generators read it (.env.example, the key manifest, .keys-axi.toml).", + "whenToUse": "Every environment variable, secret or build argument an application reads. Group the ones that change together; a setting is a field, so it carries its type, @required, @default and validators the same way an entity field does.", + "attrs": [], + "children": [ + { + "childType": "field", + "childSubType": [ + "string", + "int", + "long", + "double", + "float", + "decimal", + "boolean", + "date", + "time", + "timestamp", + "enum", + "uuid", + "uri", + "inet", + "duration" + ], + "childName": "*", + "min": 0, + "max": null + }, + { + "childType": "validator", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "scope", + "subType": "env", + "description": "Where a vault keeps one environment's secrets. Its name is the environment's name in the model (the same name a deployment's environment uses), so a deployment finds its scope by name.", + "whenToUse": "One per environment that reads secrets from the vault: dev, staging, production.", + "attrs": [ + { + "name": "env", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The store's environment slug (Infisical's dev, staging, prod). Absent, the scope's own name." + }, + { + "name": "project", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The store's own name for the place: for Infisical, the project slug or id." + } + ], + "children": [] + }, + { + "type": "vault", + "subType": "infisical", + "description": "An Infisical secret store. It names where the values of @secret settings live, per environment, through its scope.env children; the values never appear in the model. The reference to an entry is derived: a secret setting is read under its environment name, in the scope the vault maps to the environment being deployed.", + "whenToUse": "A project whose secrets live in Infisical. The .keys-axi.toml generator writes its scopes for keys-axi, so `keys-axi run` needs no project flag.", + "attrs": [ + { + "name": "defaultScope", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The name of the scope.env child used when no environment is given: written to .keys-axi.toml as its top-level scope and default_environment." + } + ], + "children": [ + { + "childType": "scope", + "childSubType": "env", + "childName": "*", + "min": 0, + "max": null + } + ] + } + ], + "extends": [ + { + "type": "field", + "subType": "base", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "boolean", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "currency", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "date", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "decimal", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "double", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "duration", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "enum", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "float", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "inet", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "int", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "long", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "map", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "object", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "string", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "time", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "timestamp", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "uri", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "field", + "subType": "uuid", + "attrs": [ + { + "name": "envName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "name": "phase", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + }, + { + "name": "secret", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + } + ], + "children": [] + }, + { + "type": "metadata", + "subType": "root", + "attrs": [], + "children": [ + { + "childType": "vault", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + } + ], + "commonAttrs": [], + "defaultSubTypes": {} +} diff --git a/packs/config/metamodel/config.json b/packs/config/metamodel/config.json new file mode 100644 index 000000000..8eabb939f --- /dev/null +++ b/packs/config/metamodel/config.json @@ -0,0 +1,122 @@ +{ + "provider": "metaobjects-config", + "types": [ + { + "type": "object", + "subType": "settings", + "description": "A settings group: one thing an application must be told to run (a database connection, an LLM provider, a payment account). Each field is one setting, named in the environment as _ in upper snake case (Database.url is DATABASE_URL) unless the field's @envName says otherwise. A field marked @secret has its value in a vault and never in the model, the repository or generated output. A settings group has no source, so it generates no table, query or route (core's entity generator types it as it does a value object); the configuration generators read it (.env.example, the key manifest, .keys-axi.toml).", + "whenToUse": "Every environment variable, secret or build argument an application reads. Group the ones that change together; a setting is a field, so it carries its type, @required, @default and validators the same way an entity field does.", + "children": [ + { + "type": "field", + "subType": ["string", "int", "long", "double", "float", "decimal", "boolean", "date", "time", "timestamp", "enum", "uuid", "uri", "inet", "duration"], + "name": "*", + "min": 0, + "max": null, + "description": "One setting. Only scalar field subtypes: an environment variable holds one value." + }, + { + "type": "validator", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "vault", + "subType": "infisical", + "description": "An Infisical secret store. It names where the values of @secret settings live, per environment, through its scope.env children; the values never appear in the model. The reference to an entry is derived: a secret setting is read under its environment name, in the scope the vault maps to the environment being deployed.", + "whenToUse": "A project whose secrets live in Infisical. The .keys-axi.toml generator writes its scopes for keys-axi, so `keys-axi run` needs no project flag.", + "children": [ + { + "type": "scope", + "subType": "env", + "name": "*", + "min": 0, + "max": null, + "description": "The vault's place for one environment. A vault with none is refused by the generators that read it." + }, + { + "type": "attr", + "subType": "string", + "name": "defaultScope", + "min": 0, + "max": 1, + "description": "The name of the scope.env child used when no environment is given: written to .keys-axi.toml as its top-level scope and default_environment." + } + ] + }, + { + "type": "scope", + "subType": "env", + "description": "Where a vault keeps one environment's secrets. Its name is the environment's name in the model (the same name a deployment's environment uses), so a deployment finds its scope by name.", + "whenToUse": "One per environment that reads secrets from the vault: dev, staging, production.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "project", + "min": 1, + "max": 1, + "description": "The store's own name for the place: for Infisical, the project slug or id." + }, + { + "type": "attr", + "subType": "string", + "name": "env", + "min": 0, + "max": 1, + "description": "The store's environment slug (Infisical's dev, staging, prod). Absent, the scope's own name." + } + ] + } + ], + "extends": [ + { + "type": "metadata", + "subType": "root", + "children": [ + { + "type": "vault", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "field", + "subType": "*", + "children": [ + { + "type": "attr", + "subType": "boolean", + "name": "secret", + "min": 0, + "max": 1, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + }, + { + "type": "attr", + "subType": "string", + "name": "envName", + "min": 0, + "max": 1, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "type": "attr", + "subType": "string", + "name": "phase", + "min": 0, + "max": 1, + "allowedValues": ["runtime", "build"], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + } + ] + } + ] +} diff --git a/packs/config/pack.json b/packs/config/pack.json new file mode 100644 index 000000000..afb705d2e --- /dev/null +++ b/packs/config/pack.json @@ -0,0 +1,10 @@ +{ + "id": "metaobjects-config", + "version": "0.1.0", + "stability": "preview", + "description": "Settings and secrets: object.settings, the @secret / @envName / @phase field attributes, vault.infisical with its scopes, and generators for .env.example, the key manifest and .keys-axi.toml.", + "requires": { "metamodel": ">=1.3 <2", "packs": {} }, + "ports": { + "typescript": { "package": "@metaobjectsdev/pack-config", "core": ">=1.3.0 <2.0.0", "publish": false } + } +} diff --git a/packs/config/typescript/package.json b/packs/config/typescript/package.json new file mode 100644 index 000000000..91b7b6b3b --- /dev/null +++ b/packs/config/typescript/package.json @@ -0,0 +1,51 @@ +{ + "name": "@metaobjectsdev/pack-config", + "version": "0.1.0", + "private": true, + "description": "MetaObjects config pack: settings groups, secret settings, vaults, and the .env.example, key manifest and .keys-axi.toml generators.", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "bun": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "files": [ + "dist", + "src", + "README.md" + ], + "scripts": { + "build": "tsc -p .", + "typecheck": "tsc -p tsconfig.typecheck.json", + "embed": "bun scripts/embed-definition.ts" + }, + "license": "Apache-2.0", + "author": "MetaObjects contributors", + "homepage": "https://metaobjects.dev", + "repository": { + "type": "git", + "url": "https://github.com/metaobjectsdev/metaobjects.git", + "directory": "packs/config/typescript" + }, + "keywords": [ + "metaobjects", + "settings", + "secrets", + "infisical", + "env" + ], + "peerDependencies": { + "@metaobjectsdev/metadata": ">=1.3.0 <2.0.0", + "@metaobjectsdev/codegen-ts": ">=1.3.0 <2.0.0" + }, + "devDependencies": { + "@metaobjectsdev/metadata": "workspace:*", + "@metaobjectsdev/codegen-ts": "workspace:*", + "bun-types": "latest", + "typescript": "^5.6.0" + } +} diff --git a/packs/config/typescript/scripts/embed-definition.ts b/packs/config/typescript/scripts/embed-definition.ts new file mode 100644 index 000000000..9935e8189 --- /dev/null +++ b/packs/config/typescript/scripts/embed-definition.ts @@ -0,0 +1,43 @@ +#!/usr/bin/env bun +/** + * Embed the pack's vocabulary definition (packs/config/metamodel/config.json) as + * src/config-definition.embedded.ts, so the provider registers it wherever the pack's + * own files are not on disk (a built or bundled install). The JSON is the source; the + * test `definition.test.ts` fails when the embedded copy is stale. + * + * bun run embed # rewrite the embedded copy + */ +import { readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +export const DEFINITION_JSON = join(here, "..", "..", "metamodel", "config.json"); +export const EMBEDDED_TS = join(here, "..", "src", "config-definition.embedded.ts"); + +export function renderEmbedded(json: string): string { + const body = JSON.stringify(JSON.parse(json), null, 2); + return [ + "// AUTO-GENERATED by packs/config/typescript/scripts/embed-definition.ts — DO NOT EDIT.", + "// Source: packs/config/metamodel/config.json. Regenerate: bun run embed (in packs/config/typescript).", + 'import type { PackDefinition } from "./definition.js";', + "", + `export const CONFIG_DEFINITION: PackDefinition = ${body};`, + "", + ].join("\n"); +} + +if (import.meta.main) { + const next = renderEmbedded(readFileSync(DEFINITION_JSON, "utf8")); + let current = ""; + try { + current = readFileSync(EMBEDDED_TS, "utf8"); + } catch { + // first run + } + if (current === next) console.log("config definition: embedded copy unchanged"); + else { + writeFileSync(EMBEDDED_TS, next); + console.log("config definition: wrote src/config-definition.embedded.ts"); + } +} diff --git a/packs/config/typescript/src/config-definition.embedded.ts b/packs/config/typescript/src/config-definition.embedded.ts new file mode 100644 index 000000000..4d0a10996 --- /dev/null +++ b/packs/config/typescript/src/config-definition.embedded.ts @@ -0,0 +1,145 @@ +// AUTO-GENERATED by packs/config/typescript/scripts/embed-definition.ts — DO NOT EDIT. +// Source: packs/config/metamodel/config.json. Regenerate: bun run embed (in packs/config/typescript). +import type { PackDefinition } from "./definition.js"; + +export const CONFIG_DEFINITION: PackDefinition = { + "provider": "metaobjects-config", + "types": [ + { + "type": "object", + "subType": "settings", + "description": "A settings group: one thing an application must be told to run (a database connection, an LLM provider, a payment account). Each field is one setting, named in the environment as _ in upper snake case (Database.url is DATABASE_URL) unless the field's @envName says otherwise. A field marked @secret has its value in a vault and never in the model, the repository or generated output. A settings group has no source, so it generates no table, query or route (core's entity generator types it as it does a value object); the configuration generators read it (.env.example, the key manifest, .keys-axi.toml).", + "whenToUse": "Every environment variable, secret or build argument an application reads. Group the ones that change together; a setting is a field, so it carries its type, @required, @default and validators the same way an entity field does.", + "children": [ + { + "type": "field", + "subType": [ + "string", + "int", + "long", + "double", + "float", + "decimal", + "boolean", + "date", + "time", + "timestamp", + "enum", + "uuid", + "uri", + "inet", + "duration" + ], + "name": "*", + "min": 0, + "max": null, + "description": "One setting. Only scalar field subtypes: an environment variable holds one value." + }, + { + "type": "validator", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "vault", + "subType": "infisical", + "description": "An Infisical secret store. It names where the values of @secret settings live, per environment, through its scope.env children; the values never appear in the model. The reference to an entry is derived: a secret setting is read under its environment name, in the scope the vault maps to the environment being deployed.", + "whenToUse": "A project whose secrets live in Infisical. The .keys-axi.toml generator writes its scopes for keys-axi, so `keys-axi run` needs no project flag.", + "children": [ + { + "type": "scope", + "subType": "env", + "name": "*", + "min": 0, + "max": null, + "description": "The vault's place for one environment. A vault with none is refused by the generators that read it." + }, + { + "type": "attr", + "subType": "string", + "name": "defaultScope", + "min": 0, + "max": 1, + "description": "The name of the scope.env child used when no environment is given: written to .keys-axi.toml as its top-level scope and default_environment." + } + ] + }, + { + "type": "scope", + "subType": "env", + "description": "Where a vault keeps one environment's secrets. Its name is the environment's name in the model (the same name a deployment's environment uses), so a deployment finds its scope by name.", + "whenToUse": "One per environment that reads secrets from the vault: dev, staging, production.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "project", + "min": 1, + "max": 1, + "description": "The store's own name for the place: for Infisical, the project slug or id." + }, + { + "type": "attr", + "subType": "string", + "name": "env", + "min": 0, + "max": 1, + "description": "The store's environment slug (Infisical's dev, staging, prod). Absent, the scope's own name." + } + ] + } + ], + "extends": [ + { + "type": "metadata", + "subType": "root", + "children": [ + { + "type": "vault", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "field", + "subType": "*", + "children": [ + { + "type": "attr", + "subType": "boolean", + "name": "secret", + "min": 0, + "max": 1, + "description": "On a setting (a field of an object.settings): the value is a secret. It lives in a vault, is never printed, and generated files carry its name only. A secret setting may not declare @default. Read only on settings." + }, + { + "type": "attr", + "subType": "string", + "name": "envName", + "min": 0, + "max": 1, + "description": "On a setting: its environment variable name, when the derived _ is wrong (DB_POOL_SIZE rather than DATABASE_POOL_SIZE). Upper case letters, digits and underscores, not starting with a digit. Read only on settings." + }, + { + "type": "attr", + "subType": "string", + "name": "phase", + "min": 0, + "max": 1, + "allowedValues": [ + "runtime", + "build" + ], + "description": "On a setting: when the application reads it. runtime (the meaning when absent) is read by the running process; build is a build-time variable, such as a Docker build argument. Read only on settings." + } + ] + } + ] +}; diff --git a/packs/config/typescript/src/constants.ts b/packs/config/typescript/src/constants.ts new file mode 100644 index 000000000..955e26dab --- /dev/null +++ b/packs/config/typescript/src/constants.ts @@ -0,0 +1,27 @@ +/** The config pack's metamodel strings: one definition each (the project's constants rule). */ + +/** The provider id; pack.json's `id`. */ +export const CONFIG_PROVIDER_ID = "metaobjects-config"; + +export const OBJECT_SUBTYPE_SETTINGS = "settings"; + +export const TYPE_VAULT = "vault"; +export const VAULT_SUBTYPE_INFISICAL = "infisical"; +export const VAULT_ATTR_DEFAULT_SCOPE = "defaultScope"; + +export const TYPE_SCOPE = "scope"; +export const SCOPE_SUBTYPE_ENV = "env"; +export const SCOPE_ATTR_PROJECT = "project"; +export const SCOPE_ATTR_ENV = "env"; + +export const FIELD_ATTR_SECRET = "secret"; +export const FIELD_ATTR_ENV_NAME = "envName"; +export const FIELD_ATTR_PHASE = "phase"; + +export const PHASE_RUNTIME = "runtime"; +export const PHASE_BUILD = "build"; +export const PHASES = [PHASE_RUNTIME, PHASE_BUILD] as const; +export type Phase = (typeof PHASES)[number]; + +/** What an environment variable name may be: upper case, digits and underscores, no leading digit. */ +export const ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]*$/; diff --git a/packs/config/typescript/src/definition.ts b/packs/config/typescript/src/definition.ts new file mode 100644 index 000000000..12d73379f --- /dev/null +++ b/packs/config/typescript/src/definition.ts @@ -0,0 +1,114 @@ +/** + * Register a pack's vocabulary definition (the spec/metamodel/*.json format, ADR-0069's + * `metamodel/*.json`) through the public provider contract: `registry.register` for each + * type the pack owns, `registry.extend` for each rule it adds to a type it does not. + * + * Core lowers its own bundled definitions the same way (provider-data.ts) but does not + * export that path, and a pack may lean only on what core's package version promises + * (ADR-0069 §5). `definition.test.ts` holds this lowering to core's: the two give the + * same registry manifest for this pack's file. + */ +import { TypeId, type AttrSchema, type ChildRule, type MetaData, type TypeRegistry } from "@metaobjectsdev/metadata"; + +type AttrValue = NonNullable; +type ValueType = NonNullable; + +/** One `children` entry: an attribute when `type` is `"attr"`, otherwise a child rule. */ +export interface PackChildDef { + readonly type: string; + readonly subType?: string | readonly string[]; + readonly name: string; + readonly min: number; + readonly max: number | null; + readonly named?: boolean; + readonly description?: string; + readonly default?: unknown; + readonly allowedValues?: readonly unknown[]; + readonly isArray?: boolean; +} + +export interface PackTypeDef { + readonly type: string; + readonly subType: string; + readonly description: string; + readonly whenToUse?: string; + readonly children: readonly PackChildDef[]; +} + +export interface PackExtendDef { + readonly type: string; + /** A subtype, a list of them, or `"*"` for every subtype registered when the pack is composed. */ + readonly subType: string | readonly string[]; + readonly children: readonly PackChildDef[]; +} + +export interface PackDefinition { + readonly provider: string; + readonly types: readonly PackTypeDef[]; + readonly extends?: readonly PackExtendDef[]; +} + +export type PackFactory = (typeId: TypeId, name: string) => MetaData; + +const ATTR = "attr"; +const WILDCARD = "*"; + +function toAttr(owner: string, c: PackChildDef): AttrSchema { + if (Array.isArray(c.subType)) throw new Error(`${owner}: attr @${c.name} declares a list subType; an attr has one value type`); + return { + name: c.name, + ...(c.subType !== undefined ? { valueType: c.subType as ValueType } : {}), + ...(c.isArray !== undefined ? { isArray: c.isArray } : {}), + required: c.min >= 1, + ...(c.default !== undefined ? { default: c.default as AttrValue } : {}), + ...(c.allowedValues !== undefined ? { allowedValues: c.allowedValues as readonly AttrValue[] } : {}), + description: c.description ?? "", + }; +} + +function toRule(c: PackChildDef): ChildRule { + return { + childType: c.type, + childSubType: c.subType ?? WILDCARD, + childName: c.name, + min: c.min, + max: c.max, + ...(c.named !== undefined ? { named: c.named } : {}), + }; +} + +function split(owner: string, children: readonly PackChildDef[]): { attributes: AttrSchema[]; childRules: ChildRule[] } { + const attributes: AttrSchema[] = []; + const childRules: ChildRule[] = []; + for (const c of children) { + if (c.type === ATTR) attributes.push(toAttr(owner, c)); + else childRules.push(toRule(c)); + } + return { attributes, childRules }; +} + +/** Register every type `def` owns, with the factory `factories` names for it, then apply its `extends`. */ +export function registerDefinition( + registry: TypeRegistry, + def: PackDefinition, + factories: Readonly>, +): void { + for (const t of def.types) { + const key = `${t.type}.${t.subType}`; + const factory = factories[key]; + if (factory === undefined) throw new Error(`${def.provider}: no factory for ${key}`); + registry.register({ + typeId: new TypeId(t.type, t.subType), + description: t.description, + ...(t.whenToUse !== undefined ? { whenToUse: t.whenToUse } : {}), + factory, + ...split(key, t.children), + }); + } + for (const ext of def.extends ?? []) { + const owner = `${ext.type}.${Array.isArray(ext.subType) ? ext.subType.join(",") : ext.subType}`; + const additions = split(owner, ext.children); + const subTypes = ext.subType === WILDCARD ? registry.allSubTypesOf(ext.type) : Array.isArray(ext.subType) ? ext.subType : [ext.subType as string]; + for (const subType of subTypes) registry.extend(ext.type, subType, additions); + } +} diff --git a/packs/config/typescript/src/generators.ts b/packs/config/typescript/src/generators.ts new file mode 100644 index 000000000..e5dca1434 --- /dev/null +++ b/packs/config/typescript/src/generators.ts @@ -0,0 +1,154 @@ +/** + * The config pack's generators. Each writes one whole-model file and stops: they talk to + * no vault and no platform, and no value of a secret setting ever reaches their output + * (the model holds none). + * + * - `envExampleFile()` `.env.example`: every setting's name, with its default when it is + * not secret, and a comment line saying what it is. + * - `keyManifestFile()` `keys.manifest.json`: the same names, typed, plus each vault's + * scopes. What a deploy or doctor script compares a vault and a + * platform against. + * - `keysAxiTomlFile()` `.keys-axi.toml`: the Infisical vault's scope per environment, in + * the file `keys-axi` reads, so `keys-axi run` needs no project flag. + * + * Paths are relative to the generator's target. These files belong at the project root, + * so wire them to a target whose `outDir` is `"."` (README, "Wiring"). + */ +import type { EmittedFile, Generator, GenContext } from "@metaobjectsdev/codegen-ts"; +import { PHASE_BUILD, VAULT_SUBTYPE_INFISICAL } from "./constants.js"; +import { readSettings, readVaults, type Setting, type Vault } from "./settings.js"; + +const PACKAGE = "@metaobjectsdev/pack-config"; + +export interface ConfigGeneratorOptions { + /** The output path, relative to the target. */ + readonly path?: string; + /** The named output target (`targets` in metaobjects.config.ts). Default: `"default"`. */ + readonly target?: string; +} + +export interface KeysAxiTomlOptions extends ConfigGeneratorOptions { + /** The vault to write, by name, when the model declares more than one. */ + readonly vault?: string; +} + +function header(generator: string, comment: string): string { + return `${comment} @generated by ${PACKAGE} (${generator}). Do not edit: change the model and run \`meta gen\`.`; +} + +function generator(name: string, opts: ConfigGeneratorOptions, generate: (ctx: GenContext) => EmittedFile[]): Generator { + return { name, ...(opts.target !== undefined ? { target: opts.target } : {}), generate }; +} + +// ── .env.example ───────────────────────────────────────────────────────────── + +/** A value as dotenv writes it: bare when that is unambiguous, else double-quoted. */ +export function dotenvValue(v: string): string { + return /^[^\s"'#\\$`]*$/.test(v) ? v : `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, "\\$").replace(/`/g, "\\`")}"`; +} + +function describe(s: Setting): string { + const facts = [s.type, s.required ? "required" : "optional"]; + if (s.secret) facts.push("secret: the value lives in the vault"); + if (s.phase === PHASE_BUILD) facts.push("build-time"); + const what = s.description === undefined ? "" : ` — ${s.description.replace(/\s+/g, " ").trim()}`; + return `# ${s.envName}: ${facts.join(", ")}${what}`; +} + +export function renderEnvExample(ctx: GenContext): string | undefined { + const groups = readSettings(ctx.entities.filter(ctx.matches)).filter((g) => g.settings.length > 0); + if (groups.length === 0) return undefined; + const lines = [ + header("env-example", "#"), + "# Every setting the application reads. Secret settings are listed by name only.", + ]; + for (const g of groups) { + lines.push("", `# ── ${g.name} (${g.key}) ──`); + if (g.description !== undefined) lines.push(`# ${g.description.replace(/\s+/g, " ").trim()}`); + for (const s of g.settings) lines.push(describe(s), `${s.envName}=${s.default === undefined ? "" : dotenvValue(s.default)}`); + } + return `${lines.join("\n")}\n`; +} + +export function envExampleFile(opts: ConfigGeneratorOptions = {}): Generator { + return generator("env-example", opts, (ctx) => { + const content = renderEnvExample(ctx); + return content === undefined ? [] : [{ path: opts.path ?? ".env.example", content }]; + }); +} + +// ── keys.manifest.json ────────────────────────────────────────────────────── + +export function renderKeyManifest(ctx: GenContext): string | undefined { + const settings = readSettings(ctx.entities.filter(ctx.matches)).flatMap((g) => g.settings); + const vaults = readVaults(ctx.loadedRoot); + if (settings.length === 0 && vaults.length === 0) return undefined; + const manifest = { + generatedBy: `${PACKAGE} (key-manifest)`, + settings: [...settings].sort((a, b) => (a.envName < b.envName ? -1 : a.envName > b.envName ? 1 : 0)), + vaults: vaults.map((v) => ({ + name: v.name, + key: v.key, + product: v.product, + ...(v.defaultScope !== undefined ? { defaultScope: v.defaultScope.name } : {}), + scopes: v.scopes, + })), + }; + return `${JSON.stringify(manifest, null, 2)}\n`; +} + +export function keyManifestFile(opts: ConfigGeneratorOptions = {}): Generator { + return generator("key-manifest", opts, (ctx) => { + const content = renderKeyManifest(ctx); + return content === undefined ? [] : [{ path: opts.path ?? "keys.manifest.json", content }]; + }); +} + +// ── .keys-axi.toml ────────────────────────────────────────────────────────── + +/** A TOML basic string. */ +function tomlString(v: string): string { + return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +/** A TOML key: bare when it may be, else quoted. */ +function tomlKey(k: string): string { + return /^[A-Za-z0-9_-]+$/.test(k) ? k : tomlString(k); +} + +function pickVault(vaults: readonly Vault[], wanted: string | undefined): Vault | undefined { + if (wanted !== undefined) { + const v = vaults.find((x) => x.name === wanted || x.key === wanted); + if (v === undefined) throw new Error(`keys-axi-toml: no vault named "${wanted}" (the model declares: ${vaults.map((x) => x.key).join(", ") || "none"})`); + return v; + } + if (vaults.length > 1) { + throw new Error(`keys-axi-toml: the model declares ${vaults.length} vaults (${vaults.map((x) => x.key).join(", ")}); name one with keysAxiTomlFile({ vault })`); + } + return vaults[0]; +} + +export function renderKeysAxiToml(vault: Vault): string { + if (vault.product !== VAULT_SUBTYPE_INFISICAL) { + throw new Error(`keys-axi-toml: vault ${vault.key} is vault.${vault.product}; keys-axi reads only vault.${VAULT_SUBTYPE_INFISICAL} from this generator`); + } + const lines = [header("keys-axi-toml", "#"), `# From vault.${vault.product} ${vault.key}.`, `backend = ${tomlString(vault.product)}`]; + if (vault.defaultScope !== undefined) { + lines.push(`scope = ${tomlString(vault.defaultScope.project)}`, `default_environment = ${tomlString(vault.defaultScope.env)}`); + } + for (const s of vault.scopes) { + lines.push("", `# ${s.name}`, `[environments.${tomlKey(s.env)}]`, `scope = ${tomlString(s.project)}`); + } + return `${lines.join("\n")}\n`; +} + +export function keysAxiTomlFile(opts: KeysAxiTomlOptions = {}): Generator { + return generator("keys-axi-toml", opts, (ctx) => { + const vault = pickVault(readVaults(ctx.loadedRoot), opts.vault); + if (vault === undefined) { + ctx.warn("keys-axi-toml: the model declares no vault, so there is no .keys-axi.toml to write"); + return []; + } + return [{ path: opts.path ?? ".keys-axi.toml", content: renderKeysAxiToml(vault) }]; + }); +} diff --git a/packs/config/typescript/src/index.ts b/packs/config/typescript/src/index.ts new file mode 100644 index 000000000..b82130b7e --- /dev/null +++ b/packs/config/typescript/src/index.ts @@ -0,0 +1,30 @@ +/** + * @metaobjectsdev/pack-config — the config pack (ADR-0069): settings, secrets and vaults. + * + * import { configProvider, envExampleFile, keyManifestFile, keysAxiTomlFile } from "@metaobjectsdev/pack-config"; + * export default defineConfig({ providers: [configProvider], generators: [envExampleFile(), ...] }); + */ +export { configProvider, configProvider as provider } from "./provider.js"; +export * from "./constants.js"; +export { MetaVault, MetaVaultScope, isVault, isVaultScope } from "./nodes.js"; +export { + ConfigModelError, + deriveEnvName, + isSettings, + readSettings, + readVaults, + type Setting, + type SettingsGroup, + type Vault, + type VaultScope, +} from "./settings.js"; +export { + envExampleFile, + keyManifestFile, + keysAxiTomlFile, + renderEnvExample, + renderKeyManifest, + renderKeysAxiToml, + type ConfigGeneratorOptions, + type KeysAxiTomlOptions, +} from "./generators.js"; diff --git a/packs/config/typescript/src/nodes.ts b/packs/config/typescript/src/nodes.ts new file mode 100644 index 000000000..76baa2050 --- /dev/null +++ b/packs/config/typescript/src/nodes.ts @@ -0,0 +1,24 @@ +/** + * The node classes for the types this pack owns outright. A settings group is a plain + * `MetaObject` (core's class), so every object-walking reader in core sees it as one. + * + * Code outside this package never `instanceof`s these: two copies of the pack in one + * process would make that false for a real node. Readers go by type and subtype + * (`isVault`, `isVaultScope`). + */ +import { MetaData } from "@metaobjectsdev/metadata"; +import { SCOPE_SUBTYPE_ENV, TYPE_SCOPE, TYPE_VAULT } from "./constants.js"; + +/** A secret store: `vault.`. */ +export class MetaVault extends MetaData {} + +/** One environment's place in a vault: `scope.env`. */ +export class MetaVaultScope extends MetaData {} + +export function isVault(node: MetaData): boolean { + return node.typeId.type === TYPE_VAULT; +} + +export function isVaultScope(node: MetaData): boolean { + return node.typeId.type === TYPE_SCOPE && node.typeId.subType === SCOPE_SUBTYPE_ENV; +} diff --git a/packs/config/typescript/src/provider.ts b/packs/config/typescript/src/provider.ts new file mode 100644 index 000000000..b6293630e --- /dev/null +++ b/packs/config/typescript/src/provider.ts @@ -0,0 +1,30 @@ +/** + * The config pack's provider (ADR-0069): an independent pack, outside the default bundle. + * A project opts in by naming it (`defineConfig({ providers: [configProvider] })`). + * + * It owns `object.settings`, `vault.infisical` and `scope.env`, lets `metadata.root` hold a + * vault, and adds the optional `@secret`, `@envName` and `@phase` attributes to every field + * subtype registered when it is composed. Leave it out and all of these are unknown to the + * loader, which refuses a model that uses them by name. + */ +import { MetaObject, TYPE_OBJECT, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { CONFIG_DEFINITION } from "./config-definition.embedded.js"; +import { CONFIG_PROVIDER_ID, OBJECT_SUBTYPE_SETTINGS, SCOPE_SUBTYPE_ENV, TYPE_SCOPE, TYPE_VAULT, VAULT_SUBTYPE_INFISICAL } from "./constants.js"; +import { registerDefinition } from "./definition.js"; +import { MetaVault, MetaVaultScope } from "./nodes.js"; + +export const configProvider: MetaDataTypeProvider = { + id: CONFIG_PROVIDER_ID, + // After core-types: `field.*` in the definition's `extends` means the field subtypes + // registered by then. + dependencies: ["metaobjects-core-types"], + description: + "Settings and secrets (config pack): object.settings, @secret / @envName / @phase on fields, vault.infisical and scope.env.", + registerTypes(registry) { + registerDefinition(registry, CONFIG_DEFINITION, { + [`${TYPE_OBJECT}.${OBJECT_SUBTYPE_SETTINGS}`]: (typeId, name) => new MetaObject(typeId, name), + [`${TYPE_VAULT}.${VAULT_SUBTYPE_INFISICAL}`]: (typeId, name) => new MetaVault(typeId, name), + [`${TYPE_SCOPE}.${SCOPE_SUBTYPE_ENV}`]: (typeId, name) => new MetaVaultScope(typeId, name), + }); + }, +}; diff --git a/packs/config/typescript/src/settings.ts b/packs/config/typescript/src/settings.ts new file mode 100644 index 000000000..26bfbd92d --- /dev/null +++ b/packs/config/typescript/src/settings.ts @@ -0,0 +1,171 @@ +/** + * What the model says about settings and vaults, read once for every generator in the pack. + * + * Accessors are the resolving ones (`attr`, `fields`, `children`; ADR-0039), so a setting + * inherited through `extends` is read like one declared in place. Problems a loader cannot + * see (a name collision across groups, a secret with a default) are collected and thrown + * together, each naming the node, so one `meta gen` lists them all. + */ +import { TYPE_OBJECT, toSnakeCase, type AttrValue, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import { + ENV_NAME_PATTERN, + FIELD_ATTR_ENV_NAME, + FIELD_ATTR_PHASE, + FIELD_ATTR_SECRET, + OBJECT_SUBTYPE_SETTINGS, + PHASE_BUILD, + PHASE_RUNTIME, + SCOPE_ATTR_ENV, + SCOPE_ATTR_PROJECT, + VAULT_ATTR_DEFAULT_SCOPE, + type Phase, +} from "./constants.js"; +import { isVault, isVaultScope } from "./nodes.js"; + +const ATTR_REQUIRED = "required"; +const ATTR_DEFAULT = "default"; +const ATTR_DESCRIPTION = "description"; + +export interface Setting { + /** The environment variable: `@envName`, else `_` in upper snake case. */ + readonly envName: string; + /** `.`, the setting's name in the model. */ + readonly setting: string; + /** The field subtype: string, int, boolean, ... */ + readonly type: string; + readonly required: boolean; + readonly secret: boolean; + readonly phase: Phase; + /** The `@default`, as the text an environment variable would hold. Never set on a secret. */ + readonly default?: string; + readonly description?: string; +} + +export interface SettingsGroup { + readonly name: string; + readonly key: string; + readonly description?: string; + readonly settings: readonly Setting[]; +} + +export interface VaultScope { + /** The environment's name in the model. */ + readonly name: string; + /** The store's place for it (an Infisical project). */ + readonly project: string; + /** The store's environment slug. */ + readonly env: string; +} + +export interface Vault { + readonly name: string; + readonly key: string; + /** The vault subtype: the product (infisical). */ + readonly product: string; + readonly defaultScope?: VaultScope; + readonly scopes: readonly VaultScope[]; +} + +/** Thrown with every problem found, one per line, each naming its node. */ +export class ConfigModelError extends Error { + constructor(readonly problems: readonly string[]) { + super(`config pack: ${problems.length} problem(s) in the model:\n${problems.map((p) => ` - ${p}`).join("\n")}`); + this.name = "ConfigModelError"; + } +} + +export function isSettings(o: MetaData): boolean { + return o.typeId.type === TYPE_OBJECT && o.typeId.subType === OBJECT_SUBTYPE_SETTINGS; +} + +function text(v: AttrValue | undefined): string | undefined { + return typeof v === "string" ? v : undefined; +} + +/** An attribute value as the text an environment variable holds. */ +export function envText(v: AttrValue): string { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : JSON.stringify(v); +} + +/** `Database` + `poolSize` → `DATABASE_POOL_SIZE`. */ +export function deriveEnvName(group: string, field: string): string { + return `${toSnakeCase(group)}_${toSnakeCase(field)}`.toUpperCase(); +} + +/** + * Every settings group among `objects`, in model order, with its settings in declared + * order. Throws a {@link ConfigModelError} listing every problem. + */ +export function readSettings(objects: readonly MetaObject[]): SettingsGroup[] { + const problems: string[] = []; + const seen = new Map(); + const groups: SettingsGroup[] = []; + for (const o of objects) { + if (!isSettings(o)) continue; + const key = o.resolutionKey(); + const settings: Setting[] = []; + for (const f of o.fields()) { + const where = `${key}.${f.name}`; + const declared = text(f.attr(FIELD_ATTR_ENV_NAME)); + const envName = declared ?? deriveEnvName(o.name, f.name); + if (declared !== undefined && !ENV_NAME_PATTERN.test(declared)) { + problems.push(`${where}: @envName "${declared}" is not an environment variable name (upper case letters, digits and _, not starting with a digit)`); + } + const other = seen.get(envName); + if (other !== undefined) problems.push(`${where}: environment variable ${envName} is also ${other}`); + else seen.set(envName, where); + if (f.resolvedIsArray()) problems.push(`${where}: a setting holds one value; @isArray is not supported`); + const secret = f.attr(FIELD_ATTR_SECRET) === true; + const def = f.attr(ATTR_DEFAULT); + if (secret && def !== undefined) problems.push(`${where}: a @secret setting may not declare @default (its value belongs in the vault)`); + const description = text(f.attr(ATTR_DESCRIPTION)); + settings.push({ + envName, + setting: where, + type: f.typeId.subType, + required: f.attr(ATTR_REQUIRED) === true, + secret, + phase: f.attr(FIELD_ATTR_PHASE) === PHASE_BUILD ? PHASE_BUILD : PHASE_RUNTIME, + ...(def !== undefined && !secret ? { default: envText(def) } : {}), + ...(description !== undefined ? { description } : {}), + }); + } + const description = text(o.attr(ATTR_DESCRIPTION)); + groups.push({ name: o.name, key, ...(description !== undefined ? { description } : {}), settings }); + } + if (problems.length > 0) throw new ConfigModelError(problems); + return groups; +} + +/** Every vault declared at the root, in model order. Throws a {@link ConfigModelError} listing every problem. */ +export function readVaults(root: MetaData): Vault[] { + const problems: string[] = []; + const out: Vault[] = []; + for (const v of root.children()) { + if (!isVault(v)) continue; + const key = v.resolutionKey(); + const scopes: VaultScope[] = []; + const bySlug = new Map(); + for (const s of v.children()) { + if (!isVaultScope(s)) continue; + const scope: VaultScope = { + name: s.name, + project: text(s.attr(SCOPE_ATTR_PROJECT)) ?? "", + env: text(s.attr(SCOPE_ATTR_ENV)) ?? s.name, + }; + const clash = bySlug.get(scope.env); + if (clash !== undefined) problems.push(`${key}: scopes ${clash} and ${s.name} both use the store environment "${scope.env}"`); + else bySlug.set(scope.env, s.name); + scopes.push(scope); + } + if (scopes.length === 0) problems.push(`${key}: a vault needs at least one scope.env, one per environment that reads it`); + const defaultName = text(v.attr(VAULT_ATTR_DEFAULT_SCOPE)); + const defaultScope = defaultName === undefined ? undefined : scopes.find((s) => s.name === defaultName); + if (defaultName !== undefined && defaultScope === undefined) { + problems.push(`${key}: @defaultScope "${defaultName}" names no scope.env of this vault (${scopes.map((s) => s.name).join(", ")})`); + } + out.push({ name: v.name, key, product: v.typeId.subType, ...(defaultScope !== undefined ? { defaultScope } : {}), scopes }); + } + if (problems.length > 0) throw new ConfigModelError(problems); + return out; +} diff --git a/packs/config/typescript/test/definition.test.ts b/packs/config/typescript/test/definition.test.ts new file mode 100644 index 000000000..4a55854c8 --- /dev/null +++ b/packs/config/typescript/test/definition.test.ts @@ -0,0 +1,44 @@ +// The pack's definition file is its vocabulary, and the embedded copy and the lowering +// are two ways it could drift from what registers. Both are held here. +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { buildRegistryManifest, composeRegistry, coreProviders, MetaObject, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { DEFINITION_JSON, EMBEDDED_TS, renderEmbedded } from "../scripts/embed-definition.js"; +import { CONFIG_DEFINITION } from "../src/config-definition.embedded.js"; +import type { PackFactory } from "../src/definition.js"; +import { configProvider } from "../src/index.js"; +import { MetaVault, MetaVaultScope } from "../src/nodes.js"; + +// Core's own lowering of a definition file (provider-data.ts) is not on its public surface, +// so this test reaches it by path, at run time, as the reference the pack's lowering must +// match. Under bun, @metaobjectsdev/metadata resolves to the same src/ tree, so the registry +// it fills is the one the pack registers into. The path is computed so tsc, which reads +// core's built declarations, never compiles core's sources into this package. +type Apply = (registry: unknown, def: unknown, factories: Record) => void; +const CORE_PROVIDER_DATA = join(import.meta.dir, "..", "..", "..", "..", "server/typescript/packages/metadata/src/provider-data.ts"); +const { applyProviderDefinition } = (await import(pathToFileURL(CORE_PROVIDER_DATA).href)) as { applyProviderDefinition: Apply }; + +describe("config pack definition", () => { + test("the embedded copy is current (bun run embed)", () => { + expect(readFileSync(EMBEDDED_TS, "utf8")).toBe(renderEmbedded(readFileSync(DEFINITION_JSON, "utf8"))); + }); + + test("registers the same vocabulary core's own lowering would", () => { + const reference: MetaDataTypeProvider = { + id: configProvider.id, + dependencies: configProvider.dependencies ?? [], + registerTypes(registry) { + applyProviderDefinition(registry, CONFIG_DEFINITION, { + "object.settings": (t, n) => new MetaObject(t, n), + "vault.infisical": (t, n) => new MetaVault(t, n), + "scope.env": (t, n) => new MetaVaultScope(t, n), + }); + }, + }; + const ours = buildRegistryManifest(composeRegistry([...coreProviders, configProvider])); + const theirs = buildRegistryManifest(composeRegistry([...coreProviders, reference])); + expect(JSON.stringify(ours)).toBe(JSON.stringify(theirs)); + }); +}); diff --git a/packs/config/typescript/test/generators.test.ts b/packs/config/typescript/test/generators.test.ts new file mode 100644 index 000000000..6f02f2f38 --- /dev/null +++ b/packs/config/typescript/test/generators.test.ts @@ -0,0 +1,125 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { defineConfig, runGen, type Generator } from "@metaobjectsdev/codegen-ts"; +import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; +import { envExampleFile, keyManifestFile, keysAxiTomlFile, renderKeysAxiToml } from "../src/index.js"; +import { loadModel } from "./model.js"; + +const scratch = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "pack-config-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +/** A dry run: every rendered file by its path relative to the output directory, nothing written. */ +async function render(generators: Generator[], model?: unknown): Promise> { + const out = join(scratch, "out"); + const res = await runGen({ + config: defineConfig({ outDir: out, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators }), + metadata: await loadModel(model), + projectRoot: scratch, + dryRun: true, + }); + const files = new Map(); + for (const [abs, content] of res.rendered ?? []) files.set(abs.slice(out.length + 1), content); + return files; +} + +const ENV_EXAMPLE = `# @generated by @metaobjectsdev/pack-config (env-example). Do not edit: change the model and run \`meta gen\`. +# Every setting the application reads. Secret settings are listed by name only. + +# ── Database (acme::app::Database) ── +# The primary database. +# DATABASE_URL: string, required, secret: the value lives in the vault — Connection URL. +DATABASE_URL= +# DATABASE_USERNAME: string, required +DATABASE_USERNAME= +# DB_POOL_SIZE: int, optional +DB_POOL_SIZE=10 + +# ── LlmProvider (acme::app::LlmProvider) ── +# LLM_PROVIDER_API_KEY: string, required, secret: the value lives in the vault +LLM_PROVIDER_API_KEY= +# LLM_PROVIDER_MODEL: string, optional +LLM_PROVIDER_MODEL="a model name" +# LLM_PROVIDER_TRACE: boolean, optional +LLM_PROVIDER_TRACE=false + +# ── Build (acme::app::Build) ── +# BUILD_COMMIT_SHA: string, optional, build-time +BUILD_COMMIT_SHA= +`; + +const KEYS_AXI_TOML = `# @generated by @metaobjectsdev/pack-config (keys-axi-toml). Do not edit: change the model and run \`meta gen\`. +# From vault.infisical acme::app::keys. +backend = "infisical" +scope = "acme-app" +default_environment = "dev" + +# dev +[environments.dev] +scope = "acme-app" + +# production +[environments.prod] +scope = "acme-app-prod" +`; + +describe("config pack generators", () => { + test(".env.example lists every setting, secrets by name only", async () => { + const files = await render([envExampleFile()]); + expect([...files.keys()]).toEqual([".env.example"]); + expect(files.get(".env.example")).toBe(ENV_EXAMPLE); + }); + + test("the key manifest names, types and flags every setting and lists the vault's scopes", async () => { + const manifest = JSON.parse((await render([keyManifestFile()])).get("keys.manifest.json")!); + expect(manifest.generatedBy).toBe("@metaobjectsdev/pack-config (key-manifest)"); + expect(manifest.settings.map((s: { envName: string }) => s.envName)).toEqual([ + "BUILD_COMMIT_SHA", "DATABASE_URL", "DATABASE_USERNAME", "DB_POOL_SIZE", + "LLM_PROVIDER_API_KEY", "LLM_PROVIDER_MODEL", "LLM_PROVIDER_TRACE", + ]); + expect(manifest.settings.find((s: { envName: string }) => s.envName === "DATABASE_URL")).toEqual({ + envName: "DATABASE_URL", setting: "acme::app::Database.url", type: "string", + required: true, secret: true, phase: "runtime", description: "Connection URL.", + }); + expect(manifest.vaults).toEqual([{ + name: "keys", key: "acme::app::keys", product: "infisical", defaultScope: "dev", + scopes: [{ name: "dev", project: "acme-app", env: "dev" }, { name: "production", project: "acme-app-prod", env: "prod" }], + }]); + }); + + test(".keys-axi.toml maps each store environment to its project", async () => { + const files = await render([keysAxiTomlFile()]); + expect(files.get(".keys-axi.toml")).toBe(KEYS_AXI_TOML); + }); + + test(".keys-axi.toml without a default scope writes only the environments", () => { + const toml = renderKeysAxiToml({ name: "k", key: "a::k", product: "infisical", scopes: [{ name: "qa env", project: 'p"q', env: "qa env" }] }); + expect(toml).toContain('backend = "infisical"\n\n# qa env\n[environments."qa env"]\nscope = "p\\"q"\n'); + expect(toml).not.toContain("default_environment"); + }); + + test("a model with two vaults needs the one to write named", async () => { + // A settings group too: runGen runs no generator for a root with no object at all. + const twoVaults = { "metadata.root": { package: "acme::app", children: [ + { "object.settings": { name: "App", children: [{ "field.string": { name: "mode" } }] } }, + { "vault.infisical": { name: "a", children: [{ "scope.env": { name: "dev", "@project": "pa" } }] } }, + { "vault.infisical": { name: "b", children: [{ "scope.env": { name: "dev", "@project": "pb" } }] } }, + ] } }; + await expect(render([keysAxiTomlFile()], twoVaults)).rejects.toThrow(/declares 2 vaults/); + expect((await render([keysAxiTomlFile({ vault: "b" })], twoVaults)).get(".keys-axi.toml")).toContain('scope = "pb"'); + }); + + test("a model with no settings and no vault writes none of the files", async () => { + const empty = { "metadata.root": { package: "acme::app", children: [] } }; + expect((await render([envExampleFile(), keyManifestFile(), keysAxiTomlFile()], empty)).size).toBe(0); + }); + + test("core's entity generator types a settings group as it does a value object: no table", async () => { + const files = await render([entityFile()]); + expect(files.get("Customer.ts")).toContain("Table("); + const db = files.get("Database.ts")!; + expect(db).toContain("export interface Database {"); + expect(db).not.toContain("Table("); + }); +}); diff --git a/packs/config/typescript/test/model.ts b/packs/config/typescript/test/model.ts new file mode 100644 index 000000000..634f4e2b2 --- /dev/null +++ b/packs/config/typescript/test/model.ts @@ -0,0 +1,68 @@ +// A small model that uses everything the pack registers, loaded with the pack composed. +import { MetaDataLoader, InMemoryStringSource, composeRegistry, coreProviders, type MetaRoot } from "@metaobjectsdev/metadata"; +import { configProvider } from "../src/index.js"; + +export const MODEL = { + "metadata.root": { + package: "acme::app", + children: [ + { + "object.entity": { + name: "Customer", + children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "email" } }, + { "identity.primary": { name: "id", "@fields": "id", "@generation": "increment" } }, + ], + }, + }, + { + "object.settings": { + name: "Database", + "@description": "The primary database.", + children: [ + { "field.string": { name: "url", "@required": true, "@secret": true, "@description": "Connection URL." } }, + { "field.string": { name: "username", "@required": true } }, + { "field.int": { name: "poolSize", "@default": 10, "@envName": "DB_POOL_SIZE" } }, + ], + }, + }, + { + "object.settings": { + name: "LlmProvider", + children: [ + { "field.string": { name: "apiKey", "@required": true, "@secret": true } }, + { "field.string": { name: "model", "@default": "a model name" } }, + { "field.boolean": { name: "trace", "@default": false } }, + ], + }, + }, + { + "object.settings": { + name: "Build", + children: [{ "field.string": { name: "commitSha", "@phase": "build" } }], + }, + }, + { + "vault.infisical": { + name: "keys", + "@defaultScope": "dev", + children: [ + { "scope.env": { name: "dev", "@project": "acme-app" } }, + { "scope.env": { name: "production", "@project": "acme-app-prod", "@env": "prod" } }, + ], + }, + }, + ], + }, +}; + +export async function loadModel(model: unknown = MODEL): Promise { + const registry = composeRegistry([...coreProviders, configProvider]); + const res = await new MetaDataLoader({ registry, strict: true }).load([ + new InMemoryStringSource(JSON.stringify(model), { id: "meta.app.json", format: "json" }), + ]); + if (res.errors.length > 0) throw new Error(res.errors.map((e) => e.message).join("\n")); + return res.root; +} diff --git a/packs/config/typescript/test/settings.test.ts b/packs/config/typescript/test/settings.test.ts new file mode 100644 index 000000000..ab452694c --- /dev/null +++ b/packs/config/typescript/test/settings.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, test } from "bun:test"; +import { isMetaObject } from "@metaobjectsdev/metadata"; +import { ConfigModelError, deriveEnvName, readSettings, readVaults } from "../src/index.js"; +import { MODEL, loadModel } from "./model.js"; + +function withSettings(children: unknown[]): unknown { + return { "metadata.root": { package: "acme::app", children } }; +} + +async function objects(model: unknown = MODEL) { + const root = await loadModel(model); + return root.children().filter(isMetaObject); +} + +describe("readSettings", () => { + test("derives names, reads types, defaults and flags", async () => { + const groups = readSettings(await objects()); + expect(groups.map((g) => g.name)).toEqual(["Database", "LlmProvider", "Build"]); + const db = groups[0]!; + expect(db.description).toBe("The primary database."); + expect(db.settings).toEqual([ + { envName: "DATABASE_URL", setting: "acme::app::Database.url", type: "string", required: true, secret: true, phase: "runtime", description: "Connection URL." }, + { envName: "DATABASE_USERNAME", setting: "acme::app::Database.username", type: "string", required: true, secret: false, phase: "runtime" }, + { envName: "DB_POOL_SIZE", setting: "acme::app::Database.poolSize", type: "int", required: false, secret: false, phase: "runtime", default: "10" }, + ]); + expect(groups[1]!.settings.map((s) => [s.envName, s.default])).toEqual([ + ["LLM_PROVIDER_API_KEY", undefined], + ["LLM_PROVIDER_MODEL", "a model name"], + ["LLM_PROVIDER_TRACE", "false"], + ]); + expect(groups[2]!.settings[0]!.phase).toBe("build"); + }); + + test("names every problem a loader cannot see, together", async () => { + const model = withSettings([ + { "object.settings": { name: "Database", children: [ + { "field.string": { name: "url", "@secret": true, "@default": "postgres://x" } }, + { "field.string": { name: "host", "@envName": "db-host" } }, + { "field.string": { name: "tags", "isArray": true } }, + ] } }, + { "object.settings": { name: "Db", children: [{ "field.string": { name: "x", "@envName": "DATABASE_URL" } }] } }, + ]); + let err: unknown; + try { + readSettings(await objects(model)); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(ConfigModelError); + const problems = (err as ConfigModelError).problems.join("\n"); + expect(problems).toContain("acme::app::Database.url: a @secret setting may not declare @default"); + expect(problems).toContain('acme::app::Database.host: @envName "db-host" is not an environment variable name'); + expect(problems).toContain("acme::app::Database.tags: a setting holds one value"); + expect(problems).toContain("acme::app::Db.x: environment variable DATABASE_URL is also acme::app::Database.url"); + }); + + test("derives upper snake case through acronyms and digits", () => { + expect(deriveEnvName("Database", "poolSize")).toBe("DATABASE_POOL_SIZE"); + expect(deriveEnvName("OAuth2", "clientID")).toBe("O_AUTH2_CLIENT_ID"); + expect(deriveEnvName("S3", "bucketName")).toBe("S3_BUCKET_NAME"); + }); +}); + +describe("readVaults", () => { + test("reads scopes, defaulting the store environment to the scope's name", async () => { + const vaults = readVaults(await loadModel()); + expect(vaults).toEqual([ + { + name: "keys", + key: "acme::app::keys", + product: "infisical", + defaultScope: { name: "dev", project: "acme-app", env: "dev" }, + scopes: [ + { name: "dev", project: "acme-app", env: "dev" }, + { name: "production", project: "acme-app-prod", env: "prod" }, + ], + }, + ]); + }); + + test("refuses a missing default scope, two scopes on one store environment, and a vault with no scope", async () => { + const model = withSettings([ + { "vault.infisical": { name: "keys", "@defaultScope": "qa", children: [ + { "scope.env": { name: "staging", "@project": "a", "@env": "prod" } }, + { "scope.env": { name: "production", "@project": "b", "@env": "prod" } }, + ] } }, + { "vault.infisical": { name: "empty" } }, + ]); + const root = await loadModel(model); + expect(() => readVaults(root)).toThrow(/scopes staging and production both use the store environment "prod"[\s\S]*@defaultScope "qa" names no scope.env of this vault[\s\S]*acme::app::empty: a vault needs at least one scope.env/); + }); +}); diff --git a/packs/config/typescript/tsconfig.json b/packs/config/typescript/tsconfig.json new file mode 100644 index 000000000..576c0e24f --- /dev/null +++ b/packs/config/typescript/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2023"], + "strict": true, + "noImplicitOverride": true, + "noUncheckedIndexedAccess": true, + "noFallthroughCasesInSwitch": true, + "exactOptionalPropertyTypes": true, + "esModuleInterop": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "types": ["bun-types"], + "rootDir": "src", + "outDir": "dist" + }, + "include": ["src/**/*"], + "exclude": ["dist", "test", "node_modules"] +} diff --git a/packs/config/typescript/tsconfig.typecheck.json b/packs/config/typescript/tsconfig.typecheck.json new file mode 100644 index 000000000..8500f86ff --- /dev/null +++ b/packs/config/typescript/tsconfig.typecheck.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "rootDir": "." + }, + "include": ["src/**/*", "test/**/*", "scripts/**/*"], + "exclude": ["dist", "node_modules"] +} diff --git a/scripts/check-pack-boundary.ts b/scripts/check-pack-boundary.ts index 180f617b5..c213e7cdf 100644 --- a/scripts/check-pack-boundary.ts +++ b/scripts/check-pack-boundary.ts @@ -80,7 +80,9 @@ export function coreFiles(root: string): string[] { export function scanCore(root: string, packs: Map = packsById(root)): string[] { const out: string[] = []; const ids = [...packs.keys()]; - const idRes = ids.map((id) => [id, new RegExp(`(^|[^A-Za-z0-9_-])${id}([^A-Za-z0-9_-]|$)`)] as const); + // A whole id, not part of a longer name and not a file stem: `metaobjects-config.ts` is + // core's own config module, not the config pack's provider id. + const idRes = ids.map((id) => [id, new RegExp(`(^|[^A-Za-z0-9_-])${id}(?![A-Za-z0-9_-]|\\.[A-Za-z])`)] as const); for (const rel of coreFiles(root)) { const text = readFileSync(join(root, rel), "utf8"); if (!PACK_COORDINATE.test(text) && !INTO_PACKS.test(text) && !ids.some((id) => text.includes(id))) continue; diff --git a/scripts/packs.test.ts b/scripts/packs.test.ts index 524378a48..a388ae4a0 100644 --- a/scripts/packs.test.ts +++ b/scripts/packs.test.ts @@ -174,6 +174,18 @@ describe("pack boundary", () => { expect(problems).not.toContain("docs/packs.md"); }); + test("a file named like a pack id is not the id", () => { + const root = scratchRoot(); + makePack(root, "demo"); + write(root, "server/typescript/packages/cli/src/c.ts", `import { x } from "./metaobjects-demo.js";\n`); + write(root, "server/python/src/d.py", `SCHEMA = "metaobjects-demo.schema.json"\n`); + write(root, "server/python/src/e.py", "# The provider is metaobjects-demo.\n"); + const problems = scanCore(root).join("\n"); + expect(problems).not.toContain("c.ts"); + expect(problems).not.toContain("d.py"); + expect(problems).toContain('server/python/src/e.py:1: names the independent pack provider "metaobjects-demo"'); + }); + test("the root workspace may hold the pack glob, and core's scripts may not filter on '*'", () => { const root = scratchRoot(); write(root, "package.json", json({ From 54d00118a2a3c41dce92474055b857a12d292dc4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 02:07:55 -0500 Subject: [PATCH 2/9] fix(packs): config pack review and simplify follow-ups - An abstract settings group is a base: read through the groups that extend it, never emitted under its own name. - Vaults are read inside the project's scope, as settings are. - Setting attributes put on a non-settings field warn once per run, from whichever config generator runs first. - keys-axi-toml problems are ConfigModelErrors like the model's others. - scope.env declares min 1 (the generators enforce it; the loader does not count child rules). - Reuse core's FIELD_ATTR_* / DOC_ATTR_DESCRIPTION constants and GENERATED_EDIT_NOTE: hand edits are three-way merged, so the header no longer says "do not edit". - check-pack-boundary: a file-name tail (.test.ts, .schema.json) after a pack id is a file stem; an id followed by another dotted word still trips. --- packs/config/README.md | 7 ++- .../config/fixtures/expected-vocabulary.json | 2 +- packs/config/metamodel/config.json | 4 +- .../src/config-definition.embedded.ts | 4 +- packs/config/typescript/src/generators.ts | 57 ++++++++++++++----- packs/config/typescript/src/index.ts | 1 + packs/config/typescript/src/settings.ts | 48 +++++++++++----- .../config/typescript/test/generators.test.ts | 4 +- packs/config/typescript/test/settings.test.ts | 24 +++++++- scripts/check-pack-boundary.ts | 8 ++- scripts/packs.test.ts | 4 ++ 11 files changed, 125 insertions(+), 38 deletions(-) diff --git a/packs/config/README.md b/packs/config/README.md index 7cfe9405d..79ccf9271 100644 --- a/packs/config/README.md +++ b/packs/config/README.md @@ -28,7 +28,10 @@ packs, which refer to this pack's nodes by name. | `scope.env` | Where the vault keeps one environment's secrets. Its name is the model's environment name; `@project` is the Infisical project; `@env` is Infisical's environment slug (absent: the scope's name). | The three field attributes are registered on every field subtype (a pack may add optional -attributes to a type it does not own, ADR-0050); the generators read them on settings only. +attributes to a type it does not own, ADR-0050); the generators read them on settings only, +and the first of them to run warns, naming the field, when a model puts one anywhere else. An +abstract settings group is a base: its settings appear under each group that extends it, not +under its own name. A secret is never referenced by value or by a separate node: it is read under its environment name, in the scope the vault maps to the environment being deployed. @@ -78,7 +81,7 @@ export default defineConfig({ }); ``` -`meta gen` runs no generator over a model with no object at all, so a model that declares a +Vaults, like settings, are read inside the project's `scope`. `meta gen` runs no generator over a model with no object at all, so a model that declares a vault and no settings group writes nothing. ## Checks diff --git a/packs/config/fixtures/expected-vocabulary.json b/packs/config/fixtures/expected-vocabulary.json index aadfd7af9..120dc5546 100644 --- a/packs/config/fixtures/expected-vocabulary.json +++ b/packs/config/fixtures/expected-vocabulary.json @@ -82,7 +82,7 @@ "childType": "scope", "childSubType": "env", "childName": "*", - "min": 0, + "min": 1, "max": null } ] diff --git a/packs/config/metamodel/config.json b/packs/config/metamodel/config.json index 8eabb939f..3774ac850 100644 --- a/packs/config/metamodel/config.json +++ b/packs/config/metamodel/config.json @@ -34,9 +34,9 @@ "type": "scope", "subType": "env", "name": "*", - "min": 0, + "min": 1, "max": null, - "description": "The vault's place for one environment. A vault with none is refused by the generators that read it." + "description": "The vault's place for one environment. At least one: the loader does not count child rules, so the generators that read a vault refuse one with none." }, { "type": "attr", diff --git a/packs/config/typescript/src/config-definition.embedded.ts b/packs/config/typescript/src/config-definition.embedded.ts index 4d0a10996..04e4b2508 100644 --- a/packs/config/typescript/src/config-definition.embedded.ts +++ b/packs/config/typescript/src/config-definition.embedded.ts @@ -54,9 +54,9 @@ export const CONFIG_DEFINITION: PackDefinition = { "type": "scope", "subType": "env", "name": "*", - "min": 0, + "min": 1, "max": null, - "description": "The vault's place for one environment. A vault with none is refused by the generators that read it." + "description": "The vault's place for one environment. At least one: the loader does not count child rules, so the generators that read a vault refuse one with none." }, { "type": "attr", diff --git a/packs/config/typescript/src/generators.ts b/packs/config/typescript/src/generators.ts index e5dca1434..db86a2912 100644 --- a/packs/config/typescript/src/generators.ts +++ b/packs/config/typescript/src/generators.ts @@ -14,9 +14,10 @@ * Paths are relative to the generator's target. These files belong at the project root, * so wire them to a target whose `outDir` is `"."` (README, "Wiring"). */ -import type { EmittedFile, Generator, GenContext } from "@metaobjectsdev/codegen-ts"; +import { GENERATED_EDIT_NOTE, type EmittedFile, type Generator, type GenContext } from "@metaobjectsdev/codegen-ts"; +import type { MetaObject } from "@metaobjectsdev/metadata"; import { PHASE_BUILD, VAULT_SUBTYPE_INFISICAL } from "./constants.js"; -import { readSettings, readVaults, type Setting, type Vault } from "./settings.js"; +import { ConfigModelError, misplacedSettingAttrs, readSettings, readVaults, type Setting, type Vault } from "./settings.js"; const PACKAGE = "@metaobjectsdev/pack-config"; @@ -33,17 +34,45 @@ export interface KeysAxiTomlOptions extends ConfigGeneratorOptions { } function header(generator: string, comment: string): string { - return `${comment} @generated by ${PACKAGE} (${generator}). Do not edit: change the model and run \`meta gen\`.`; + return `${comment} @generated by ${PACKAGE} (${generator}) — ${GENERATED_EDIT_NOTE}`; } +/** The run's objects inside its `scope`. */ +function scopedObjects(ctx: GenContext): MetaObject[] { + return ctx.entities.filter(ctx.matches); +} + +/** Text on one comment line. */ +function oneLine(s: string): string { + return s.replace(/\s+/g, " ").trim(); +} + +/** The root's vaults inside the run's scope (`scope` in the project config), as settings are. */ +function vaultsInScope(ctx: GenContext): Vault[] { + return readVaults(ctx.loadedRoot, (key) => ctx.select?.(key) ?? true); +} + +/** Roots already checked for misplaced setting attributes: warn once per run, whichever generators run. */ +const checked = new WeakSet(); + function generator(name: string, opts: ConfigGeneratorOptions, generate: (ctx: GenContext) => EmittedFile[]): Generator { - return { name, ...(opts.target !== undefined ? { target: opts.target } : {}), generate }; + return { + name, + ...(opts.target !== undefined ? { target: opts.target } : {}), + generate(ctx) { + if (!checked.has(ctx.loadedRoot)) { + checked.add(ctx.loadedRoot); + for (const w of misplacedSettingAttrs(scopedObjects(ctx))) ctx.warn(`${PACKAGE}: ${w}`); + } + return generate(ctx); + }, + }; } // ── .env.example ───────────────────────────────────────────────────────────── /** A value as dotenv writes it: bare when that is unambiguous, else double-quoted. */ -export function dotenvValue(v: string): string { +function dotenvValue(v: string): string { return /^[^\s"'#\\$`]*$/.test(v) ? v : `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, "\\$").replace(/`/g, "\\`")}"`; } @@ -51,12 +80,12 @@ function describe(s: Setting): string { const facts = [s.type, s.required ? "required" : "optional"]; if (s.secret) facts.push("secret: the value lives in the vault"); if (s.phase === PHASE_BUILD) facts.push("build-time"); - const what = s.description === undefined ? "" : ` — ${s.description.replace(/\s+/g, " ").trim()}`; + const what = s.description === undefined ? "" : ` — ${oneLine(s.description)}`; return `# ${s.envName}: ${facts.join(", ")}${what}`; } export function renderEnvExample(ctx: GenContext): string | undefined { - const groups = readSettings(ctx.entities.filter(ctx.matches)).filter((g) => g.settings.length > 0); + const groups = readSettings(scopedObjects(ctx)).filter((g) => g.settings.length > 0); if (groups.length === 0) return undefined; const lines = [ header("env-example", "#"), @@ -64,7 +93,7 @@ export function renderEnvExample(ctx: GenContext): string | undefined { ]; for (const g of groups) { lines.push("", `# ── ${g.name} (${g.key}) ──`); - if (g.description !== undefined) lines.push(`# ${g.description.replace(/\s+/g, " ").trim()}`); + if (g.description !== undefined) lines.push(`# ${oneLine(g.description)}`); for (const s of g.settings) lines.push(describe(s), `${s.envName}=${s.default === undefined ? "" : dotenvValue(s.default)}`); } return `${lines.join("\n")}\n`; @@ -80,8 +109,8 @@ export function envExampleFile(opts: ConfigGeneratorOptions = {}): Generator { // ── keys.manifest.json ────────────────────────────────────────────────────── export function renderKeyManifest(ctx: GenContext): string | undefined { - const settings = readSettings(ctx.entities.filter(ctx.matches)).flatMap((g) => g.settings); - const vaults = readVaults(ctx.loadedRoot); + const settings = readSettings(scopedObjects(ctx)).flatMap((g) => g.settings); + const vaults = vaultsInScope(ctx); if (settings.length === 0 && vaults.length === 0) return undefined; const manifest = { generatedBy: `${PACKAGE} (key-manifest)`, @@ -119,18 +148,18 @@ function tomlKey(k: string): string { function pickVault(vaults: readonly Vault[], wanted: string | undefined): Vault | undefined { if (wanted !== undefined) { const v = vaults.find((x) => x.name === wanted || x.key === wanted); - if (v === undefined) throw new Error(`keys-axi-toml: no vault named "${wanted}" (the model declares: ${vaults.map((x) => x.key).join(", ") || "none"})`); + if (v === undefined) throw new ConfigModelError([`keys-axi-toml: no vault named "${wanted}" (the model declares: ${vaults.map((x) => x.key).join(", ") || "none"})`]); return v; } if (vaults.length > 1) { - throw new Error(`keys-axi-toml: the model declares ${vaults.length} vaults (${vaults.map((x) => x.key).join(", ")}); name one with keysAxiTomlFile({ vault })`); + throw new ConfigModelError([`keys-axi-toml: the model declares ${vaults.length} vaults (${vaults.map((x) => x.key).join(", ")}); name one with keysAxiTomlFile({ vault })`]); } return vaults[0]; } export function renderKeysAxiToml(vault: Vault): string { if (vault.product !== VAULT_SUBTYPE_INFISICAL) { - throw new Error(`keys-axi-toml: vault ${vault.key} is vault.${vault.product}; keys-axi reads only vault.${VAULT_SUBTYPE_INFISICAL} from this generator`); + throw new ConfigModelError([`keys-axi-toml: vault ${vault.key} is vault.${vault.product}; keys-axi reads only vault.${VAULT_SUBTYPE_INFISICAL} from this generator`]); } const lines = [header("keys-axi-toml", "#"), `# From vault.${vault.product} ${vault.key}.`, `backend = ${tomlString(vault.product)}`]; if (vault.defaultScope !== undefined) { @@ -144,7 +173,7 @@ export function renderKeysAxiToml(vault: Vault): string { export function keysAxiTomlFile(opts: KeysAxiTomlOptions = {}): Generator { return generator("keys-axi-toml", opts, (ctx) => { - const vault = pickVault(readVaults(ctx.loadedRoot), opts.vault); + const vault = pickVault(vaultsInScope(ctx), opts.vault); if (vault === undefined) { ctx.warn("keys-axi-toml: the model declares no vault, so there is no .keys-axi.toml to write"); return []; diff --git a/packs/config/typescript/src/index.ts b/packs/config/typescript/src/index.ts index b82130b7e..aebbf4484 100644 --- a/packs/config/typescript/src/index.ts +++ b/packs/config/typescript/src/index.ts @@ -11,6 +11,7 @@ export { ConfigModelError, deriveEnvName, isSettings, + misplacedSettingAttrs, readSettings, readVaults, type Setting, diff --git a/packs/config/typescript/src/settings.ts b/packs/config/typescript/src/settings.ts index 26bfbd92d..989de7718 100644 --- a/packs/config/typescript/src/settings.ts +++ b/packs/config/typescript/src/settings.ts @@ -6,7 +6,16 @@ * see (a name collision across groups, a secret with a default) are collected and thrown * together, each naming the node, so one `meta gen` lists them all. */ -import { TYPE_OBJECT, toSnakeCase, type AttrValue, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import { + DOC_ATTR_DESCRIPTION, + FIELD_ATTR_DEFAULT, + FIELD_ATTR_REQUIRED, + TYPE_OBJECT, + toSnakeCase, + type AttrValue, + type MetaData, + type MetaObject, +} from "@metaobjectsdev/metadata"; import { ENV_NAME_PATTERN, FIELD_ATTR_ENV_NAME, @@ -22,10 +31,6 @@ import { } from "./constants.js"; import { isVault, isVaultScope } from "./nodes.js"; -const ATTR_REQUIRED = "required"; -const ATTR_DEFAULT = "default"; -const ATTR_DESCRIPTION = "description"; - export interface Setting { /** The environment variable: `@envName`, else `_` in upper snake case. */ readonly envName: string; @@ -83,7 +88,7 @@ function text(v: AttrValue | undefined): string | undefined { } /** An attribute value as the text an environment variable holds. */ -export function envText(v: AttrValue): string { +function envText(v: AttrValue): string { return typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : JSON.stringify(v); } @@ -101,7 +106,8 @@ export function readSettings(objects: readonly MetaObject[]): SettingsGroup[] { const seen = new Map(); const groups: SettingsGroup[] = []; for (const o of objects) { - if (!isSettings(o)) continue; + // An abstract group is a base other groups extend: its fields are read through them. + if (!isSettings(o) || o.isAbstract) continue; const key = o.resolutionKey(); const settings: Setting[] = []; for (const f of o.fields()) { @@ -116,33 +122,49 @@ export function readSettings(objects: readonly MetaObject[]): SettingsGroup[] { else seen.set(envName, where); if (f.resolvedIsArray()) problems.push(`${where}: a setting holds one value; @isArray is not supported`); const secret = f.attr(FIELD_ATTR_SECRET) === true; - const def = f.attr(ATTR_DEFAULT); + const def = f.attr(FIELD_ATTR_DEFAULT); if (secret && def !== undefined) problems.push(`${where}: a @secret setting may not declare @default (its value belongs in the vault)`); - const description = text(f.attr(ATTR_DESCRIPTION)); + const description = text(f.attr(DOC_ATTR_DESCRIPTION)); settings.push({ envName, setting: where, type: f.typeId.subType, - required: f.attr(ATTR_REQUIRED) === true, + required: f.attr(FIELD_ATTR_REQUIRED) === true, secret, phase: f.attr(FIELD_ATTR_PHASE) === PHASE_BUILD ? PHASE_BUILD : PHASE_RUNTIME, ...(def !== undefined && !secret ? { default: envText(def) } : {}), ...(description !== undefined ? { description } : {}), }); } - const description = text(o.attr(ATTR_DESCRIPTION)); + const description = text(o.attr(DOC_ATTR_DESCRIPTION)); groups.push({ name: o.name, key, ...(description !== undefined ? { description } : {}), settings }); } if (problems.length > 0) throw new ConfigModelError(problems); return groups; } +/** + * Where a model puts `@secret`, `@envName` or `@phase` on a field of something other than a + * settings group: they load there (every field subtype carries them) and nothing reads them. + */ +export function misplacedSettingAttrs(objects: readonly MetaObject[]): string[] { + const out: string[] = []; + for (const o of objects) { + if (isSettings(o)) continue; + for (const f of o.fields()) { + const names = [FIELD_ATTR_SECRET, FIELD_ATTR_ENV_NAME, FIELD_ATTR_PHASE].filter((a) => f.attr(a) !== undefined); + if (names.length > 0) out.push(`${o.resolutionKey()}.${f.name}: ${names.map((a) => `@${a}`).join(", ")} only mean something on a field of an object.settings; here nothing reads them`); + } + } + return out; +} + /** Every vault declared at the root, in model order. Throws a {@link ConfigModelError} listing every problem. */ -export function readVaults(root: MetaData): Vault[] { +export function readVaults(root: MetaData, inScope: (key: string) => boolean = () => true): Vault[] { const problems: string[] = []; const out: Vault[] = []; for (const v of root.children()) { - if (!isVault(v)) continue; + if (!isVault(v) || !inScope(v.resolutionKey())) continue; const key = v.resolutionKey(); const scopes: VaultScope[] = []; const bySlug = new Map(); diff --git a/packs/config/typescript/test/generators.test.ts b/packs/config/typescript/test/generators.test.ts index 6f02f2f38..4bef69826 100644 --- a/packs/config/typescript/test/generators.test.ts +++ b/packs/config/typescript/test/generators.test.ts @@ -24,7 +24,7 @@ async function render(generators: Generator[], model?: unknown): Promise { expect(problems).toContain("acme::app::Db.x: environment variable DATABASE_URL is also acme::app::Database.url"); }); + test("an abstract group is read only through the groups that extend it", async () => { + const groups = readSettings(await objects(withSettings([ + { "object.settings": { name: "Base", abstract: true, children: [{ "field.string": { name: "host" } }] } }, + { "object.settings": { name: "Db", extends: "Base", children: [{ "field.int": { name: "port" } }] } }, + ]))); + expect(groups.map((g) => g.name)).toEqual(["Db"]); + expect(groups[0]!.settings.map((s) => s.envName).sort()).toEqual(["DB_HOST", "DB_PORT"]); + }); + + test("names setting attributes put on a field of something other than settings", async () => { + const found = misplacedSettingAttrs(await objects(withSettings([ + { "object.value": { name: "Token", children: [{ "field.string": { name: "value", "@secret": true, "@envName": "TOKEN" } }] } }, + { "object.settings": { name: "Ok", children: [{ "field.string": { name: "x", "@secret": true } }] } }, + ]))); + expect(found).toEqual(["acme::app::Token.value: @secret, @envName only mean something on a field of an object.settings; here nothing reads them"]); + }); + test("derives upper snake case through acronyms and digits", () => { expect(deriveEnvName("Database", "poolSize")).toBe("DATABASE_POOL_SIZE"); expect(deriveEnvName("OAuth2", "clientID")).toBe("O_AUTH2_CLIENT_ID"); @@ -78,6 +95,11 @@ describe("readVaults", () => { ]); }); + test("skips a vault outside the run's scope", async () => { + const root = await loadModel(withSettings([{ "vault.infisical": { name: "empty" } }])); + expect(readVaults(root, () => false)).toEqual([]); + }); + test("refuses a missing default scope, two scopes on one store environment, and a vault with no scope", async () => { const model = withSettings([ { "vault.infisical": { name: "keys", "@defaultScope": "qa", children: [ diff --git a/scripts/check-pack-boundary.ts b/scripts/check-pack-boundary.ts index c213e7cdf..f541ce704 100644 --- a/scripts/check-pack-boundary.ts +++ b/scripts/check-pack-boundary.ts @@ -76,13 +76,19 @@ export function coreFiles(root: string): string[] { return files.filter((f) => SCANNED.test(f) && existsSync(join(root, f))); } +/** + * An id followed by a file name's tail (`.ts`, `.test.ts`, `.schema.json`) is a file stem, + * not the id: the tail ends in one of the extensions core's trees hold. + */ +const FILE_EXTENSION = /(?:\.[A-Za-z0-9_-]+)*\.(?:[cm]?[jt]sx?|json|ya?ml|py|md|toml|cs|csproj|java|kt|xml|sql)(?![A-Za-z0-9])/; + /** Rule 1 and the source half of rule 2. */ export function scanCore(root: string, packs: Map = packsById(root)): string[] { const out: string[] = []; const ids = [...packs.keys()]; // A whole id, not part of a longer name and not a file stem: `metaobjects-config.ts` is // core's own config module, not the config pack's provider id. - const idRes = ids.map((id) => [id, new RegExp(`(^|[^A-Za-z0-9_-])${id}(?![A-Za-z0-9_-]|\\.[A-Za-z])`)] as const); + const idRes = ids.map((id) => [id, new RegExp(`(^|[^A-Za-z0-9_-])${id}(?![A-Za-z0-9_-]|${FILE_EXTENSION.source})`)] as const); for (const rel of coreFiles(root)) { const text = readFileSync(join(root, rel), "utf8"); if (!PACK_COORDINATE.test(text) && !INTO_PACKS.test(text) && !ids.some((id) => text.includes(id))) continue; diff --git a/scripts/packs.test.ts b/scripts/packs.test.ts index a388ae4a0..04cbdac9b 100644 --- a/scripts/packs.test.ts +++ b/scripts/packs.test.ts @@ -180,10 +180,14 @@ describe("pack boundary", () => { write(root, "server/typescript/packages/cli/src/c.ts", `import { x } from "./metaobjects-demo.js";\n`); write(root, "server/python/src/d.py", `SCHEMA = "metaobjects-demo.schema.json"\n`); write(root, "server/python/src/e.py", "# The provider is metaobjects-demo.\n"); + write(root, "server/python/src/f.py", "ID = metaobjects-demo.provider\n"); + write(root, "server/typescript/packages/cli/test/g.ts", `import "../src/metaobjects-demo.test.ts";\n`); const problems = scanCore(root).join("\n"); expect(problems).not.toContain("c.ts"); expect(problems).not.toContain("d.py"); + expect(problems).not.toContain("g.ts"); expect(problems).toContain('server/python/src/e.py:1: names the independent pack provider "metaobjects-demo"'); + expect(problems).toContain('server/python/src/f.py:1: names the independent pack provider "metaobjects-demo"'); }); test("the root workspace may hold the pack glob, and core's scripts may not filter on '*'", () => { From 82eb94721badb041547a55a8410e2f6bc474488d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 02:09:10 -0500 Subject: [PATCH 3/9] docs(packs): leave packs/README.md to the systems lane (it names the packs) --- packs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packs/README.md b/packs/README.md index f7774c4d1..ca3ae1e3a 100644 --- a/packs/README.md +++ b/packs/README.md @@ -2,7 +2,7 @@ A directory here is an **independent pack**: vocabulary, generators and runtime for a capability that is not part of core, built and versioned as if it were its own repository -([ADR-0069](../spec/decisions/ADR-0069-independent-packs.md)). The first is `config` (settings and secrets). +([ADR-0069](../spec/decisions/ADR-0069-independent-packs.md)). None exists yet. An independent pack is not in the default bundle. A project opts in by naming its provider. It is never in `fixtures/registry-conformance/expected-registry.json` and never moves From c9fa6d6b05c881f2e938e8f2f13a3f54df751a9f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 02:48:33 -0500 Subject: [PATCH 4/9] no-mistakes(review): validate all settings groups, tighten pack lowering --- packs/config/typescript/src/definition.ts | 9 +++++ packs/config/typescript/src/generators.ts | 10 ++---- packs/config/typescript/src/index.ts | 2 -- packs/config/typescript/src/settings.ts | 33 ++++++++++++++----- .../config/typescript/test/definition.test.ts | 21 ++++++++++-- .../config/typescript/test/generators.test.ts | 6 ++-- packs/config/typescript/test/settings.test.ts | 24 ++++++++++++++ 7 files changed, 84 insertions(+), 21 deletions(-) diff --git a/packs/config/typescript/src/definition.ts b/packs/config/typescript/src/definition.ts index 12d73379f..0b41cc072 100644 --- a/packs/config/typescript/src/definition.ts +++ b/packs/config/typescript/src/definition.ts @@ -53,6 +53,14 @@ export type PackFactory = (typeId: TypeId, name: string) => MetaData; const ATTR = "attr"; const WILDCARD = "*"; +function validateCardinality(owner: string, c: PackChildDef): void { + if (c.min < 0) throw new Error(`${owner}: child "${c.name}" has min ${c.min} < 0`); + if (c.max !== null && c.max < c.min) throw new Error(`${owner}: child "${c.name}" has max ${c.max} < min ${c.min}`); + if (c.type === ATTR && c.max !== 1 && c.isArray !== true) { + throw new Error(`${owner}: attr "${c.name}" is single-valued (max must be 1; a list-valued attr sets isArray: true)`); + } +} + function toAttr(owner: string, c: PackChildDef): AttrSchema { if (Array.isArray(c.subType)) throw new Error(`${owner}: attr @${c.name} declares a list subType; an attr has one value type`); return { @@ -81,6 +89,7 @@ function split(owner: string, children: readonly PackChildDef[]): { attributes: const attributes: AttrSchema[] = []; const childRules: ChildRule[] = []; for (const c of children) { + validateCardinality(owner, c); if (c.type === ATTR) attributes.push(toAttr(owner, c)); else childRules.push(toRule(c)); } diff --git a/packs/config/typescript/src/generators.ts b/packs/config/typescript/src/generators.ts index db86a2912..eb6c843da 100644 --- a/packs/config/typescript/src/generators.ts +++ b/packs/config/typescript/src/generators.ts @@ -84,7 +84,7 @@ function describe(s: Setting): string { return `# ${s.envName}: ${facts.join(", ")}${what}`; } -export function renderEnvExample(ctx: GenContext): string | undefined { +function renderEnvExample(ctx: GenContext): string | undefined { const groups = readSettings(scopedObjects(ctx)).filter((g) => g.settings.length > 0); if (groups.length === 0) return undefined; const lines = [ @@ -108,7 +108,7 @@ export function envExampleFile(opts: ConfigGeneratorOptions = {}): Generator { // ── keys.manifest.json ────────────────────────────────────────────────────── -export function renderKeyManifest(ctx: GenContext): string | undefined { +function renderKeyManifest(ctx: GenContext): string | undefined { const settings = readSettings(scopedObjects(ctx)).flatMap((g) => g.settings); const vaults = vaultsInScope(ctx); if (settings.length === 0 && vaults.length === 0) return undefined; @@ -174,10 +174,6 @@ export function renderKeysAxiToml(vault: Vault): string { export function keysAxiTomlFile(opts: KeysAxiTomlOptions = {}): Generator { return generator("keys-axi-toml", opts, (ctx) => { const vault = pickVault(vaultsInScope(ctx), opts.vault); - if (vault === undefined) { - ctx.warn("keys-axi-toml: the model declares no vault, so there is no .keys-axi.toml to write"); - return []; - } - return [{ path: opts.path ?? ".keys-axi.toml", content: renderKeysAxiToml(vault) }]; + return vault === undefined ? [] : [{ path: opts.path ?? ".keys-axi.toml", content: renderKeysAxiToml(vault) }]; }); } diff --git a/packs/config/typescript/src/index.ts b/packs/config/typescript/src/index.ts index aebbf4484..c4f1ee76c 100644 --- a/packs/config/typescript/src/index.ts +++ b/packs/config/typescript/src/index.ts @@ -23,8 +23,6 @@ export { envExampleFile, keyManifestFile, keysAxiTomlFile, - renderEnvExample, - renderKeyManifest, renderKeysAxiToml, type ConfigGeneratorOptions, type KeysAxiTomlOptions, diff --git a/packs/config/typescript/src/settings.ts b/packs/config/typescript/src/settings.ts index 989de7718..d0991f09b 100644 --- a/packs/config/typescript/src/settings.ts +++ b/packs/config/typescript/src/settings.ts @@ -29,8 +29,16 @@ import { VAULT_ATTR_DEFAULT_SCOPE, type Phase, } from "./constants.js"; +import { CONFIG_DEFINITION } from "./config-definition.embedded.js"; import { isVault, isVaultScope } from "./nodes.js"; +const SETTINGS_FIELD_SUBTYPES: readonly string[] = (() => { + const rule = CONFIG_DEFINITION.types + .find((t) => t.type === TYPE_OBJECT && t.subType === OBJECT_SUBTYPE_SETTINGS) + ?.children.find((c) => c.type === "field"); + return typeof rule?.subType === "string" ? [rule.subType] : (rule?.subType ?? []); +})(); + export interface Setting { /** The environment variable: `@envName`, else `_` in upper snake case. */ readonly envName: string; @@ -106,20 +114,28 @@ export function readSettings(objects: readonly MetaObject[]): SettingsGroup[] { const seen = new Map(); const groups: SettingsGroup[] = []; for (const o of objects) { - // An abstract group is a base other groups extend: its fields are read through them. - if (!isSettings(o) || o.isAbstract) continue; + if (!isSettings(o)) continue; const key = o.resolutionKey(); const settings: Setting[] = []; for (const f of o.fields()) { const where = `${key}.${f.name}`; const declared = text(f.attr(FIELD_ATTR_ENV_NAME)); const envName = declared ?? deriveEnvName(o.name, f.name); - if (declared !== undefined && !ENV_NAME_PATTERN.test(declared)) { - problems.push(`${where}: @envName "${declared}" is not an environment variable name (upper case letters, digits and _, not starting with a digit)`); + if (!ENV_NAME_PATTERN.test(envName)) { + problems.push( + declared !== undefined + ? `${where}: @envName "${declared}" is not an environment variable name (upper case letters, digits and _, not starting with a digit)` + : `${where}: the derived environment variable name "${envName}" is not valid (upper case letters, digits and _, not starting with a digit); set @envName`, + ); + } + if (!o.isAbstract) { + const other = seen.get(envName); + if (other !== undefined) problems.push(`${where}: environment variable ${envName} is also ${other}`); + else seen.set(envName, where); + } + if (!SETTINGS_FIELD_SUBTYPES.includes(f.typeId.subType)) { + problems.push(`${where}: a setting is a scalar; field.${f.typeId.subType} is not one of ${SETTINGS_FIELD_SUBTYPES.join(", ")}`); } - const other = seen.get(envName); - if (other !== undefined) problems.push(`${where}: environment variable ${envName} is also ${other}`); - else seen.set(envName, where); if (f.resolvedIsArray()) problems.push(`${where}: a setting holds one value; @isArray is not supported`); const secret = f.attr(FIELD_ATTR_SECRET) === true; const def = f.attr(FIELD_ATTR_DEFAULT); @@ -137,7 +153,8 @@ export function readSettings(objects: readonly MetaObject[]): SettingsGroup[] { }); } const description = text(o.attr(DOC_ATTR_DESCRIPTION)); - groups.push({ name: o.name, key, ...(description !== undefined ? { description } : {}), settings }); + // An abstract group is a base other groups extend: checked here, listed under its extenders. + if (!o.isAbstract) groups.push({ name: o.name, key, ...(description !== undefined ? { description } : {}), settings }); } if (problems.length > 0) throw new ConfigModelError(problems); return groups; diff --git a/packs/config/typescript/test/definition.test.ts b/packs/config/typescript/test/definition.test.ts index 4a55854c8..2d8b0c265 100644 --- a/packs/config/typescript/test/definition.test.ts +++ b/packs/config/typescript/test/definition.test.ts @@ -4,10 +4,10 @@ import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; -import { buildRegistryManifest, composeRegistry, coreProviders, MetaObject, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { buildRegistryManifest, composeRegistry, coreProviders, MetaObject, type MetaDataTypeProvider, type TypeId, type TypeRegistry } from "@metaobjectsdev/metadata"; import { DEFINITION_JSON, EMBEDDED_TS, renderEmbedded } from "../scripts/embed-definition.js"; import { CONFIG_DEFINITION } from "../src/config-definition.embedded.js"; -import type { PackFactory } from "../src/definition.js"; +import { registerDefinition, type PackDefinition, type PackFactory } from "../src/definition.js"; import { configProvider } from "../src/index.js"; import { MetaVault, MetaVaultScope } from "../src/nodes.js"; @@ -41,4 +41,21 @@ describe("config pack definition", () => { const theirs = buildRegistryManifest(composeRegistry([...coreProviders, reference])); expect(JSON.stringify(ours)).toBe(JSON.stringify(theirs)); }); + + const attr = (extra: object) => ({ type: "attr", subType: "boolean", name: "secret", min: 0, max: 1, ...extra }); + const invalid: Record = { + "an attr with max above 1 and no isArray": [attr({ max: 5 })], + "a child with min below 0": [attr({ min: -1 })], + "a child with max below min": [{ type: "field", subType: "string", name: "*", min: 1, max: 0 }], + }; + for (const [title, children] of Object.entries(invalid)) { + test(`both lowerings reject ${title}`, () => { + const def = { provider: "bad", types: [{ type: "object", subType: "settings", description: "d", children }] }; + const factories = { "object.settings": (t: TypeId, n: string) => new MetaObject(t, n) }; + const lower = (apply: Apply) => () => + composeRegistry([...coreProviders, { id: "bad", dependencies: ["metaobjects-core-types"], registerTypes: (r) => apply(r, def, factories) }]); + expect(lower(applyProviderDefinition)).toThrow(); + expect(lower((r, d, f) => registerDefinition(r as TypeRegistry, d as PackDefinition, f))).toThrow(); + }); + } }); diff --git a/packs/config/typescript/test/generators.test.ts b/packs/config/typescript/test/generators.test.ts index 4bef69826..c200c64dd 100644 --- a/packs/config/typescript/test/generators.test.ts +++ b/packs/config/typescript/test/generators.test.ts @@ -111,8 +111,10 @@ describe("config pack generators", () => { }); test("a model with no settings and no vault writes none of the files", async () => { - const empty = { "metadata.root": { package: "acme::app", children: [] } }; - expect((await render([envExampleFile(), keyManifestFile(), keysAxiTomlFile()], empty)).size).toBe(0); + const entityOnly = { "metadata.root": { package: "acme::app", children: [ + { "object.entity": { name: "Customer", children: [{ "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }] } }, + ] } }; + expect((await render([envExampleFile(), keyManifestFile(), keysAxiTomlFile()], entityOnly)).size).toBe(0); }); test("core's entity generator types a settings group as it does a value object: no table", async () => { diff --git a/packs/config/typescript/test/settings.test.ts b/packs/config/typescript/test/settings.test.ts index 9e02ccf71..0d7a33f56 100644 --- a/packs/config/typescript/test/settings.test.ts +++ b/packs/config/typescript/test/settings.test.ts @@ -54,6 +54,30 @@ describe("readSettings", () => { expect(problems).toContain("acme::app::Db.x: environment variable DATABASE_URL is also acme::app::Database.url"); }); + test("refuses a derived name that is no variable, a non-scalar field, and invalid settings on an abstract base", async () => { + const model = withSettings([ + { "object.settings": { name: "Database", children: [{ "field.string": { name: "pool-size" } }] } }, + { "object.value": { name: "Nested", children: [{ "field.object": { name: "inner", "@objectRef": "acme::app::Nested" } }] } }, + { "object.settings": { name: "Api", extends: "Nested" } }, + { "object.settings": { name: "Base", abstract: true, children: [ + { "field.string": { name: "key", "@secret": true, "@default": "x", "@envName": "not-valid" } }, + ] } }, + ]); + let err: unknown; + try { + readSettings(await objects(model)); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(ConfigModelError); + const problems = (err as ConfigModelError).problems.join("\n"); + expect(problems).toContain('acme::app::Database.pool-size: the derived environment variable name "DATABASE_POOL-SIZE" is not valid'); + expect(problems).toContain("set @envName"); + expect(problems).toContain("acme::app::Api.inner: a setting is a scalar; field.object is not one of"); + expect(problems).toContain("acme::app::Base.key: a @secret setting may not declare @default"); + expect(problems).toContain('acme::app::Base.key: @envName "not-valid" is not an environment variable name'); + }); + test("an abstract group is read only through the groups that extend it", async () => { const groups = readSettings(await objects(withSettings([ { "object.settings": { name: "Base", abstract: true, children: [{ "field.string": { name: "host" } }] } }, From ffd6dbc1ee17e5e3a5a9d7e5486b81236080028a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 02:50:16 -0500 Subject: [PATCH 5/9] no-mistakes(review): scope misplaced-attr warning per run; add runGen tests --- packs/config/typescript/src/generators.ts | 6 +-- .../config/typescript/test/generators.test.ts | 40 ++++++++++++++++++- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/packs/config/typescript/src/generators.ts b/packs/config/typescript/src/generators.ts index eb6c843da..a5cfd0d46 100644 --- a/packs/config/typescript/src/generators.ts +++ b/packs/config/typescript/src/generators.ts @@ -52,7 +52,7 @@ function vaultsInScope(ctx: GenContext): Vault[] { return readVaults(ctx.loadedRoot, (key) => ctx.select?.(key) ?? true); } -/** Roots already checked for misplaced setting attributes: warn once per run, whichever generators run. */ +/** Runs already checked for misplaced setting attributes (a run shares one `entities` array): warn once per run, whichever generators run. */ const checked = new WeakSet(); function generator(name: string, opts: ConfigGeneratorOptions, generate: (ctx: GenContext) => EmittedFile[]): Generator { @@ -60,8 +60,8 @@ function generator(name: string, opts: ConfigGeneratorOptions, generate: (ctx: G name, ...(opts.target !== undefined ? { target: opts.target } : {}), generate(ctx) { - if (!checked.has(ctx.loadedRoot)) { - checked.add(ctx.loadedRoot); + if (!checked.has(ctx.entities)) { + checked.add(ctx.entities); for (const w of misplacedSettingAttrs(scopedObjects(ctx))) ctx.warn(`${PACKAGE}: ${w}`); } return generate(ctx); diff --git a/packs/config/typescript/test/generators.test.ts b/packs/config/typescript/test/generators.test.ts index c200c64dd..7a3897ce9 100644 --- a/packs/config/typescript/test/generators.test.ts +++ b/packs/config/typescript/test/generators.test.ts @@ -11,7 +11,7 @@ const scratch = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "pack-conf afterAll(() => rmSync(scratch, { recursive: true, force: true })); /** A dry run: every rendered file by its path relative to the output directory, nothing written. */ -async function render(generators: Generator[], model?: unknown): Promise> { +async function render(generators: Generator[], model?: unknown, warnings?: string[]): Promise> { const out = join(scratch, "out"); const res = await runGen({ config: defineConfig({ outDir: out, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators }), @@ -19,6 +19,7 @@ async function render(generators: Generator[], model?: unknown): Promise(); for (const [abs, content] of res.rendered ?? []) files.set(abs.slice(out.length + 1), content); return files; @@ -117,6 +118,43 @@ describe("config pack generators", () => { expect((await render([envExampleFile(), keyManifestFile(), keysAxiTomlFile()], entityOnly)).size).toBe(0); }); + test("setting attributes on a field outside a settings group warn once per run, not per generator", async () => { + const generators = [envExampleFile(), keyManifestFile(), keysAxiTomlFile()]; + const misplaced = { "metadata.root": { package: "acme::app", children: [ + { "object.value": { name: "Token", children: [{ "field.string": { name: "value", "@secret": true } }] } }, + { "object.settings": { name: "Ok", children: [{ "field.string": { name: "x", "@secret": true, "@phase": "build" } }] } }, + ] } }; + const first: string[] = []; + await render(generators, misplaced, first); + const found = first.filter((w) => w.includes("only mean something on a field of an object.settings")); + expect(found).toHaveLength(1); + expect(found[0]).toContain("acme::app::Token.value: @secret"); + expect(found[0]).not.toContain("Ok.x"); + + const second: string[] = []; + await render(generators, misplaced, second); + expect(second.filter((w) => w.includes("acme::app::Token.value"))).toHaveLength(1); + + const clean: string[] = []; + await render(generators, undefined, clean); + expect(clean.filter((w) => w.includes("only mean something"))).toEqual([]); + }); + + test("a second run over the same loaded root warns again", async () => { + const root = await loadModel({ "metadata.root": { package: "acme::app", children: [ + { "object.value": { name: "Token", children: [{ "field.string": { name: "value", "@envName": "TOKEN" } }] } }, + ] } }); + const warnings: string[] = []; + const run = () => runGen({ + config: defineConfig({ outDir: join(scratch, "out"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [envExampleFile(), keyManifestFile()] }), + metadata: root, + projectRoot: scratch, + dryRun: true, + }); + for (let i = 0; i < 2; i++) warnings.push(...(await run()).warnings.filter((w) => w.includes("Token.value"))); + expect(warnings).toHaveLength(2); + }); + test("core's entity generator types a settings group as it does a value object: no table", async () => { const files = await render([entityFile()]); expect(files.get("Customer.ts")).toContain("Table("); From cf55c75c2365b729d1bea3a6434248f641718059 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:15:27 -0500 Subject: [PATCH 6/9] no-mistakes(test): apply changes made during test validation --- packs/config/typescript/src/generators.ts | 18 ++++++++++++++++++ .../config/typescript/test/generators.test.ts | 11 +++++++++++ 2 files changed, 29 insertions(+) diff --git a/packs/config/typescript/src/generators.ts b/packs/config/typescript/src/generators.ts index a5cfd0d46..5534cdfb8 100644 --- a/packs/config/typescript/src/generators.ts +++ b/packs/config/typescript/src/generators.ts @@ -55,6 +55,23 @@ function vaultsInScope(ctx: GenContext): Vault[] { /** Runs already checked for misplaced setting attributes (a run shares one `entities` array): warn once per run, whichever generators run. */ const checked = new WeakSet(); +/** + * The settings and the vaults in one error: each reader stops at its own first problem, so + * reading them one after the other would name only the settings when the vault is also wrong. + */ +function checkModel(ctx: GenContext): void { + const problems: string[] = []; + for (const read of [() => readSettings(scopedObjects(ctx)), () => vaultsInScope(ctx)]) { + try { + read(); + } catch (e) { + if (!(e instanceof ConfigModelError)) throw e; + problems.push(...e.problems); + } + } + if (problems.length > 0) throw new ConfigModelError(problems); +} + function generator(name: string, opts: ConfigGeneratorOptions, generate: (ctx: GenContext) => EmittedFile[]): Generator { return { name, @@ -64,6 +81,7 @@ function generator(name: string, opts: ConfigGeneratorOptions, generate: (ctx: G checked.add(ctx.entities); for (const w of misplacedSettingAttrs(scopedObjects(ctx))) ctx.warn(`${PACKAGE}: ${w}`); } + checkModel(ctx); return generate(ctx); }, }; diff --git a/packs/config/typescript/test/generators.test.ts b/packs/config/typescript/test/generators.test.ts index 7a3897ce9..6213179b1 100644 --- a/packs/config/typescript/test/generators.test.ts +++ b/packs/config/typescript/test/generators.test.ts @@ -111,6 +111,17 @@ describe("config pack generators", () => { expect((await render([keysAxiTomlFile({ vault: "b" })], twoVaults)).get(".keys-axi.toml")).toContain('scope = "pb"'); }); + test("a run with a settings problem and a vault problem fails once, naming both", async () => { + const both = { "metadata.root": { package: "acme::app", children: [ + { "object.settings": { name: "Db", children: [{ "field.string": { name: "url", "@secret": true, "@default": "x" } }] } }, + { "vault.infisical": { name: "keys", "@defaultScope": "nope", children: [{ "scope.env": { name: "dev", "@project": "p" } }] } }, + ] } }; + const error = await render([envExampleFile(), keyManifestFile(), keysAxiTomlFile()], both).then(() => null, (e: unknown) => e); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain("acme::app::Db.url: a @secret setting may not declare @default"); + expect((error as Error).message).toContain('@defaultScope "nope" names no scope.env'); + }); + test("a model with no settings and no vault writes none of the files", async () => { const entityOnly = { "metadata.root": { package: "acme::app", children: [ { "object.entity": { name: "Customer", children: [{ "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }] } }, From 0d8084d4a63e65006f19cd40b59f2fba5d4d88e7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:17:21 -0500 Subject: [PATCH 7/9] no-mistakes(document): config pack README and fragment now accurate --- changelog.d/independent-packs-skeleton.md | 4 ++-- packs/config/README.md | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/changelog.d/independent-packs-skeleton.md b/changelog.d/independent-packs-skeleton.md index dbb6b41c7..f463971e3 100644 --- a/changelog.d/independent-packs-skeleton.md +++ b/changelog.d/independent-packs-skeleton.md @@ -1,7 +1,7 @@ - **Independent packs: the `packs/` directory, its gates and its lane (ADR-0069).** A capability that is not core vocabulary can now be built in `packs//` with its own version, changelog - and port list, outside the default bundle and outside `metamodelVersion`. No pack exists yet, - and nothing published changes. `scripts/check-pack-boundary.ts` fails a change that makes core + and port list, outside the default bundle and outside `metamodelVersion`. No pack is shipped + yet, and nothing published changes. `scripts/check-pack-boundary.ts` fails a change that makes core depend on a pack, puts a pack in the bundle, or lets core's release tooling see `packs/`. `scripts/check-pack-manifests.ts` holds each `pack.json` to its ports' native manifests. `scripts/pack-vocabulary.ts` pins the rows a pack adds and fails one that changes the bundle's, diff --git a/packs/config/README.md b/packs/config/README.md index 79ccf9271..79fc9d6fd 100644 --- a/packs/config/README.md +++ b/packs/config/README.md @@ -57,10 +57,11 @@ environment name, in the scope the vault maps to the environment being deployed. | `keysAxiTomlFile({ vault? })` | `.keys-axi.toml` | The vault's backend, default scope and one `[environments.]` table per scope, the file `keys-axi` reads so `keys-axi run` needs no project flag. Name the vault when the model declares more than one | Each takes `path` and `target`. No value of a secret ever reaches their output: the model -holds none. A problem the loader cannot see (two settings on one variable name, a malformed -`@envName`, a secret with a default, an array setting, a `@defaultScope` naming no scope, two -scopes on one Infisical environment, a vault with no scope) fails the run with every such -problem listed, each naming its node. +holds none. A problem the loader cannot see fails the run with every such problem listed, each +naming its node. These include: two settings on one variable name; a malformed `@envName`; a +derived variable name that is not valid; a setting that is not a scalar field, or is an array; +a secret with a default; a `@defaultScope` naming no scope; two scopes on one Infisical +environment; a vault with no scope. Abstract groups are checked too. ### Wiring @@ -81,8 +82,8 @@ export default defineConfig({ }); ``` -Vaults, like settings, are read inside the project's `scope`. `meta gen` runs no generator over a model with no object at all, so a model that declares a -vault and no settings group writes nothing. +Vaults, like settings, are read inside the project's `scope`. `meta gen` runs no generator over +a model with no object at all, so a model whose only declaration is a vault writes nothing. ## Checks From d5e3162873c0793f13af54f08dec7b2404465d49 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 03:49:28 -0500 Subject: [PATCH 8/9] no-mistakes(test): Fix config pack README wiring outDir; add runGen test --- packs/config/README.md | 6 +++- .../config/typescript/test/generators.test.ts | 29 ++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packs/config/README.md b/packs/config/README.md index 79fc9d6fd..ee832feec 100644 --- a/packs/config/README.md +++ b/packs/config/README.md @@ -65,13 +65,17 @@ environment; a vault with no scope. Abstract groups are checked too. ### Wiring -These files belong at the project root, so give them a target whose `outDir` is `"."`: +These files belong at the project root, so give them a target whose `outDir` is `"."`. The +top-level `outDir` and `dialect` are the project's own existing settings: `meta gen` requires a +top-level `outDir`, and `dialect` is needed when the model also has a persisted entity. ```ts import { defineConfig } from "@metaobjectsdev/cli"; import { configProvider, envExampleFile, keyManifestFile, keysAxiTomlFile } from "@metaobjectsdev/pack-config"; export default defineConfig({ + outDir: "src/generated", // the project's existing setting + dialect: "postgres", // the project's existing setting providers: [configProvider], targets: { root: { outDir: "." } }, generators: [ diff --git a/packs/config/typescript/test/generators.test.ts b/packs/config/typescript/test/generators.test.ts index 6213179b1..38853067d 100644 --- a/packs/config/typescript/test/generators.test.ts +++ b/packs/config/typescript/test/generators.test.ts @@ -1,5 +1,5 @@ import { afterAll, describe, expect, test } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { defineConfig, runGen, type Generator } from "@metaobjectsdev/codegen-ts"; @@ -166,6 +166,33 @@ describe("config pack generators", () => { expect(warnings).toHaveLength(2); }); + test("the README wiring writes the three files at the project root and nothing under the top-level outDir", async () => { + const root = mkdtempSync(join(scratch, "wiring-")); + // Exactly the README's wiring: the project's own outDir and dialect, plus a root target at ".". + const res = await runGen({ + config: defineConfig({ + outDir: "src/generated", + dialect: "postgres", + targets: { root: { outDir: "." } }, + generators: [ + envExampleFile({ target: "root" }), + keyManifestFile({ target: "root" }), + keysAxiTomlFile({ target: "root" }), + ], + }), + metadata: await loadModel(), + projectRoot: root, + }); + expect(res.warnings).toEqual([]); + expect(readFileSync(join(root, ".env.example"), "utf8")).toBe(ENV_EXAMPLE); + expect(readFileSync(join(root, ".keys-axi.toml"), "utf8")).toBe(KEYS_AXI_TOML); + expect(JSON.parse(readFileSync(join(root, "keys.manifest.json"), "utf8")).vaults).toHaveLength(1); + // Nothing from these generators lands under the top-level outDir. + expect(existsSync(join(root, "src", "generated", ".env.example"))).toBe(false); + expect(existsSync(join(root, "src", "generated", "keys.manifest.json"))).toBe(false); + expect(existsSync(join(root, "src", "generated", ".keys-axi.toml"))).toBe(false); + }); + test("core's entity generator types a settings group as it does a value object: no table", async () => { const files = await render([entityFile()]); expect(files.get("Customer.ts")).toContain("Table("); From 62043f120db794ea65f51c9ceff120583796cc4f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:02:16 -0500 Subject: [PATCH 9/9] no-mistakes(document): Config pack README: abstract group check scope --- packs/config/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packs/config/README.md b/packs/config/README.md index ee832feec..bf5d9aaca 100644 --- a/packs/config/README.md +++ b/packs/config/README.md @@ -61,7 +61,8 @@ holds none. A problem the loader cannot see fails the run with every such proble naming its node. These include: two settings on one variable name; a malformed `@envName`; a derived variable name that is not valid; a setting that is not a scalar field, or is an array; a secret with a default; a `@defaultScope` naming no scope; two scopes on one Infisical -environment; a vault with no scope. Abstract groups are checked too. +environment; a vault with no scope. An abstract group is checked for all of these except name +collisions, which are checked under each group that extends it. ### Wiring