Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/39396-migrate-write-export-default.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/cli': patch
---

fix(cli): `os migrate meta --write` no longer skips the stock generator's object modules as `not written [shared]`

Clause-②: no
Metadata-protocol: none

Who sees it: a developer upgrading a project whose modules have the shape `os generate` writes, `export const X = …;` followed by `export default X;`.

- **The edit is now written.** `--write` counted the `export default X;` line as a second use of `X`, so it left each edit in such a module for hand edits, reported as `not written [shared]`. That line only hands the module's value out. Now it counts as an export, like `export { X }`.
- **A real second use is still refused.** If another module imports `X`, by name or as the default, and reads it, or the module reads `X` again itself, the edit stays `[shared]` and is listed for a hand edit.
133 changes: 133 additions & 0 deletions packages/cli/src/utils/authored-source-codemod-39396.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `os migrate meta --write` over the stock generator's module shape:
* `export const X = …; export default X;`, with the barrel re-exporting `X`.
*
* The `export default X;` line is how the module hands its one value out, not
* a second use of it, so the edit is written. A real second use still refuses
* `[shared]`: another module that imports `X` (by name or as the default) and
* reads it, or the module itself reading `X` again.
*
* In-process over the planner, against temp projects with no dependencies: no
* process is spawned and no kernel is booted.
*/

import { afterAll, describe, expect, it } from 'vitest';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import type { MigrationApplication } from '@objectstack/spec/migrations';
import { planAuthoredSourceWrite } from './authored-source-codemod.js';

const root = mkdtempSync(join(tmpdir(), 'os-codemod-39396-'));
afterAll(() => rmSync(root, { recursive: true, force: true }));
let seq = 0;

function writeProject(files: Record<string, string>): string {
const dir = join(root, `case-${++seq}`);
for (const [rel, text] of Object.entries(files)) {
const path = join(dir, rel);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, text);
}
return join(dir, 'objectstack.config.ts');
}

/** The object module `os generate object contact` writes, cut to two keys. */
const GENERATED = `export const contact = {
name: 'contact',
label: 'Contact',
};

export default contact;
`;

const CONFIG = `import * as objects from './src/objects';

export default { objects: Object.values(objects) };
`;

const applied: MigrationApplication = {
toMajor: 19, conversionId: 'probe-label', surface: 'probe', from: 'a', to: 'b', path: 'objects[0].label',
};

async function plan(files: Record<string, string>, extra: Record<string, unknown> = {}) {
const configPath = writeProject(files);
const loaded = { objects: [{ name: 'contact', label: 'Contact' }], ...extra };
return planAuthoredSourceWrite({
configPath,
config: loaded,
namedExports: [],
normalized: loaded,
migrated: { ...loaded, objects: [{ name: 'contact', label: 'People' }] },
applied: [applied],
});
}

const kinds = (p: Awaited<ReturnType<typeof plan>>) => p.manual.map((m) => m.refusal.kind);

describe('--write over the generator shape (#39396)', () => {
it('writes the edit: `export default X;` beside `export const X` is not a second use', async () => {
const p = await plan({
'objectstack.config.ts': CONFIG,
'src/objects/index.ts': "export { contact } from './contact.object';\n",
'src/objects/contact.object.ts': GENERATED,
});
expect(kinds(p)).toEqual([]);
expect(p.written.map((w) => w.application.conversionId)).toEqual(['probe-label']);
expect(p.rewrites).toHaveLength(1);
expect(p.rewrites[0]!.after).toBe(GENERATED.replace("label: 'Contact'", "label: 'People'"));
});

it('writes it through a barrel that re-exports the default, too', async () => {
const p = await plan({
'objectstack.config.ts': CONFIG,
'src/objects/index.ts': "export { default as contact } from './contact.object';\n",
'src/objects/contact.object.ts': GENERATED,
});
expect(kinds(p)).toEqual([]);
expect(p.written.map((w) => w.application.conversionId)).toEqual(['probe-label']);
});

it('still refuses [shared] when another module imports the default and reads it', async () => {
const p = await plan({
'objectstack.config.ts': `import * as objects from './src/objects';
import { mirror } from './src/mirror';

export default { objects: Object.values(objects), description: mirror };
`,
'src/objects/index.ts': "export { contact } from './contact.object';\n",
'src/objects/contact.object.ts': GENERATED,
'src/mirror.ts': "import person from './objects/contact.object';\n\nexport const mirror = person.label;\n",
}, { description: 'Contact' });
expect(kinds(p)).toEqual(['shared']);
expect(p.manual[0]!.refusal.reason).toContain('`contact`');
expect(p.rewrites).toEqual([]);
});

it('still refuses [shared] when another module imports the name and reads it', async () => {
const p = await plan({
'objectstack.config.ts': `import * as objects from './src/objects';
import { mirror } from './src/mirror';

export default { objects: Object.values(objects), description: mirror };
`,
'src/objects/index.ts': "export { contact } from './contact.object';\n",
'src/objects/contact.object.ts': GENERATED,
'src/mirror.ts': "import { contact } from './objects/contact.object';\n\nexport const mirror = contact.label;\n",
}, { description: 'Contact' });
expect(kinds(p)).toEqual(['shared']);
expect(p.rewrites).toEqual([]);
});

it('still refuses [shared] when the module itself reads the binding again', async () => {
const p = await plan({
'objectstack.config.ts': CONFIG,
'src/objects/index.ts': "export { contact } from './contact.object';\n",
'src/objects/contact.object.ts': `${GENERATED}\nexport const contactLabel = contact.label;\n`,
});
expect(kinds(p)).toEqual(['shared']);
expect(p.rewrites).toEqual([]);
});
});
21 changes: 20 additions & 1 deletion packages/cli/src/utils/authored-source-codemod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1103,7 +1103,10 @@ class SourceGraph {
if (ts.isIdentifier(decl.name) && decl.name.text === name) return key;
}
} else if (ts.isExportAssignment(stmt) && !stmt.isExportEquals && name === 'default') {
return key;
// `export default X;` of a module-level `X` hands out X itself, so a
// default import reads X — counted against X, never a binding of its own.
const local = this.defaultExportedLocal(stmt);
return local === undefined ? key : `${mod.path}#${local}`;
} else if (ts.isExportDeclaration(stmt) && !stmt.isTypeOnly) {
const specifier = stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier) ? stmt.moduleSpecifier.text : undefined;
const clause = stmt.exportClause;
Expand All @@ -1125,11 +1128,27 @@ class SourceGraph {
return hits.length === 1 ? this.bindingOfExport(hits[0]!, name, visiting) : null;
}

/**
* The module-level variable an `export default X;` names, or undefined when
* its expression is anything else (an import, a call, a literal, `(X)`).
*/
private defaultExportedLocal(stmt: TS.ExportAssignment): string | undefined {
const ts = this.ts;
const e = stmt.expression;
if (stmt.isExportEquals || !ts.isIdentifier(e)) return undefined;
const declared = stmt.getSourceFile().statements.some((s) => ts.isVariableStatement(s)
&& s.declarationList.declarations.some((d) => ts.isIdentifier(d.name) && d.name.text === e.text));
return declared ? e.text : undefined;
}

/** Whether an identifier occurrence READS a binding (not a declaration, key, type or specifier). */
private isReference(id: TS.Identifier): boolean {
const ts = this.ts;
const p = id.parent;
if (!p) return false;
// `export default X;` re-exports X like `export { X }` does: the module's
// importers are its uses (see `bindingOfExport`), not this line (#39396).
if (ts.isExportAssignment(p) && p.expression === id && this.defaultExportedLocal(p) !== undefined) return false;
if ((ts.isVariableDeclaration(p) || ts.isFunctionDeclaration(p) || ts.isClassDeclaration(p)
|| ts.isEnumDeclaration(p) || ts.isInterfaceDeclaration(p) || ts.isTypeAliasDeclaration(p)
|| ts.isParameter(p) || ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p)
Expand Down
Loading