@agentic-kit/db-tools 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +138 -0
- package/app-workspace.d.ts +16 -0
- package/app-workspace.js +145 -0
- package/context.d.ts +62 -0
- package/context.js +282 -0
- package/db-probe.d.ts +30 -0
- package/db-probe.js +50 -0
- package/esm/app-workspace.d.ts +16 -0
- package/esm/app-workspace.js +134 -0
- package/esm/context.d.ts +62 -0
- package/esm/context.js +270 -0
- package/esm/db-probe.d.ts +30 -0
- package/esm/db-probe.js +47 -0
- package/esm/host.d.ts +115 -0
- package/esm/host.js +23 -0
- package/esm/index.d.ts +20 -0
- package/esm/index.js +52 -0
- package/esm/policy/add-policies-to-table.d.ts +26 -0
- package/esm/policy/add-policies-to-table.js +66 -0
- package/esm/policy/provision-helpers.d.ts +38 -0
- package/esm/policy/provision-helpers.js +50 -0
- package/esm/provision-database/credential.d.ts +14 -0
- package/esm/provision-database/credential.js +19 -0
- package/esm/provision-database/env-file.d.ts +37 -0
- package/esm/provision-database/env-file.js +85 -0
- package/esm/provision-database/manifest.d.ts +10 -0
- package/esm/provision-database/manifest.js +48 -0
- package/esm/provision-database/pg-fixups.d.ts +16 -0
- package/esm/provision-database/pg-fixups.js +132 -0
- package/esm/provision-database/preset-match.d.ts +13 -0
- package/esm/provision-database/preset-match.js +66 -0
- package/esm/provision-database/presets.d.ts +4 -0
- package/esm/provision-database/presets.js +13 -0
- package/esm/provision-database/request-database.d.ts +61 -0
- package/esm/provision-database/request-database.js +130 -0
- package/esm/provision-database/resolve.d.ts +27 -0
- package/esm/provision-database/resolve.js +49 -0
- package/esm/records/meta.d.ts +41 -0
- package/esm/records/meta.js +167 -0
- package/esm/run-codegen/barrels.d.ts +3 -0
- package/esm/run-codegen/barrels.js +48 -0
- package/esm/run-codegen/endpoints.d.ts +8 -0
- package/esm/run-codegen/endpoints.js +46 -0
- package/esm/schema-resolve.d.ts +23 -0
- package/esm/schema-resolve.js +69 -0
- package/esm/tool-schema.d.ts +3 -0
- package/esm/tool-schema.js +10 -0
- package/esm/tools/add-policies.d.ts +24 -0
- package/esm/tools/add-policies.js +94 -0
- package/esm/tools/add-records.d.ts +18 -0
- package/esm/tools/add-records.js +122 -0
- package/esm/tools/add-relation-schema.d.ts +29 -0
- package/esm/tools/add-relation-schema.js +56 -0
- package/esm/tools/add-relation.d.ts +10 -0
- package/esm/tools/add-relation.js +91 -0
- package/esm/tools/create-api-key.d.ts +25 -0
- package/esm/tools/create-api-key.js +214 -0
- package/esm/tools/describe-schema.d.ts +19 -0
- package/esm/tools/describe-schema.js +130 -0
- package/esm/tools/manage-entity-types.d.ts +40 -0
- package/esm/tools/manage-entity-types.js +201 -0
- package/esm/tools/mutations.d.ts +35 -0
- package/esm/tools/mutations.js +230 -0
- package/esm/tools/provision-blueprint.d.ts +21 -0
- package/esm/tools/provision-blueprint.js +109 -0
- package/esm/tools/provision-database.d.ts +18 -0
- package/esm/tools/provision-database.js +260 -0
- package/esm/tools/run-codegen.d.ts +12 -0
- package/esm/tools/run-codegen.js +137 -0
- package/esm/tools/templates.d.ts +71 -0
- package/esm/tools/templates.js +331 -0
- package/host.d.ts +115 -0
- package/host.js +28 -0
- package/index.d.ts +20 -0
- package/index.js +76 -0
- package/package.json +49 -0
- package/policy/add-policies-to-table.d.ts +26 -0
- package/policy/add-policies-to-table.js +71 -0
- package/policy/provision-helpers.d.ts +38 -0
- package/policy/provision-helpers.js +58 -0
- package/provision-database/credential.d.ts +14 -0
- package/provision-database/credential.js +22 -0
- package/provision-database/env-file.d.ts +37 -0
- package/provision-database/env-file.js +91 -0
- package/provision-database/manifest.d.ts +10 -0
- package/provision-database/manifest.js +56 -0
- package/provision-database/pg-fixups.d.ts +16 -0
- package/provision-database/pg-fixups.js +170 -0
- package/provision-database/preset-match.d.ts +13 -0
- package/provision-database/preset-match.js +70 -0
- package/provision-database/presets.d.ts +4 -0
- package/provision-database/presets.js +17 -0
- package/provision-database/request-database.d.ts +61 -0
- package/provision-database/request-database.js +134 -0
- package/provision-database/resolve.d.ts +27 -0
- package/provision-database/resolve.js +53 -0
- package/records/meta.d.ts +41 -0
- package/records/meta.js +172 -0
- package/run-codegen/barrels.d.ts +3 -0
- package/run-codegen/barrels.js +54 -0
- package/run-codegen/endpoints.d.ts +8 -0
- package/run-codegen/endpoints.js +51 -0
- package/schema-resolve.d.ts +23 -0
- package/schema-resolve.js +75 -0
- package/tool-schema.d.ts +3 -0
- package/tool-schema.js +13 -0
- package/tools/add-policies.d.ts +24 -0
- package/tools/add-policies.js +97 -0
- package/tools/add-records.d.ts +18 -0
- package/tools/add-records.js +125 -0
- package/tools/add-relation-schema.d.ts +29 -0
- package/tools/add-relation-schema.js +60 -0
- package/tools/add-relation.d.ts +10 -0
- package/tools/add-relation.js +94 -0
- package/tools/create-api-key.d.ts +25 -0
- package/tools/create-api-key.js +220 -0
- package/tools/describe-schema.d.ts +19 -0
- package/tools/describe-schema.js +133 -0
- package/tools/manage-entity-types.d.ts +40 -0
- package/tools/manage-entity-types.js +206 -0
- package/tools/mutations.d.ts +35 -0
- package/tools/mutations.js +233 -0
- package/tools/provision-blueprint.d.ts +21 -0
- package/tools/provision-blueprint.js +112 -0
- package/tools/provision-database.d.ts +18 -0
- package/tools/provision-database.js +266 -0
- package/tools/run-codegen.d.ts +12 -0
- package/tools/run-codegen.js +141 -0
- package/tools/templates.d.ts +71 -0
- package/tools/templates.js +335 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# @agentic-kit/db-tools
|
|
2
|
+
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
<a href="https://www.npmjs.com/package/@agentic-kit/db-tools"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=agentic%2Fdb-tools%2Fpackage.json"/></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
The Constructive typed database tools, as **harness-neutral** [`HarnessTool`](https://www.npmjs.com/package/@agentic-kit/harness)s: zod parameters, `execute(params, { cwd, signal })`, and no coding-agent SDK anywhere in the package. Binding them to a harness is the *adapter's* job — [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) does it with `toPiTool()` — so a second, compatible harness registers the same 18 tools without a fork.
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
@agentic-kit/db-tools ──► @agentic-kit/harness (HarnessTool)
|
|
19
|
+
▲
|
|
20
|
+
├── @agentic-kit/pi toPiTool() ──► pi's ToolDefinition
|
|
21
|
+
└── your adapter toXTool() ──► your harness's tool shape
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install @agentic-kit/db-tools
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## What's inside
|
|
29
|
+
|
|
30
|
+
- **18 typed db tools** — `provision_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `delete_field`, `add_policies`, `add_records`, `manage_entity_types`, `create_api_key`, `run_codegen`, and the template suite (`list` / `create` / `apply` / `update` / `delete`). `constructiveDbTools` is the list, in registration order.
|
|
31
|
+
- **Host injection** — credentials, backend endpoints and data-plane tokens come from the host application, not from the package. Call `configureHost()` once at startup; the tools read it lazily per call.
|
|
32
|
+
- **Project context** — `resolveProjectContext` / `resolveDataToken` resolve the database a tool acts on from the cwd's `.env` plus the host's session, and `deriveSubdomainEndpoint` derives its per-database endpoints.
|
|
33
|
+
- **Provisioning model** — the pinned `node-type-registry` presets, the provision manifest, and overlay resolution (`resolveProvisionModules`).
|
|
34
|
+
- **`toolSchema`** — a tool's zod parameters as plain JSON Schema, for adapters whose harness wants JSON Schema rather than zod.
|
|
35
|
+
|
|
36
|
+
## Usage
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { configureHost, constructiveDbTools } from '@agentic-kit/db-tools';
|
|
40
|
+
|
|
41
|
+
configureHost({
|
|
42
|
+
account: () => ({ userId, accessToken }),
|
|
43
|
+
backendConfig: () => ({ apiEndpoint, modulesEndpoint }),
|
|
44
|
+
signInHint: 'Run `agent login` to sign in.'
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
for (const tool of constructiveDbTools) {
|
|
48
|
+
myHarness.registerTool(myToolBinding(tool));
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A tool executes against nothing but its params and a context, so it is callable directly — which is also how the tests drive it:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const result = await describeSchemaTool.execute({ database_name: 'my-app' }, { cwd: process.cwd() });
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Related
|
|
59
|
+
|
|
60
|
+
| Package | Role |
|
|
61
|
+
| --- | --- |
|
|
62
|
+
| [`@agentic-kit/harness`](https://www.npmjs.com/package/@agentic-kit/harness) | the neutral contracts: `HarnessTool`, `HarnessAdapter`, the run gate |
|
|
63
|
+
| [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) | the pi adapter: binds these tools and attaches a run's lanes to a pi session |
|
|
64
|
+
| [`@agentic-kit/cli`](https://www.npmjs.com/package/@agentic-kit/cli) | the `agent` CLI, which materializes the tools into a pi agent dir |
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Education and Tutorials
|
|
69
|
+
|
|
70
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
71
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
72
|
+
|
|
73
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
74
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
75
|
+
|
|
76
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
77
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
78
|
+
|
|
79
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
80
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
81
|
+
|
|
82
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
83
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
84
|
+
|
|
85
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
86
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
87
|
+
|
|
88
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
89
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
90
|
+
|
|
91
|
+
## Related Constructive Tooling
|
|
92
|
+
|
|
93
|
+
### 📦 Package Management
|
|
94
|
+
|
|
95
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
96
|
+
|
|
97
|
+
### 🧪 Testing
|
|
98
|
+
|
|
99
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
100
|
+
* [pglite-test](https://github.com/constructive-io/constructive/tree/main/postgres/pglite-test): **🪶 Drop-in pgsql-test replacement backed by PGlite** — in-process Postgres, no server required, instance-per-suite isolation.
|
|
101
|
+
* [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
|
|
102
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
103
|
+
* [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
104
|
+
* [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
|
|
105
|
+
|
|
106
|
+
### 🧠 Parsing & AST
|
|
107
|
+
|
|
108
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
109
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
110
|
+
* [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
|
|
111
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
112
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
113
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
114
|
+
|
|
115
|
+
### 📚 Documentation & Skills
|
|
116
|
+
|
|
117
|
+
* [constructive-skills](https://github.com/constructive-io/constructive-skills): **📖 Platform documentation and AI agent skills** — feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
|
|
118
|
+
|
|
119
|
+
Install skills for AI coding agents:
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
123
|
+
npx skills add constructive-io/constructive-skills
|
|
124
|
+
|
|
125
|
+
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
126
|
+
npx skills add https://github.com/constructive-io/constructive --skill pgpm
|
|
127
|
+
npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Credits
|
|
131
|
+
|
|
132
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
133
|
+
|
|
134
|
+
## Disclaimer
|
|
135
|
+
|
|
136
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
137
|
+
|
|
138
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const NATIVE_BUILD_DEPS: string[];
|
|
2
|
+
export declare const IGNORED_BUILDS_RE: RegExp;
|
|
3
|
+
export declare function run(cmd: string, args: string[], cwd: string, env?: Record<string, string>): Promise<{
|
|
4
|
+
ok: boolean;
|
|
5
|
+
out: string;
|
|
6
|
+
}>;
|
|
7
|
+
export declare function ensureWorkspaceConfig(cwd: string): Promise<void>;
|
|
8
|
+
export declare function pinCodegenLatest(appDir: string): Promise<void>;
|
|
9
|
+
export declare function ensureAppScaffold(cwd: string): Promise<{
|
|
10
|
+
ok: boolean;
|
|
11
|
+
out: string;
|
|
12
|
+
}>;
|
|
13
|
+
export declare function prewarmAppWorkspace(cwd: string): Promise<{
|
|
14
|
+
ok: boolean;
|
|
15
|
+
out: string;
|
|
16
|
+
}>;
|
package/app-workspace.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.IGNORED_BUILDS_RE = exports.NATIVE_BUILD_DEPS = void 0;
|
|
7
|
+
exports.run = run;
|
|
8
|
+
exports.ensureWorkspaceConfig = ensureWorkspaceConfig;
|
|
9
|
+
exports.pinCodegenLatest = pinCodegenLatest;
|
|
10
|
+
exports.ensureAppScaffold = ensureAppScaffold;
|
|
11
|
+
exports.prewarmAppWorkspace = prewarmAppWorkspace;
|
|
12
|
+
const node_child_process_1 = require("node:child_process");
|
|
13
|
+
const node_fs_1 = require("node:fs");
|
|
14
|
+
const promises_1 = require("node:fs/promises");
|
|
15
|
+
const node_os_1 = __importDefault(require("node:os"));
|
|
16
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
17
|
+
const node_util_1 = require("node:util");
|
|
18
|
+
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
|
|
19
|
+
// pnpm 11.8 no longer reads the `pnpm` field from a non-root package.json, so the
|
|
20
|
+
// template's `pnpm.overrides.graphql` (in packages/app/package.json) is silently
|
|
21
|
+
// ignored. Without that override two graphql versions (16.13.0 + 16.14.0) get
|
|
22
|
+
// installed, which instantiates two copies of `grafast` under DIFFERENT
|
|
23
|
+
// peer-dependency hash contexts. graphile-search then resolves in one context
|
|
24
|
+
// while graphile-connection-filter was linked under the other, so codegen dies
|
|
25
|
+
// with `Cannot find module 'graphile-connection-filter'`. Hoisting the override
|
|
26
|
+
// to the ROOT pnpm-workspace.yaml (which pnpm 11.8 DOES read) collapses graphql —
|
|
27
|
+
// and therefore grafast — to a single version, and the missing module resolves
|
|
28
|
+
// (PNPM-GRAPHQL-OVERRIDE-001). We also strip the nested packages/app
|
|
29
|
+
// pnpm-workspace.yaml the template ships, and keep onlyBuiltDependencies so the
|
|
30
|
+
// native deps build where honored (PNPM-BUILDS-001).
|
|
31
|
+
exports.NATIVE_BUILD_DEPS = ['esbuild', 'sharp', 'unrs-resolver'];
|
|
32
|
+
exports.IGNORED_BUILDS_RE = /ERR_PNPM_IGNORED_BUILDS|Ignored build scripts/;
|
|
33
|
+
const DEFAULT_GRAPHQL_OVERRIDE = '16.14.0';
|
|
34
|
+
const TEMPLATE_REPO = 'https://github.com/constructive-io/sandbox-templates';
|
|
35
|
+
const TEMPLATE_SUBDIR = node_path_1.default.join('nextjs', 'constructive-app');
|
|
36
|
+
async function run(cmd, args, cwd, env) {
|
|
37
|
+
try {
|
|
38
|
+
const { stdout, stderr } = await execFileAsync(cmd, args, {
|
|
39
|
+
cwd,
|
|
40
|
+
timeout: 5 * 60_000,
|
|
41
|
+
encoding: 'utf-8',
|
|
42
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
43
|
+
env: env ? { ...process.env, ...env } : process.env,
|
|
44
|
+
});
|
|
45
|
+
return { ok: true, out: `${stdout}${stderr}`.trim() };
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
const e = err;
|
|
49
|
+
return { ok: false, out: `${e.stdout ?? ''}${e.stderr ?? ''}`.trim() || e.message || 'failed' };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
// Read the graphql pin the template wants from its (now-ignored) pnpm.overrides
|
|
53
|
+
// so we propagate the template's own value instead of hardcoding ours.
|
|
54
|
+
async function templateGraphqlOverride(cwd) {
|
|
55
|
+
try {
|
|
56
|
+
const pkg = JSON.parse(await (0, promises_1.readFile)(node_path_1.default.join(cwd, 'packages', 'app', 'package.json'), 'utf8'));
|
|
57
|
+
const v = pkg?.pnpm?.overrides?.graphql;
|
|
58
|
+
return typeof v === 'string' && v.length > 0 ? v : DEFAULT_GRAPHQL_OVERRIDE;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return DEFAULT_GRAPHQL_OVERRIDE;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async function ensureWorkspaceConfig(cwd) {
|
|
65
|
+
const nested = node_path_1.default.join(cwd, 'packages', 'app', 'pnpm-workspace.yaml');
|
|
66
|
+
if ((0, node_fs_1.existsSync)(nested)) {
|
|
67
|
+
await (0, promises_1.rm)(nested, { force: true });
|
|
68
|
+
}
|
|
69
|
+
const graphqlPin = await templateGraphqlOverride(cwd);
|
|
70
|
+
const builds = exports.NATIVE_BUILD_DEPS.map((d) => ` - ${d}`).join('\n');
|
|
71
|
+
const text = `packages:\n - "packages/*"\n\n` +
|
|
72
|
+
`overrides:\n graphql: ${graphqlPin}\n\n` +
|
|
73
|
+
`onlyBuiltDependencies:\n${builds}\n`;
|
|
74
|
+
await (0, promises_1.writeFile)(node_path_1.default.join(cwd, 'pnpm-workspace.yaml'), text);
|
|
75
|
+
}
|
|
76
|
+
// Force @constructive-io/graphql-codegen to `latest` in the app package.json
|
|
77
|
+
// before the single install — older 4.9.x throws on PostGraphile `filter` inputs
|
|
78
|
+
// (TS-001).
|
|
79
|
+
async function pinCodegenLatest(appDir) {
|
|
80
|
+
const pkgPath = node_path_1.default.join(appDir, 'package.json');
|
|
81
|
+
const pkg = JSON.parse(await (0, promises_1.readFile)(pkgPath, 'utf8'));
|
|
82
|
+
for (const field of ['devDependencies', 'dependencies']) {
|
|
83
|
+
if (pkg[field]?.['@constructive-io/graphql-codegen']) {
|
|
84
|
+
pkg[field]['@constructive-io/graphql-codegen'] = 'latest';
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
await (0, promises_1.writeFile)(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
|
88
|
+
}
|
|
89
|
+
// The Constructive Next.js app is just the `nextjs/constructive-app` tree from
|
|
90
|
+
// the sandbox-templates repo — it ships no `____VAR____` placeholders, so there
|
|
91
|
+
// is nothing to templatize. `pgpm init` only fetches and copies that tree, but
|
|
92
|
+
// its CLI is unreliable in the non-TTY agent shell, which made the agent thrash
|
|
93
|
+
// for minutes. Materialize `packages/app` deterministically by shallow-cloning
|
|
94
|
+
// the template instead (PGPM-001).
|
|
95
|
+
async function ensureAppScaffold(cwd) {
|
|
96
|
+
const appDir = node_path_1.default.join(cwd, 'packages', 'app');
|
|
97
|
+
if ((0, node_fs_1.existsSync)(node_path_1.default.join(appDir, 'package.json'))) {
|
|
98
|
+
return { ok: true, out: 'packages/app already scaffolded' };
|
|
99
|
+
}
|
|
100
|
+
const tmp = node_path_1.default.join(node_os_1.default.tmpdir(), `airpage-app-template-${process.pid}`);
|
|
101
|
+
await (0, promises_1.rm)(tmp, { recursive: true, force: true });
|
|
102
|
+
const clone = await run('git', ['clone', '--depth', '1', TEMPLATE_REPO, tmp], cwd);
|
|
103
|
+
if (!clone.ok) {
|
|
104
|
+
await (0, promises_1.rm)(tmp, { recursive: true, force: true });
|
|
105
|
+
return { ok: false, out: `Template clone failed:\n${clone.out}` };
|
|
106
|
+
}
|
|
107
|
+
const src = node_path_1.default.join(tmp, TEMPLATE_SUBDIR);
|
|
108
|
+
if (!(0, node_fs_1.existsSync)(src)) {
|
|
109
|
+
await (0, promises_1.rm)(tmp, { recursive: true, force: true });
|
|
110
|
+
return { ok: false, out: `Template subdir ${TEMPLATE_SUBDIR} missing in ${TEMPLATE_REPO}` };
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
await (0, promises_1.mkdir)(node_path_1.default.dirname(appDir), { recursive: true });
|
|
114
|
+
await (0, promises_1.cp)(src, appDir, { recursive: true });
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
await (0, promises_1.rm)(tmp, { recursive: true, force: true });
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
out: `Copying template into packages/app failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
await (0, promises_1.rm)(tmp, { recursive: true, force: true });
|
|
124
|
+
return { ok: true, out: 'Scaffolded packages/app from the constructive-app template.' };
|
|
125
|
+
}
|
|
126
|
+
// Scaffold packages/app, hoist the workspace config, pin codegen, and run the one
|
|
127
|
+
// clean install. All of this is database-INDEPENDENT, so it can be prewarmed
|
|
128
|
+
// concurrently with the ~90s provision_database backend mutation to keep clone +
|
|
129
|
+
// install off run_codegen's critical path. Best-effort and fully idempotent:
|
|
130
|
+
// run_codegen re-runs the same steps, finding the scaffold present and the install
|
|
131
|
+
// already satisfied (a fast no-op). Errors are swallowed by callers that prewarm —
|
|
132
|
+
// run_codegen surfaces any real failure later.
|
|
133
|
+
async function prewarmAppWorkspace(cwd) {
|
|
134
|
+
const scaffold = await ensureAppScaffold(cwd);
|
|
135
|
+
if (!scaffold.ok)
|
|
136
|
+
return scaffold;
|
|
137
|
+
const appDir = node_path_1.default.join(cwd, 'packages', 'app');
|
|
138
|
+
await ensureWorkspaceConfig(cwd);
|
|
139
|
+
await pinCodegenLatest(appDir);
|
|
140
|
+
const install = await run('pnpm', ['install', '--no-frozen-lockfile'], cwd);
|
|
141
|
+
if (!install.ok && !exports.IGNORED_BUILDS_RE.test(install.out)) {
|
|
142
|
+
return { ok: false, out: `pnpm install failed:\n${install.out}` };
|
|
143
|
+
}
|
|
144
|
+
return { ok: true, out: 'Prewarmed packages/app scaffold + install.' };
|
|
145
|
+
}
|
package/context.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { api, modules } from '@constructive-io/sdk';
|
|
2
|
+
export type ApiClient = ReturnType<typeof api.createClient>;
|
|
3
|
+
export type ModulesClient = ReturnType<typeof modules.createClient>;
|
|
4
|
+
export type ProjectContext = {
|
|
5
|
+
api: ApiClient;
|
|
6
|
+
modules: ModulesClient;
|
|
7
|
+
databaseId: string;
|
|
8
|
+
schemaId: string;
|
|
9
|
+
ownerId: string | undefined;
|
|
10
|
+
apiEndpoint: string;
|
|
11
|
+
modulesEndpoint: string;
|
|
12
|
+
databaseName: string;
|
|
13
|
+
accessToken: string;
|
|
14
|
+
dataEndpoint: string;
|
|
15
|
+
};
|
|
16
|
+
export type ProjectContextFailureCode = 'no-env' | 'missing-credentials' | 'db-missing' | 'account-mismatch' | 'backend-unreachable' | 'schema-unresolved';
|
|
17
|
+
export type ResolveResult = {
|
|
18
|
+
context: ProjectContext | null;
|
|
19
|
+
reason: string;
|
|
20
|
+
code?: ProjectContextFailureCode;
|
|
21
|
+
};
|
|
22
|
+
export declare const CONTEXT_ENV_KEYS: readonly ["ACCESS_TOKEN", "DATABASE_ID", "API_ENDPOINT", "MODULES_ENDPOINT", "DATABASE_NAME", "OWNER_ID"];
|
|
23
|
+
export type ContextEnvKey = (typeof CONTEXT_ENV_KEYS)[number];
|
|
24
|
+
/** Prefix for injected variables: `ACCESS_TOKEN` is far too generic to claim in
|
|
25
|
+
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not. Inside a
|
|
26
|
+
* project `.env` the bare names stay readable (and are what the scaffolder
|
|
27
|
+
* writes), so both spellings resolve, prefixed winning. */
|
|
28
|
+
export declare const CONTEXT_ENV_PREFIX = "CONSTRUCTIVE_";
|
|
29
|
+
/** Values keyed by name, or a lookup function (a host with a secret store). */
|
|
30
|
+
export type ContextSource = Record<string, string | undefined> | ((name: string) => string | undefined);
|
|
31
|
+
/** Use the process environment (or any injected record) as the source. */
|
|
32
|
+
export declare function fromEnvironment(environment?: Record<string, string | undefined>): ContextSource;
|
|
33
|
+
/** Read a project `.env` as the source. The file is authoritative here — the
|
|
34
|
+
* key in it belongs to whatever backend wrote it, so it is not merged under
|
|
35
|
+
* the ambient environment. Returns null when the file is absent. */
|
|
36
|
+
export declare function fromEnvFile(cwd: string): Promise<ContextSource | null>;
|
|
37
|
+
export type ResolveOptions = {
|
|
38
|
+
/** Which plane the context is for. Ownership gates the control plane only:
|
|
39
|
+
* schema editing and provisioning act under the signed-in account, so a
|
|
40
|
+
* foreign-owned binding is blocked ('account-mismatch'). The data plane
|
|
41
|
+
* (real rows via app end-user tokens) never checks desktop-account
|
|
42
|
+
* ownership — a live foreign-owned database serves data fine, exactly as
|
|
43
|
+
* the app itself does in the Preview. */
|
|
44
|
+
plane?: 'control' | 'data';
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Resolve the project context from injected values, or from a project folder.
|
|
48
|
+
*
|
|
49
|
+
* Passing a `cwd` string keeps the original behavior (read `<cwd>/.env`) so
|
|
50
|
+
* existing hosts — Constructive Desktop, the confirm gate — are unchanged.
|
|
51
|
+
* Headless hosts pass values instead: `fromEnvironment()` for a container or
|
|
52
|
+
* Job, an explicit record for anything else.
|
|
53
|
+
*/
|
|
54
|
+
export declare function resolveProjectContext(input: string | ContextSource, options?: ResolveOptions): Promise<ResolveResult>;
|
|
55
|
+
export type DataTokenResult = {
|
|
56
|
+
token?: string;
|
|
57
|
+
userId?: string;
|
|
58
|
+
reason?: string;
|
|
59
|
+
};
|
|
60
|
+
export declare function resolveDataToken(context: ProjectContext): Promise<DataTokenResult>;
|
|
61
|
+
export declare function deriveSubdomainEndpoint(baseEndpoint: string, firstLabel: string): string;
|
|
62
|
+
export declare function resolveOrgName(ownerId: string): Promise<string | undefined>;
|