@ductape/cli 0.4.1 → 0.4.3

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.
@@ -1,5 +1,6 @@
1
1
  export type ComponentActionKind = 'graph' | 'vector';
2
2
  export type ComponentActionVerb = 'create' | 'update' | 'get' | 'list' | 'delete' | 'execute';
3
+ export declare function assertComponentActionResult(kind: ComponentActionKind, verb: ComponentActionVerb, result: unknown): void;
3
4
  export declare function runComponentActions(kind: ComponentActionKind, verb: ComponentActionVerb, opts: {
4
5
  resource?: string;
5
6
  action?: string;
@@ -1,6 +1,15 @@
1
1
  import { readJsonBody } from '../lib/read-body.js';
2
2
  import { getSdkProxy, requireSession } from '../lib/proxy/context.js';
3
3
  import { printJson } from '../lib/output.js';
4
+ export function assertComponentActionResult(kind, verb, result) {
5
+ if (verb === 'get' && (result === null || result === undefined)) {
6
+ throw new Error(`${kind} action was not found in the canonical product catalogue`);
7
+ }
8
+ if (verb === 'execute' && result && typeof result === 'object' && result.success === false) {
9
+ const message = result.error ?? result.message;
10
+ throw new Error(`${kind} action execution failed${message ? `: ${String(message)}` : ''}`);
11
+ }
12
+ }
4
13
  export async function runComponentActions(kind, verb, opts) {
5
14
  const session = requireSession();
6
15
  const body = readJsonBody(opts.file) ?? {};
@@ -41,5 +50,6 @@ export async function runComponentActions(kind, verb, opts) {
41
50
  params = [{ product: session.project.product_tag, env: session.project.env_slug, ...body }];
42
51
  }
43
52
  const result = await getSdkProxy(session).execute(kind, method, params);
53
+ assertComponentActionResult(kind, verb, result);
44
54
  printJson(result, Boolean(opts.json));
45
55
  }
@@ -2,6 +2,8 @@ interface MigrateOpts {
2
2
  env?: string;
3
3
  db?: string;
4
4
  dryRun?: boolean;
5
+ to?: string;
6
+ json?: boolean;
5
7
  }
6
8
  interface MigrateStatusOpts {
7
9
  env?: string;
@@ -14,6 +16,7 @@ interface MigrateRollbackOpts {
14
16
  n?: number;
15
17
  }
16
18
  export declare function runDbMigrate(opts: MigrateOpts): Promise<void>;
19
+ export declare function runDbMigrateBaseline(opts: MigrateOpts): Promise<void>;
17
20
  export declare function runDbMigrateStatus(opts: MigrateStatusOpts): Promise<void>;
18
21
  export declare function runDbMigrateRollback(opts: MigrateRollbackOpts): Promise<void>;
19
22
  export {};
@@ -67,25 +67,38 @@ export async function runDbMigrate(opts) {
67
67
  const dbContext = buildDbContext(db, envSlug, productTag);
68
68
  const migrations = loadMigrationFiles(dir, db);
69
69
  if (migrations.length === 0) {
70
- console.log(`[${db}] No migration files found. Run \`ductape db schema generate\` first.`);
70
+ if (!opts.json)
71
+ console.log(`[${db}] No migration files found. Run \`ductape db schema generate\` first.`);
71
72
  continue;
72
73
  }
73
74
  const appliedTags = await getAppliedTags(proxy, dbContext);
74
- const pending = migrations.filter((m) => !appliedTags.includes(m.tag));
75
+ const targetIndex = opts.to ? migrations.findIndex(m => m.tag === opts.to) : migrations.length - 1;
76
+ if (targetIndex < 0)
77
+ fail(`Unknown migration target: ${opts.to}`);
78
+ const selected = migrations.slice(0, targetIndex + 1);
79
+ const pending = selected.filter((m) => !appliedTags.includes(m.tag));
80
+ // The SDK plans the whole chain, checks dependencies, and blocks replay into an existing database.
81
+ const plan = await proxy.execute('migration.run', [migrations, { dryRun: true, to: opts.to }], dbContext);
82
+ if (opts.dryRun) {
83
+ totalDry += pending.length;
84
+ if (opts.json)
85
+ printJson({ database: db, mutationState: 'not_attempted', plan }, true);
86
+ else
87
+ console.log(`[${db}] Dry run: ${pending.map(m => m.tag).join(', ')}`);
88
+ continue;
89
+ }
75
90
  if (pending.length === 0) {
76
- console.log(`[${db}] Already up to date.`);
91
+ if (!opts.json)
92
+ console.log(`[${db}] Already up to date.`);
77
93
  continue;
78
94
  }
79
- console.log(`[${db}] ${pending.length} pending migration(s).`);
95
+ if (!opts.json)
96
+ console.log(`[${db}] ${pending.length} pending migration(s).`);
80
97
  for (const migration of pending) {
81
- if (opts.dryRun) {
82
- console.log(` [dry-run] Would apply: ${migration.tag}`);
83
- totalDry++;
84
- continue;
85
- }
86
- process.stdout.write(` Applying ${migration.tag}... `);
98
+ if (!opts.json)
99
+ process.stdout.write(` Applying ${migration.tag}... `);
87
100
  try {
88
- const response = await proxy.execute('migration.run', [[migration]], dbContext);
101
+ const response = await proxy.execute('migration.run', [migrations, { to: migration.tag }], dbContext);
89
102
  const migrationResult = getMigrationResult(response, migration.tag);
90
103
  if (migrationResult && !migrationResult.success) {
91
104
  throw new Error(migrationResult.error ?? 'SDK reported an unsuccessful migration');
@@ -97,24 +110,42 @@ export async function runDbMigrate(opts) {
97
110
  if (!appliedAfterRun.includes(migration.tag)) {
98
111
  throw new Error('the operation returned without error, but the migration tag is absent from migration history');
99
112
  }
100
- console.log('done');
113
+ if (!opts.json)
114
+ console.log('done');
101
115
  totalApplied++;
102
116
  }
103
117
  catch (err) {
104
- console.log('unverified');
118
+ if (!opts.json)
119
+ console.log('unverified');
105
120
  fail(`Migration "${migration.tag}" could not be verified: ` +
106
121
  `${err instanceof Error ? err.message : String(err)}. ` +
107
122
  'Do not rerun it until the live schema and migration history have been inspected.');
108
123
  }
109
124
  }
110
125
  }
111
- if (opts.dryRun) {
126
+ if (opts.json) {
127
+ if (!opts.dryRun)
128
+ printJson({ mutationState: 'confirmed', applied: totalApplied }, true);
129
+ }
130
+ else if (opts.dryRun) {
112
131
  console.log(`\nDry run: ${totalDry} migration(s) would be applied.`);
113
132
  }
114
133
  else {
115
134
  console.log(`\nApplied ${totalApplied} migration(s).`);
116
135
  }
117
136
  }
137
+ export async function runDbMigrateBaseline(opts) {
138
+ const found = findProjectConfig();
139
+ if (!found)
140
+ fail('No linked project. Run ductape link.');
141
+ if (!opts.db || !opts.to)
142
+ fail('Baseline requires --db and --to.');
143
+ const session = requireSession();
144
+ const context = buildDbContext(opts.db, opts.env ?? session.project.env_slug, session.project.product_tag);
145
+ const migrations = loadMigrationFiles(found.dir, opts.db);
146
+ const result = await getDbProxy(session).execute('migration.baseline', [migrations, { to: opts.to, dryRun: Boolean(opts.dryRun) }], context);
147
+ printJson(result, true);
148
+ }
118
149
  export async function runDbMigrateStatus(opts) {
119
150
  const found = findProjectConfig();
120
151
  if (!found)
@@ -134,7 +165,7 @@ export async function runDbMigrateStatus(opts) {
134
165
  const appliedTags = await getAppliedTags(proxy, dbContext);
135
166
  const applied = migrations.filter((m) => appliedTags.includes(m.tag)).map((m) => m.tag);
136
167
  const pending = migrations.filter((m) => !appliedTags.includes(m.tag)).map((m) => m.tag);
137
- statusReport[db] = { applied, pending };
168
+ statusReport[db] = { applied, pending, mutationState: 'not_attempted' };
138
169
  if (!opts.json) {
139
170
  console.log(`\n[${db}]`);
140
171
  if (applied.length > 0) {
@@ -357,6 +357,10 @@ function adaptColumn(col) {
357
357
  }
358
358
  export async function runDbSchemaPush(opts) {
359
359
  const session = requireSession();
360
+ const project = findProjectConfig();
361
+ const localEntry = project && fs.existsSync(getSchemaPath(project.dir))
362
+ ? loadSchemaFile(project.dir).find((entry) => entry.db === opts.db)
363
+ : undefined;
360
364
  const proxy = getDbProxy(session);
361
365
  const envSlug = opts.env;
362
366
  const productTag = session.project.product_tag;
@@ -382,12 +386,17 @@ export async function runDbSchemaPush(opts) {
382
386
  for (const tableName of tableNames) {
383
387
  try {
384
388
  const tableSchema = await proxy.execute('schema.describe', [tableName], dbContext);
385
- const cols = Array.isArray(tableSchema?.columns)
389
+ let cols = Array.isArray(tableSchema?.columns)
386
390
  ? tableSchema.columns
387
391
  : Array.isArray(tableSchema) ? tableSchema : [];
388
392
  if (cols.length === 0) {
389
- console.warn(` [skip] ${tableName}: no columns returned`);
390
- continue;
393
+ const localDefinition = localEntry?.tables?.[tableName];
394
+ if (!localDefinition) {
395
+ console.warn(` [skip] ${tableName}: no live columns or code-first definition returned`);
396
+ continue;
397
+ }
398
+ cols = parseTableDef(tableName, localDefinition).fields;
399
+ console.log(` ${tableName}: using code-first schema because the collection is empty`);
391
400
  }
392
401
  const columns = cols
393
402
  .filter((c) => c.name)
@@ -115,7 +115,7 @@ export async function runDbActions(verb, opts, extraArgs) {
115
115
  if (!databaseTag) {
116
116
  throw new Error('list requires --database <product_tag:database_tag>');
117
117
  }
118
- method = 'action.fetchAll';
118
+ method = 'action.list';
119
119
  params = [databaseTag];
120
120
  break;
121
121
  }
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import { runResourceCrud, runResourcesList, runEventTopicCrud, runNotificationMe
17
17
  import { runCloud, runCloudPreflight } from './commands/cloud.js';
18
18
  import { runDb, runDbActions, runDbContext } from './commands/db.js';
19
19
  import { runComponentActions } from './commands/component-actions.js';
20
- import { runDbMigrate, runDbMigrateStatus, runDbMigrateRollback } from './commands/db-migrate.js';
20
+ import { runDbMigrate, runDbMigrateStatus, runDbMigrateRollback, runDbMigrateBaseline } from './commands/db-migrate.js';
21
21
  import { runFeaturesSync, runFeaturesValidate } from './commands/features-sync.js';
22
22
  import { runSessionsValidate } from './commands/sessions-validate.js';
23
23
  import { runDbSchemaGenerate, runDbSchemaPush } from './commands/db-schema.js';
@@ -809,7 +809,17 @@ const dbMigrate = db
809
809
  .option('--env <tag>', 'Override environment slug')
810
810
  .option('--db <tag>', 'Limit to one db entry from schema.json')
811
811
  .option('--dry-run', 'Print what would run without applying')
812
- .action(wrap((opts) => runDbMigrate({ env: opts.env, db: opts.db, dryRun: Boolean(opts.dryRun) })));
812
+ .option('--to <tag>', 'Apply through this migration, including dependencies')
813
+ .option('--json', 'Structured result')
814
+ .action(wrap((opts) => runDbMigrate({ env: opts.env, db: opts.db, to: opts.to, json: Boolean(opts.json), dryRun: Boolean(opts.dryRun) })));
815
+ dbMigrate.command('baseline')
816
+ .description('Verify live MongoDB schema and adopt migration history without replaying it')
817
+ .requiredOption('--db <tag>')
818
+ .requiredOption('--to <tag>')
819
+ .option('--env <tag>')
820
+ .option('--dry-run')
821
+ .option('--json')
822
+ .action(wrap(runDbMigrateBaseline));
813
823
  dbMigrate
814
824
  .command('status')
815
825
  .description('Show applied vs pending migrations')
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { parse } from '@babel/parser';
4
+ import { recordedNativeCalls } from './recorded-native-calls.js';
4
5
  const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts', '.mjs', '.cjs']);
5
6
  const NATIVE_NODES = new Map([
6
7
  ['IfStatement', ['FEATURE_NATIVE_IF', 'Replace native if/else with ctx.branch(ctx.when.*, { then, else }).']],
@@ -137,6 +138,9 @@ export function validateFeatureProject(projectRoot) {
137
138
  return;
138
139
  }
139
140
  visit(handler, { tag, mode });
141
+ for (const call of recordedNativeCalls(handler)) {
142
+ add(file, call, tag, 'FEATURE_NATIVE_RECORDED_METHOD', 'Native method on a recorded value. Use ctx.substring/ctx.transform or a portable Function.');
143
+ }
140
144
  return;
141
145
  }
142
146
  }
@@ -1,5 +1,6 @@
1
1
  import type { IMigration } from './db-types.js';
2
2
  export declare function validateEquivalentMigrationIndexes(migrations: IMigration[]): void;
3
+ export declare function validateCanonicalMigrationOperations(migrations: IMigration[]): void;
3
4
  export declare function getMigrationsDir(projectDir: string, dbTag: string): string;
4
5
  export declare function loadMigrationFiles(projectDir: string, dbTag: string): IMigration[];
5
6
  export declare function writeMigrationFile(projectDir: string, dbTag: string, migration: IMigration, counter: number): string;
@@ -22,6 +22,19 @@ export function validateEquivalentMigrationIndexes(migrations) {
22
22
  seen.set(fingerprint, { migration: migration.tag, operation: operationIndex, name: operation.name });
23
23
  });
24
24
  }
25
+ export function validateCanonicalMigrationOperations(migrations) {
26
+ for (const migration of migrations) {
27
+ for (const [direction, operations] of [['up', migration.up], ['down', migration.down]]) {
28
+ operations.forEach((operation, index) => {
29
+ if (operation.type === 'createCollection' && !operation.name) {
30
+ const legacy = operation.collection;
31
+ throw new Error(`Migration "${migration.tag}" ${direction} operation ${index + 1} createCollection requires "name"` +
32
+ (typeof legacy === 'string' ? '; "collection" is not valid for createCollection' : ''));
33
+ }
34
+ });
35
+ }
36
+ }
37
+ }
25
38
  export function getMigrationsDir(projectDir, dbTag) {
26
39
  return path.join(projectDir, PROJECT_CONFIG_DIR, 'database', 'migrations', dbTag);
27
40
  }
@@ -37,6 +50,7 @@ export function loadMigrationFiles(projectDir, dbTag) {
37
50
  const raw = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
38
51
  return raw;
39
52
  });
53
+ validateCanonicalMigrationOperations(migrations);
40
54
  validateEquivalentMigrationIndexes(migrations);
41
55
  return migrations;
42
56
  }
@@ -0,0 +1 @@
1
+ export declare function recordedNativeCalls(root: any): Set<any>;
@@ -0,0 +1,71 @@
1
+ export function recordedNativeCalls(root) {
2
+ const context = root.params?.[0]?.name || 'ctx';
3
+ const tainted = new Set();
4
+ const nodes = [];
5
+ const walk = (node) => {
6
+ if (!node || typeof node !== 'object')
7
+ return;
8
+ if (typeof node.type === 'string')
9
+ nodes.push(node);
10
+ for (const [key, value] of Object.entries(node)) {
11
+ if (['loc', 'extra', 'start', 'end'].includes(key))
12
+ continue;
13
+ if (Array.isArray(value))
14
+ value.forEach(walk);
15
+ else if (value && typeof value === 'object')
16
+ walk(value);
17
+ }
18
+ };
19
+ walk(root);
20
+ const bind = (pattern) => {
21
+ if (!pattern)
22
+ return;
23
+ if (pattern.type === 'Identifier')
24
+ tainted.add(pattern.name);
25
+ if (pattern.type === 'ObjectPattern')
26
+ pattern.properties.forEach((p) => bind(p.value || p.argument));
27
+ if (pattern.type === 'ArrayPattern')
28
+ pattern.elements.forEach(bind);
29
+ if (pattern.type === 'AssignmentPattern')
30
+ bind(pattern.left);
31
+ };
32
+ const derived = (node) => {
33
+ if (!node)
34
+ return false;
35
+ if (node.type === 'Identifier')
36
+ return tainted.has(node.name);
37
+ if (['AwaitExpression', 'TSAsExpression', 'TSNonNullExpression', 'TSTypeAssertion'].includes(node.type))
38
+ return derived(node.argument || node.expression);
39
+ if (['MemberExpression', 'OptionalMemberExpression'].includes(node.type)) {
40
+ return (node.object?.name === context && (node.property?.name || node.property?.value) === 'input') || derived(node.object);
41
+ }
42
+ if (['CallExpression', 'OptionalCallExpression'].includes(node.type)) {
43
+ if (node.callee?.object?.object?.name === context && node.callee?.object?.property?.name === 'functions' && node.callee?.property?.name === 'use')
44
+ return false;
45
+ let receiver = node.callee;
46
+ while (receiver?.object)
47
+ receiver = receiver.object;
48
+ return receiver?.name === context || derived(node.callee) || node.arguments.some(derived);
49
+ }
50
+ if (node.type === 'ObjectExpression')
51
+ return node.properties.some((p) => derived(p.value || p.argument));
52
+ if (node.type === 'ArrayExpression')
53
+ return node.elements.some(derived);
54
+ return false;
55
+ };
56
+ // Resolve aliases and destructuring to a fixed point, including aliases declared later.
57
+ for (let iteration = 0; iteration <= nodes.length; iteration++) {
58
+ const count = tainted.size;
59
+ for (const node of nodes) {
60
+ if (node.type === 'VariableDeclarator' && derived(node.init))
61
+ bind(node.id);
62
+ if (node.type === 'AssignmentExpression' && derived(node.right))
63
+ bind(node.left);
64
+ }
65
+ if (count === tainted.size)
66
+ break;
67
+ }
68
+ return new Set(nodes.filter(node => ['CallExpression', 'OptionalCallExpression'].includes(node.type) &&
69
+ ['MemberExpression', 'OptionalMemberExpression'].includes(node.callee?.type) &&
70
+ derived(node.callee.object) && node.callee.object?.name !== context));
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ductape/cli",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Ductape CLI — local platform, login, link projects, and manage resources via the proxy (Workbench-compatible)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",