From 79f3d3b2e2dcaa7d782bbbc7f2568fd36ce5cc61 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:54:20 +0000 Subject: [PATCH 1/2] chore(scripts): delete the four one-off codemod-split-*.mjs scripts; comments cite the PRs that made each split The engine, protocol, sql-driver and conversions-registry split scripts ran once per split and are run, imported and read by nothing on main. Every comment that named one now names the PR that made that split instead ("split by #NNNNN"); comment lines only, each rewritten in place, so no file's line count moves. Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh Co-Authored-By: Claude --- .gitignore | 2 +- .../driver-sql/src/sql-driver-aggregation.ts | 2 +- .../src/sql-driver-bulk-operations.ts | 2 +- .../driver-sql/src/sql-driver-class-head.ts | 2 +- .../src/sql-driver-column-creation.ts | 2 +- .../drivers/driver-sql/src/sql-driver-crud.ts | 2 +- .../src/sql-driver-database-helpers.ts | 4 +- .../driver-sql/src/sql-driver-deferred-ddl.ts | 4 +- .../driver-sql/src/sql-driver-distinct.ts | 4 +- .../driver-sql/src/sql-driver-facet-hosts.ts | 2 +- .../src/sql-driver-field-mapping.ts | 2 +- .../src/sql-driver-filter-helpers.ts | 2 +- .../src/sql-driver-internal-helpers.ts | 4 +- .../driver-sql/src/sql-driver-lifecycle.ts | 2 +- .../src/sql-driver-managed-drift.ts | 4 +- .../driver-sql/src/sql-driver-query-plan.ts | 4 +- .../driver-sql/src/sql-driver-rotation.ts | 2 +- .../src/sql-driver-schema-introspection.ts | 4 +- .../src/sql-driver-schema-sync-section.ts | 2 +- .../src/sql-driver-sequence-semantics.ts | 2 +- .../src/sql-driver-sqlite-serialisation.ts | 4 +- .../driver-sql/src/sql-driver-top-level.ts | 4 +- .../src/sql-driver-transactions-section.ts | 4 +- .../src/sql-driver-window-function-builder.ts | 4 +- .../src/sql-driver-window-functions.ts | 4 +- .../src/protocol-class-head.ts | 4 +- .../src/protocol-data-crud.ts | 4 +- .../src/protocol-diff-delete-load.ts | 4 +- .../src/protocol-discovery-and-bases.ts | 2 +- .../src/protocol-history-and-publish.ts | 2 +- .../src/protocol-package-commits.ts | 2 +- .../src/protocol-publish-batch.ts | 2 +- .../src/protocol-registry-hydration.ts | 4 +- .../metadata-protocol/src/protocol-save.ts | 2 +- .../src/protocol-search-and-cache.ts | 2 +- .../src/protocol-write-gates-tables.ts | 4 +- .../src/protocol-write-gates.ts | 2 +- ...tocol.facade-door-return-types.pin.test.ts | 6 +- packages/objectql/src/engine-actions.ts | 4 +- .../objectql/src/engine-cascade-planning.ts | 2 +- .../src/engine-compatibility-section.ts | 4 +- .../objectql/src/engine-count-aggregate.ts | 2 +- .../objectql/src/engine-datasource-routing.ts | 2 +- .../src/engine-defaults-and-autonumbers.ts | 2 +- .../src/engine-delete-and-aggregate.ts | 4 +- .../objectql/src/engine-delete-cascade.ts | 2 +- .../objectql/src/engine-driver-options.ts | 2 +- .../src/engine-execute-transactions.ts | 2 +- .../objectql/src/engine-execution-plumbing.ts | 2 +- packages/objectql/src/engine-facet-hosts.ts | 2 +- .../src/engine-file-reference-hydration.ts | 2 +- packages/objectql/src/engine-find.ts | 2 +- packages/objectql/src/engine-hook-dispatch.ts | 2 +- .../src/engine-hooks-and-functions.ts | 2 +- packages/objectql/src/engine-insert.ts | 4 +- .../src/engine-master-detail-related.ts | 2 +- .../src/engine-middleware-and-context.ts | 4 +- .../objectql/src/engine-migration-flags.ts | 2 +- .../objectql/src/engine-migration-state.ts | 2 +- .../objectql/src/engine-object-repository.ts | 2 +- .../src/engine-package-registration.ts | 2 +- .../objectql/src/engine-query-lowering.ts | 2 +- .../engine-readable-ids-permission-formula.ts | 2 +- .../objectql/src/engine-realtime-publish.ts | 2 +- .../src/engine-reference-name-visible.ts | 4 +- .../engine-references-and-master-detail.ts | 4 +- .../src/engine-referential-integrity.ts | 2 +- packages/objectql/src/engine-registration.ts | 2 +- .../objectql/src/engine-scoped-context.ts | 4 +- packages/objectql/src/engine-scoped-hosts.ts | 2 +- .../src/engine-secret-internal-fields.ts | 2 +- .../src/engine-secrets-and-routing.ts | 2 +- .../objectql/src/engine-security-resolvers.ts | 2 +- .../src/engine-summaries-and-expansion.ts | 2 +- packages/objectql/src/engine-top-level.ts | 2 +- .../src/engine-transactions-section.ts | 4 +- packages/objectql/src/engine-update.ts | 2 +- .../src/engine-validation-messages.ts | 2 +- .../federated-injected-column-readers.test.ts | 2 +- .../scripts/conversions-major18-merge.test.ts | 2 +- .../entries/11/flow-node-crud-filter-alias.ts | 4 +- .../11/flow-node-http-callout-rename.ts | 4 +- .../entries/11/page-kind-jsx-to-html.ts | 4 +- ...age-component-visibility-to-visibleWhen.ts | 4 +- .../15/view-visibleOn-to-visibleWhen.ts | 4 +- .../17/datasource-driver-mongo-to-mongodb.ts | 4 +- .../17/flow-node-connector-config-lift.ts | 4 +- .../entries/17/flow-node-crud-object-alias.ts | 4 +- .../entries/17/flow-node-map-flow-alias.ts | 4 +- .../17/flow-node-notify-config-aliases.ts | 4 +- .../17/flow-node-script-config-aliases.ts | 4 +- .../17/flow-node-subflow-flow-alias.ts | 4 +- .../17/flow-node-wait-event-config-lift.ts | 4 +- .../inline-action-api-params-to-body-extra.ts | 4 +- .../entries/17/page-header-subtitle-alias.ts | 4 +- .../entries/17/retry-policy-converged.ts | 4 +- .../sharing-rule-access-level-full-to-edit.ts | 4 +- .../entries/18/action-aria-removed.ts | 4 +- .../18/action-block-endpoint-to-target.ts | 4 +- .../18/add-record-enabled-defaulted.ts | 4 +- .../18/add-record-mode-form-view-removed.ts | 4 +- .../entries/18/agent-lifecycle-removed.ts | 4 +- .../agent-memory-long-term-store-removed.ts | 4 +- ...ructured-output-refused-members-removed.ts | 4 +- ...endpoint-cache-ttl-to-cache-ttl-seconds.ts | 4 +- .../cbp-master-detail-required-defaulted.ts | 4 +- .../entries/18/chart-config-aria-removed.ts | 4 +- ...connector-connection-timeout-ms-removed.ts | 4 +- .../18/connector-error-mapping-removed.ts | 4 +- .../18/connector-resilience-keys-removed.ts | 4 +- .../entries/18/connector-sync-keys-removed.ts | 4 +- .../entries/18/connector-triggers-removed.ts | 4 +- .../cube-join-sql-and-relationship-removed.ts | 4 +- .../18/cube-member-inner-name-removed.ts | 4 +- .../entries/18/cube-refresh-key-removed.ts | 4 +- .../18/cube-sub-day-granularities-removed.ts | 4 +- ...config-dynamic-default-currency-removed.ts | 4 +- .../18/currency-config-precision-removed.ts | 4 +- ...sh-interval-to-refresh-interval-seconds.ts | 4 +- ...d-widget-chart-config-structure-removed.ts | 4 +- ...taset-count-measure-empty-field-removed.ts | 4 +- .../entries/18/declared-index-unique-scope.ts | 4 +- .../entries/18/element-filter-removed.ts | 4 +- ...lement-flat-data-binding-to-data-source.ts | 4 +- .../entries/18/element-form-removed.ts | 4 +- .../element-input-target-variable-removed.ts | 4 +- .../18/element-text-variant-heading-levels.ts | 4 +- ...ail-template-category-is-system-removed.ts | 4 +- .../18/field-column-lists-canonicalized.ts | 4 +- ...field-malformed-scale-precision-removed.ts | 4 +- .../entries/18/field-reference-to-alias.ts | 4 +- .../flow-decision-mode-inclusive-explicit.ts | 4 +- .../18/form-field-public-picker-removed.ts | 4 +- .../18/form-layout-inline-grid-to-vertical.ts | 4 +- .../18/form-view-buttons-reset-removed.ts | 4 +- .../18/form-view-drawer-keys-removed.ts | 4 +- .../18/form-view-option-default-removed.ts | 4 +- .../form-view-presentation-types-removed.ts | 4 +- ...form-view-subform-columns-canonicalized.ts | 4 +- .../entries/18/hook-timeout-to-timeout-ms.ts | 4 +- .../entries/18/job-timeout-to-timeout-ms.ts | 4 +- .../18/list-view-options-bag-folded.ts | 4 +- .../list-view-sort-string-clause-to-array.ts | 4 +- ...anifest-packaging-manifest-deps-removed.ts | 4 +- ...anifest-permissions-string-list-removed.ts | 4 +- .../18/mapping-lookup-params-removed.ts | 4 +- ...ry-persistence-auto-save-interval-to-ms.ts | 4 +- .../entries/18/metric-filters-removed.ts | 4 +- .../navigation-mode-overlay-values-removed.ts | 4 +- .../object-external-sharing-model-removed.ts | 4 +- .../18/object-grid-default-filters-removed.ts | 4 +- .../18/object-grid-default-sort-removed.ts | 4 +- .../object-grid-resizable-columns-removed.ts | 4 +- .../18/object-kanban-quick-add-removed.ts | 4 +- ...r-detail-form-detail-sort-field-removed.ts | 4 +- ...ject-tenancy-organization-field-removed.ts | 4 +- ...ion-block-variant-destructive-to-danger.ts | 4 +- ...e-action-row-navigation-executor-to-url.ts | 4 +- .../18/page-action-row-patch-removed.ts | 4 +- .../18/page-assigned-profiles-removed.ts | 4 +- ...e-component-filter-record-to-rule-array.ts | 4 +- .../18/page-component-responsive-removed.ts | 4 +- .../18/page-header-breadcrumb-removed.ts | 4 +- .../18/page-header-show-star-removed.ts | 4 +- ...page-is-default-off-record-page-removed.ts | 4 +- ...view-object-name-view-type-to-data-type.ts | 4 +- .../18/page-main-region-width-removed.ts | 4 +- ...page-requires-non-compiled-kind-removed.ts | 4 +- .../entries/18/page-slots-tabs-removed.ts | 4 +- .../18/page-template-full-width-to-default.ts | 4 +- ...n-admin-scope-binding-authoring-removed.ts | 4 +- .../permission-allow-restore-purge-removed.ts | 4 +- ...n-modify-all-allow-delete-false-to-true.ts | 4 +- .../entries/18/permission-rls-tags-removed.ts | 4 +- .../18/permission-set-managed-by-removed.ts | 4 +- .../18/record-chatter-position-vocabulary.ts | 4 +- .../record-highlights-field-icon-removed.ts | 4 +- .../entries/18/report-joined-chart-removed.ts | 4 +- .../18/time-default-utc-suffix-dropped.ts | 4 +- ...nslation-component-submit-label-removed.ts | 4 +- .../translation-locale-tag-canonicalized.ts | 4 +- .../18/translation-locale-tag-case-folded.ts | 4 +- .../translation-per-app-settings-removed.ts | 4 +- .../translation-widget-sub-caption-removed.ts | 4 +- .../18/turso-config-encryption-key-removed.ts | 4 +- .../18/turso-config-timeout-to-timeout-ms.ts | 4 +- .../18/view-item-owner-hidden-removed.ts | 4 +- .../18/view-list-filterable-fields-removed.ts | 4 +- .../entries/18/view-list-tabs-removed.ts | 4 +- .../18/view-overlay-owner-hidden-removed.ts | 4 +- .../entries/18/view-page-mount-removed.ts | 4 +- .../18/view-personal-declarations-removed.ts | 4 +- .../spec/src/conversions/entries/shared.ts | 4 +- packages/spec/src/conversions/registry.ts | 2 +- scripts/check-adr-0087-registration.mjs | 4 +- ...check-durability-degradation-log-level.mjs | 2 +- scripts/check-stack-collection-maps.mjs | 2 +- .../codemod-split-conversions-registry.mjs | 1367 --- scripts/codemod-split-engine.mjs | 7452 ----------------- scripts/codemod-split-protocol.mjs | 4164 --------- scripts/codemod-split-sql-driver.mjs | 2950 ------- scripts/cross-package-test-inputs.mjs | 2 +- scripts/sql-driver-split-source.mjs | 2 +- 203 files changed, 341 insertions(+), 16274 deletions(-) delete mode 100644 scripts/codemod-split-conversions-registry.mjs delete mode 100644 scripts/codemod-split-engine.mjs delete mode 100644 scripts/codemod-split-protocol.mjs delete mode 100644 scripts/codemod-split-sql-driver.mjs diff --git a/.gitignore b/.gitignore index d12939307aa..b1f0b1fa378 100644 --- a/.gitignore +++ b/.gitignore @@ -68,7 +68,7 @@ packages/spec/json-schema/ packages/spec/src/migrations/registry.ts packages/spec/src/migrations/registry.ts.*.tmp -# Scratch dir of `codemod-split-conversions-registry.mjs --arrays`: its mkdtemp +# Scratch dir of the registry codemod's `--arrays` run (split by #29993): its mkdtemp # sits inside packages/spec so the copied src resolves the package's own # node_modules; removed in a finally, ignored here in case a run is killed. packages/spec/.codemod-arrays-*/ diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index d3499ccb51c..e4522620fb2 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -3,7 +3,7 @@ /** * [#29520 codemod] The "Aggregation" section of `SqlDriver`: the bodies of * `aggregate`, `aggregandColumnClassOf`, `foldEmptyAggregateAnswers` moved out - * of `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * of `sql-driver.ts` whole (split by #29598 and #30139). * * A MOVE, not a redesign. {@link AggregationFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts index 8613be87d4c..9cf0f2b6b7a 100644 --- a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts +++ b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts @@ -4,7 +4,7 @@ * [#29520 codemod] The "Bulk & Batch Operations" section of `SqlDriver`: the * bodies of `bulkCreate`, `bulkUpdate`, `bulkDelete`, `updateMany`, * `deleteMany`, `rotatedUpdateById`, `count` moved out of `sql-driver.ts` whole - * by `scripts/codemod-split-sql-driver.mjs`. + * (split by #29598 and #30139). * * A MOVE, not a redesign. {@link BulkOperationsFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-class-head.ts b/packages/drivers/driver-sql/src/sql-driver-class-head.ts index 22de655187e..96615ce9e5f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-class-head.ts +++ b/packages/drivers/driver-sql/src/sql-driver-class-head.ts @@ -8,7 +8,7 @@ * `knexConfigFor`, `withConnectBound`, `withUtcSession`, * `withMysqlCalendarDayAsText`, `withPostgresCalendarDayAsText`, * `installQueryTiming`, `assertSchemaMutable`, `assertDialectEmits` moved out - * of `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * of `sql-driver.ts` whole (split by #30139 and #30306). * * A MOVE, not a redesign. {@link ClassHeadFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-column-creation.ts b/packages/drivers/driver-sql/src/sql-driver-column-creation.ts index 0d3b982f300..9101e9eaf0e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-column-creation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-column-creation.ts @@ -10,7 +10,7 @@ * `varcharPackLength`, `varcharColumnChars`, `rowWidthProfile`, * `schemaBytesPerChar`, `explainRowSizeOverflow`, * `rethrowWithRowSizeExplanation`, `jsonColumn`, `createColumn` moved out of - * `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * `sql-driver.ts` whole (split by #29598 and #30363). * * A MOVE, not a redesign. {@link ColumnCreationFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 4d1a2e5bb3b..4303b18518f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -4,7 +4,7 @@ * [#29520 codemod] The "CRUD — IDataDriver core" section of `SqlDriver`: the * bodies of `find`, `findRows`, `findOne`, `create`, `readBackInsertedRows`, * `ensureSequencesTable`, `sequenceKeyHash` moved out of `sql-driver.ts` whole - * by `scripts/codemod-split-sql-driver.mjs`. + * (split by #29598 and #30139). * * A MOVE, not a redesign. {@link CrudFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-database-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-database-helpers.ts index bebedf8be63..c098cc7af6a 100644 --- a/packages/drivers/driver-sql/src/sql-driver-database-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-database-helpers.ts @@ -5,8 +5,8 @@ * `sqliteFilename`, `ensureDatabaseExists`, `createDatabase`, * `setFileColumnsMovedResolver`, `setTenantKeyCertifiedResolver`, * `isTenantKeyCertified`, `resolveFileColumnsMoved`, `mediaColumnIsJson`, - * `isJsonField` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `isJsonField` moved out of `sql-driver.ts` whole (split + * by #29598 and #30249). * * A MOVE, not a redesign. {@link DatabaseHelpersFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-deferred-ddl.ts b/packages/drivers/driver-sql/src/sql-driver-deferred-ddl.ts index 4e63cc68f9a..31a99ea3ede 100644 --- a/packages/drivers/driver-sql/src/sql-driver-deferred-ddl.ts +++ b/packages/drivers/driver-sql/src/sql-driver-deferred-ddl.ts @@ -3,8 +3,8 @@ /** * [#29520 codemod] The "Deferred schema DDL (#3917)" section of `SqlDriver`: * the bodies of `setDeferredDdl`, `getSchemaSyncStats`, - * `flushDeferredSchemaDdl` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `flushDeferredSchemaDdl` moved out of `sql-driver.ts` whole (split + * by #30139). * * A MOVE, not a redesign. {@link DeferredDdlFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-distinct.ts b/packages/drivers/driver-sql/src/sql-driver-distinct.ts index eaa61034720..48795c04db0 100644 --- a/packages/drivers/driver-sql/src/sql-driver-distinct.ts +++ b/packages/drivers/driver-sql/src/sql-driver-distinct.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "Distinct" section of `SqlDriver`: the bodies of - * `distinct` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `distinct` moved out of `sql-driver.ts` whole (split + * by #29598). * * A MOVE, not a redesign. {@link DistinctFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-facet-hosts.ts b/packages/drivers/driver-sql/src/sql-driver-facet-hosts.ts index 1257dcac3c3..ab9db9e0a75 100644 --- a/packages/drivers/driver-sql/src/sql-driver-facet-hosts.ts +++ b/packages/drivers/driver-sql/src/sql-driver-facet-hosts.ts @@ -11,7 +11,7 @@ * when a body assigns it), so a body reads and writes the driver exactly as * the per-call literal let it. * - * Written by `scripts/codemod-split-sql-driver.mjs`; it imports types only, so it forms no + * Written by the sql-driver codemod (split by #30139); it imports types only, so it forms no * evaluation cycle and is evaluated before the class whichever module loads * first. `index.ts` re-exports nothing from this module. */ diff --git a/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts b/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts index 4cbd26b9352..42a85a6a4c0 100644 --- a/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts +++ b/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts @@ -4,7 +4,7 @@ * [#29520 codemod] The "Field mapping" section of `SqlDriver`: the bodies of * `mapSortField`, `paginationTieBreaker`, `orderKeysFor`, `remoteColumn`, * `applyWriteColumnMap`, `mapAggregateFunc` moved out of `sql-driver.ts` whole - * by `scripts/codemod-split-sql-driver.mjs`. + * (split by #29598 and #30139). * * A MOVE, not a redesign. {@link FieldMappingFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index 7f04450a318..2996a3e6be8 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -14,7 +14,7 @@ * `resolveWithheldFilterRefusal`, `logWithheldFilterDiagnostic`, * `withWithheldFilterLog`, `compileFilters`, `applyContainsLike`, * `applyFilterCondition`, `declaredFieldsFor`, `applyFalseConstant` moved out - * of `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * of `sql-driver.ts` whole (split by #29598 and #30441). * * A MOVE, not a redesign. {@link FilterHelpersFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts index 682f5e7efc3..e56395c706e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -4,8 +4,8 @@ * [#29520 codemod] The "Internal helpers" section of `SqlDriver`: the bodies of * `getKnex`, `getBuilder`, `resolveTenantField`, `isMultiTenantMode`, * `applyTenantScope`, `readableIdsSubquery`, `injectTenantOnInsert`, - * `auditMissingTenant` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `auditMissingTenant` moved out of `sql-driver.ts` whole (split + * by #29598 and #30249). * * A MOVE, not a redesign. {@link InternalHelpersFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-lifecycle.ts b/packages/drivers/driver-sql/src/sql-driver-lifecycle.ts index 5fc2f7a4d5f..fb56a7c8eb3 100644 --- a/packages/drivers/driver-sql/src/sql-driver-lifecycle.ts +++ b/packages/drivers/driver-sql/src/sql-driver-lifecycle.ts @@ -6,7 +6,7 @@ * `autoVacuumOf`, `resolveSqliteJournalMode`, `supportsWalJournal`, * `applySqliteJournalMode`, `verifyWalReadable`, `isSqliteBusyError`, * `journalModeOf`, `checkHealth`, `disconnect` moved out of `sql-driver.ts` - * whole by `scripts/codemod-split-sql-driver.mjs`. + * whole (split by #29598 and #30249). * * A MOVE, not a redesign. {@link LifecycleFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts b/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts index 5a63d76dbc8..f08f04a4799 100644 --- a/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts +++ b/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts @@ -5,8 +5,8 @@ * `SqlDriver`: the bodies of `dialectName`, `isProductionEnv`, * `probeNullSafeUniqueDuplicates`, `buildRebuiltColumn`, `buildIndexName`, * `getExistingIndexNames`, `uniqueIndexesFromFields`, `dropIndexIfExists`, - * `syncTableIndexes` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `syncTableIndexes` moved out of `sql-driver.ts` whole (split + * by #29598). * * A MOVE, not a redesign. {@link ManagedDriftFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts index a35a3b1d8e0..47b2f3f0405 100644 --- a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts +++ b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "Query Plan Analysis" section of `SqlDriver`: the bodies - * of `explain`, `analyzeQuery` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * of `explain`, `analyzeQuery` moved out of `sql-driver.ts` whole (split + * by #29598). * * A MOVE, not a redesign. {@link QueryPlanFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-rotation.ts b/packages/drivers/driver-sql/src/sql-driver-rotation.ts index fac5f8345f9..5d963ae6c36 100644 --- a/packages/drivers/driver-sql/src/sql-driver-rotation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-rotation.ts @@ -7,7 +7,7 @@ * `computeTenantField`, `computeAndRecordTenantField`, * `registerManagedObjectMetadata`, `registerObjectMetadata`, `initObjects`, * `withPinnedSession`, `migrateMysqlDatetimeColumns`, `migrateMysqlTimeColumns` - * moved out of `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * moved out of `sql-driver.ts` whole (split by #29598 and #30363). * * A MOVE, not a redesign. {@link RotationFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-schema-introspection.ts b/packages/drivers/driver-sql/src/sql-driver-schema-introspection.ts index a8833c5d55b..3a3c9b2c593 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-introspection.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-introspection.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "Schema Introspection" section of `SqlDriver`: the - * bodies of `listPhysicalColumns` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * bodies of `listPhysicalColumns` moved out of `sql-driver.ts` whole (split + * by #30139 and #30249). * * A MOVE, not a redesign. {@link SchemaIntrospectionFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-schema-sync-section.ts b/packages/drivers/driver-sql/src/sql-driver-schema-sync-section.ts index 4bf8aa91a14..f424534ff27 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-sync-section.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-sync-section.ts @@ -3,7 +3,7 @@ /** * [#29520 codemod] The "Schema Sync (syncSchema / init)" section of * `SqlDriver`: the bodies of `syncSchema`, `dropTable`, `reclaimSpace` moved - * out of `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * out of `sql-driver.ts` whole (split by #29598 and #30139). * * A MOVE, not a redesign. {@link SchemaSyncSectionFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts b/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts index 49a0a5de135..39814dcb732 100644 --- a/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts +++ b/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts @@ -12,7 +12,7 @@ * `insertOnlyUpsertColumns`, `mergeLandsInWrittenOrganization`, * `assertMergeLandedOnSuppliedIdentity`, * `assertMergeLandedInWrittenOrganization`, `upsert`, `delete` moved out of - * `sql-driver.ts` whole by `scripts/codemod-split-sql-driver.mjs`. + * `sql-driver.ts` whole (split by #29598). * * A MOVE, not a redesign. {@link SequenceSemanticsFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts b/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts index 6abe09b39a3..d745db06680 100644 --- a/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "SQLite serialisation" section of `SqlDriver`: the - * bodies of `formatInput`, `formatOutput` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * bodies of `formatInput`, `formatOutput` moved out of `sql-driver.ts` whole (split + * by #29598). * * A MOVE, not a redesign. {@link SqliteSerialisationFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-top-level.ts b/packages/drivers/driver-sql/src/sql-driver-top-level.ts index 24d43d55fb7..0816ac85f54 100644 --- a/packages/drivers/driver-sql/src/sql-driver-top-level.ts +++ b/packages/drivers/driver-sql/src/sql-driver-top-level.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29520 codemod] The top-level declarations ahead of `SqlDriver` in -// `sql-driver.ts` that moved out whole by -// `scripts/codemod-split-sql-driver.mjs` (lever (b) of ruling 6591753301). +// `sql-driver.ts` that moved out whole +// (split by #29598; lever (b) of ruling 6591753301). // // A MOVE, not a redesign: each declaration below is its `sql-driver.ts` text // exactly, with the comments above it, in the order it stood there. A LEAF: diff --git a/packages/drivers/driver-sql/src/sql-driver-transactions-section.ts b/packages/drivers/driver-sql/src/sql-driver-transactions-section.ts index 317090fbbe2..f16670bc67e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-transactions-section.ts +++ b/packages/drivers/driver-sql/src/sql-driver-transactions-section.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "Transactions" section of `SqlDriver`: the bodies of - * `releaseTransaction` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `releaseTransaction` moved out of `sql-driver.ts` whole (split + * by #30139). * * A MOVE, not a redesign. {@link TransactionsSectionFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-window-function-builder.ts b/packages/drivers/driver-sql/src/sql-driver-window-function-builder.ts index 282cd95c4f6..ba796b93f97 100644 --- a/packages/drivers/driver-sql/src/sql-driver-window-function-builder.ts +++ b/packages/drivers/driver-sql/src/sql-driver-window-function-builder.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "Window function builder" section of `SqlDriver`: the - * bodies of `buildWindowFunction` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * bodies of `buildWindowFunction` moved out of `sql-driver.ts` whole (split + * by #29598). * * A MOVE, not a redesign. {@link WindowFunctionBuilderFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts index ace414bf21b..b8811398e14 100644 --- a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts +++ b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts @@ -2,8 +2,8 @@ /** * [#29520 codemod] The "Window Functions" section of `SqlDriver`: the bodies of - * `findWithWindowFunctions` moved out of `sql-driver.ts` whole by - * `scripts/codemod-split-sql-driver.mjs`. + * `findWithWindowFunctions` moved out of `sql-driver.ts` whole (split + * by #29598). * * A MOVE, not a redesign. {@link WindowFunctionsFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` diff --git a/packages/metadata-protocol/src/protocol-class-head.ts b/packages/metadata-protocol/src/protocol-class-head.ts index 600924b17d6..ba260c9f2c5 100644 --- a/packages/metadata-protocol/src/protocol-class-head.ts +++ b/packages/metadata-protocol/src/protocol-class-head.ts @@ -12,8 +12,8 @@ * `onMetadataMutation`, `emitMetadataMutation`, `attachMetadataMutationPubSub`, * `detachMetadataMutationPubSub`, `applyRemoteMetadataMutation`, * `resyncMetadataMutationPubSub` (#31722, written here beside its lane), - * `onMetaItemPublished`, `getOverlayRepo` moved out of `protocol.ts` whole by - * `scripts/codemod-split-protocol.mjs`; `registerUninstallGuard` (#31232) was + * `onMetaItemPublished`, `getOverlayRepo` moved out of `protocol.ts` whole (split + * by #29998 and #30954); `registerUninstallGuard` (#31232) was * written here in the same shape, beside `registerUninstallCleanup`. * * A MOVE, not a redesign. `ProtocolClassHeadFacet` is a stateless facet over the host diff --git a/packages/metadata-protocol/src/protocol-data-crud.ts b/packages/metadata-protocol/src/protocol-data-crud.ts index b1c07fefa49..ce6ddbe08d6 100644 --- a/packages/metadata-protocol/src/protocol-data-crud.ts +++ b/packages/metadata-protocol/src/protocol-data-crud.ts @@ -3,8 +3,8 @@ /** * [#29985 codemod] The "Data CRUD" facet of * `ObjectStackProtocolImplementation`: the bodies of `findData`, `getData`, - * `cloneData`, `probeRecord` moved out of `protocol.ts` whole by - * `scripts/codemod-split-protocol.mjs`. + * `cloneData`, `probeRecord` moved out of `protocol.ts` whole (split + * by #29998 and #30687). * * A MOVE, not a redesign. `ProtocolDataCrudFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 793d3afc0ad..1128f18ab99 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -4,8 +4,8 @@ * [#29985 codemod] The "Diff, deleteMetaItem, loadMetaFromDb, load reports, * findReferencesToMeta" facet of `ObjectStackProtocolImplementation`: the * bodies of `diffMetaItem`, `deleteMetaItem`, `deleteMetaItemUnaudited`, - * `loadMetaFromDb`, `findReferencesToMeta` moved out of `protocol.ts` whole by - * `scripts/codemod-split-protocol.mjs`. + * `loadMetaFromDb`, `findReferencesToMeta` moved out of `protocol.ts` whole (split + * by #29998). * * A MOVE, not a redesign. `ProtocolDiffDeleteLoadFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index c9185505738..3f952ea487d 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -9,7 +9,7 @@ * `packagedArtifactBase`, `objectRegistrationRefusal`, * `restoreTranslatedObjectEchoes`, `restoreInjectedColumnEchoes`, * `registeredTranslationBundle`, `readCodeLayerForCarryForward` moved out of - * `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`. + * `protocol.ts` whole (split by #29998). * * [#30062] Written here from the start, beside their siblings: the page, * dataset, app and book packaged bases (`getPackagedPageBase`, diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 2f82d0b0e1c..c0d117ff206 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -5,7 +5,7 @@ * `ObjectStackProtocolImplementation`: the bodies of `historyMetaItem`, * `publishMetaItem`, `publishMetaItemUnaudited`, `promoteDraftForPublish`, * `runPublishSideEffects`, `publishPackageDrafts`, `discardPackageDrafts` moved - * out of `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`. + * out of `protocol.ts` whole (split by #29998 and #32068). * * A MOVE, not a redesign. `ProtocolHistoryAndPublishFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 6e576f0d6c2..837651c7769 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -7,7 +7,7 @@ * `importUnmanagedPackage`, `reassignOrphanedMetadata`, `listCommits`, * `readRevertableCommit`, `revertCommit`, `rollbackToPackageCommit`, * `rollbackMetaItem`, `rollbackMetaItemUnaudited` moved out of `protocol.ts` - * whole by `scripts/codemod-split-protocol.mjs`. + * whole (split by #29998 and #30687). * * A MOVE, not a redesign. `ProtocolPackageCommitsFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-publish-batch.ts b/packages/metadata-protocol/src/protocol-publish-batch.ts index 32a83041615..47a77f0b761 100644 --- a/packages/metadata-protocol/src/protocol-publish-batch.ts +++ b/packages/metadata-protocol/src/protocol-publish-batch.ts @@ -288,7 +288,7 @@ export async function collectBatchPendingDeclarations( * [#30020 codemod] The body of * `ObjectStackProtocolImplementation#applySeedBodies`, the host it builds for * {@link applySeedBodies} included: moved here whole by `--hand-host` of - * `scripts/codemod-split-protocol.mjs`. It runs on the class's host + * the protocol codemod (split by #32463). It runs on the class's host * (`protocol-host.ts`) as `this`, so the class keeps a one-call stub; the * method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index d7d391da52d..6c4a6af7639 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -10,8 +10,8 @@ * `reconcileViewExpansions`, `anotherPackageShips`, * `applyRegistryWriteThrough`, `restoreArtifactRegistryView`, * `ensureObjectStorage`, `dropObjectStorage`, `unboundOwnerPackageRefusal`, - * `dropStorageRemainingRowsRefusal` moved out of `protocol.ts` whole by - * `scripts/codemod-split-protocol.mjs`. + * `dropStorageRemainingRowsRefusal` moved out of `protocol.ts` whole (split + * by #29998). * * A MOVE, not a redesign. `ProtocolRegistryHydrationFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 6da4b136ca4..aefdb76aede 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -5,7 +5,7 @@ * migrateStoredMetadata" facet of `ObjectStackProtocolImplementation`: the * bodies of `metaTypeNamespaceExists`, `viewContainerNameCollisionRefusal`, * `saveMetaItem`, `saveMetaItemUnaudited`, `migrateStoredMetadata` moved out of - * `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`. + * `protocol.ts` whole (split by #29998 and #30687). * * A MOVE, not a redesign. `ProtocolSaveFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-search-and-cache.ts b/packages/metadata-protocol/src/protocol-search-and-cache.ts index c29eebfc85d..26edfb2295d 100644 --- a/packages/metadata-protocol/src/protocol-search-and-cache.ts +++ b/packages/metadata-protocol/src/protocol-search-and-cache.ts @@ -3,7 +3,7 @@ /** * [#29985 codemod] The "Global search and the metadata cache" facet of * `ObjectStackProtocolImplementation`: the bodies of `getMetaItemCached` moved - * out of `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`. + * out of `protocol.ts` whole (split by #29998). * * A MOVE, not a redesign. `ProtocolSearchAndCacheFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol-write-gates-tables.ts b/packages/metadata-protocol/src/protocol-write-gates-tables.ts index 84c534b8c96..2e9aee1ace5 100644 --- a/packages/metadata-protocol/src/protocol-write-gates-tables.ts +++ b/packages/metadata-protocol/src/protocol-write-gates-tables.ts @@ -6,8 +6,8 @@ * conflict audit" section of `ObjectStackProtocolImplementation`: the * initializers of `OVERLAY_ALLOWED_TYPES`, `STATIC_REGISTRY_TYPES`, * `RUNTIME_CREATE_ALLOWED_TYPES`, `OVERLAY_CAPABLE_TYPES` moved out of - * `protocol.ts` whole by `scripts/codemod-split-protocol.mjs --members` - * (#30147). + * `protocol.ts` whole by the codemod's `--members` pass + * (split by #30954; #30147). * * A MOVE, not a redesign. Each initializer below is the one the class field of * the same name carried, byte for byte; the field keeps its docblock, diff --git a/packages/metadata-protocol/src/protocol-write-gates.ts b/packages/metadata-protocol/src/protocol-write-gates.ts index b9477b0cc19..124d6e76208 100644 --- a/packages/metadata-protocol/src/protocol-write-gates.ts +++ b/packages/metadata-protocol/src/protocol-write-gates.ts @@ -15,7 +15,7 @@ * `recordOptimisticConflictAudit`, `envWritableTypes`, * `organizationScopedWriteRefusal`, `requestedOrganization`, * `isPackagedBaseRefusal`, `optimisticConflictAuditEntry` moved out of - * `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`. + * `protocol.ts` whole (split by #29998). * * A MOVE, not a redesign. `ProtocolWriteGatesFacet` is a stateless facet over the host * (ruling 6624345766): each static method below is the body of the class diff --git a/packages/metadata-protocol/src/protocol.facade-door-return-types.pin.test.ts b/packages/metadata-protocol/src/protocol.facade-door-return-types.pin.test.ts index fb507ec1fea..92b15f93562 100644 --- a/packages/metadata-protocol/src/protocol.facade-door-return-types.pin.test.ts +++ b/packages/metadata-protocol/src/protocol.facade-door-return-types.pin.test.ts @@ -7,7 +7,7 @@ * * The protocol.ts codemod keeps a non-private method with an inferred return * type on the class (`inferred-return-type` in - * `scripts/codemod-split-protocol.mjs`): the published `.d.ts` prints that + * the codemod, split by #29998): the published `.d.ts` prints that * type, and once the body moved the compiler would infer it through the moved * function instead. Each door below now carries its type on the signature, * copied from the `.d.ts` it was inferred into (the PR proves the built @@ -15,8 +15,8 @@ * the body lives. An edit that drops one of these annotations turns this red, * before a later move could re-infer it. * - * A door's body moves to its facet with `codemod-split-protocol.mjs --members` - * (#30518); until it does, the door keeps its row in + * A door's body moves to its facet as the codemod's `--members` pass did + * (split by #30687; #30518); until it does, the door keeps its row in * `scripts/facade-delegation-registry.json`. */ import { readFileSync } from 'node:fs'; diff --git a/packages/objectql/src/engine-actions.ts b/packages/objectql/src/engine-actions.ts index e29c429a65e..faff736d12b 100644 --- a/packages/objectql/src/engine-actions.ts +++ b/packages/objectql/src/engine-actions.ts @@ -6,8 +6,8 @@ * `listRegisteredActions`, `removeActionsByPackage`, * `setActionActivationStore`, `hydrateActionActivations`, `isActionEnabled`, * `listDisabledActions`, `getDisabledActions`, `describeDisabledAction`, - * `setActionActive` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `setActionActive` moved out of `engine.ts` whole (split + * by #30012). * * A MOVE, not a redesign. {@link ActionsFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index daa43fc8aaf..b8d61f9b68a 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -12,7 +12,7 @@ * `keepsOrganizationReference`, `countReferencingRowsOutside`, * `organizationCountContext`, `organizationCountIsDisclosable`, * `refuseOrganizationDeleteWhileOwned`, `organizationOwnedRowCounts` moved out - * of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * of `engine.ts` whole (split by #30012). * * A MOVE, not a redesign. {@link CascadePlanningFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-compatibility-section.ts b/packages/objectql/src/engine-compatibility-section.ts index 3dc86fb4689..9e59ebd5c8d 100644 --- a/packages/objectql/src/engine-compatibility-section.ts +++ b/packages/objectql/src/engine-compatibility-section.ts @@ -4,8 +4,8 @@ * [#29986 codemod] The "Compatibility / convenience API" section of `ObjectQL`: * the bodies of `unregisterObject`, `getObject`, `getDriverByName`, * `getDriverForObject`, `dropObjectSchema`, `datasource`, `on`, `close`, - * `createContext`, `create` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `createContext`, `create` moved out of `engine.ts` whole (split + * by #30012). * * A MOVE, not a redesign. {@link CompatibilitySectionFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-count-aggregate.ts b/packages/objectql/src/engine-count-aggregate.ts index d877680e163..bcdbeef26ea 100644 --- a/packages/objectql/src/engine-count-aggregate.ts +++ b/packages/objectql/src/engine-count-aggregate.ts @@ -50,7 +50,7 @@ * exist. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-datasource-routing.ts b/packages/objectql/src/engine-datasource-routing.ts index ab98564fc58..bd5c7ea8f83 100644 --- a/packages/objectql/src/engine-datasource-routing.ts +++ b/packages/objectql/src/engine-datasource-routing.ts @@ -47,7 +47,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-defaults-and-autonumbers.ts b/packages/objectql/src/engine-defaults-and-autonumbers.ts index db8fdee18c2..6a97a311083 100644 --- a/packages/objectql/src/engine-defaults-and-autonumbers.ts +++ b/packages/objectql/src/engine-defaults-and-autonumbers.ts @@ -7,7 +7,7 @@ * `defaultFieldEntries`, `applyAutonumbers`, `adoptExplicitAutonumber`, * `createWithAutonumberResync`, `isIssuedAutonumberCollision`, * `warnAutonumberReadersUnserved`, `seedAutonumber` moved out of `engine.ts` - * whole by `scripts/codemod-split-engine.mjs`. + * whole (split by #30012 and #30987). * * A MOVE, not a redesign. {@link DefaultsAndAutonumbersFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 6ea0f870fa0..04061d71105 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -3,8 +3,8 @@ /** * [#29986 codemod] The "Delete, count, aggregate and execute" section of * `ObjectQL`: the bodies of `delete`, `assertNoInternalFieldEvaluated`, - * `aggregate` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `aggregate` moved out of `engine.ts` whole (split + * by #30012 and #31764). * * A MOVE, not a redesign. {@link DeleteAndAggregateFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-delete-cascade.ts b/packages/objectql/src/engine-delete-cascade.ts index 9c963e57986..9103215d533 100644 --- a/packages/objectql/src/engine-delete-cascade.ts +++ b/packages/objectql/src/engine-delete-cascade.ts @@ -71,7 +71,7 @@ * cycle does not exist. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index df621b5e34f..04a6025d4ed 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -58,7 +58,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-execute-transactions.ts b/packages/objectql/src/engine-execute-transactions.ts index 178a67d5bcf..c8118c772e5 100644 --- a/packages/objectql/src/engine-execute-transactions.ts +++ b/packages/objectql/src/engine-execute-transactions.ts @@ -43,7 +43,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-execution-plumbing.ts b/packages/objectql/src/engine-execution-plumbing.ts index 616a42f7f7f..cbbfd28f238 100644 --- a/packages/objectql/src/engine-execution-plumbing.ts +++ b/packages/objectql/src/engine-execution-plumbing.ts @@ -34,7 +34,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-facet-hosts.ts b/packages/objectql/src/engine-facet-hosts.ts index 7bbb7690f2a..68dc3e2eff8 100644 --- a/packages/objectql/src/engine-facet-hosts.ts +++ b/packages/objectql/src/engine-facet-hosts.ts @@ -11,7 +11,7 @@ * when a body assigns it), so a body reads and writes the engine exactly as * the per-call literal let it. * - * Written by `scripts/codemod-split-engine.mjs`; it imports types only, so it forms no + * Written by the engine codemod (split by #30083); it imports types only, so it forms no * evaluation cycle and is evaluated before the class whichever module loads * first. `index.ts` re-exports nothing from this module. */ diff --git a/packages/objectql/src/engine-file-reference-hydration.ts b/packages/objectql/src/engine-file-reference-hydration.ts index cb38749072a..e3ef7f35ae9 100644 --- a/packages/objectql/src/engine-file-reference-hydration.ts +++ b/packages/objectql/src/engine-file-reference-hydration.ts @@ -43,7 +43,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 75d7a3483d3..a877ad7b65a 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -5,7 +5,7 @@ * `ObjectQL`: the bodies of `resolveRelateThenLowerWhere`, `withResolvedWhere`, * `expandSearchOnAst`, `expandSearchOnOptions`, `fillQueryAstDefaults`, * `requireFindOnePredicate`, `find`, `reportFindFailure`, `findOne` moved out - * of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * of `engine.ts` whole (split by #30012 and #31116). * * A MOVE, not a redesign. {@link FindFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-hook-dispatch.ts b/packages/objectql/src/engine-hook-dispatch.ts index 52d7b0c9a5f..0f5f2ccdd30 100644 --- a/packages/objectql/src/engine-hook-dispatch.ts +++ b/packages/objectql/src/engine-hook-dispatch.ts @@ -40,7 +40,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-hooks-and-functions.ts b/packages/objectql/src/engine-hooks-and-functions.ts index f348c559fac..a42dfea02b7 100644 --- a/packages/objectql/src/engine-hooks-and-functions.ts +++ b/packages/objectql/src/engine-hooks-and-functions.ts @@ -10,7 +10,7 @@ * `setDefaultBodyRunner`, `getDefaultBodyRunner`, `setDefaultActionRunner`, * `getDefaultActionRunner`, `triggerHooks`, `hasHooksFor`, * `opensAfterAbortUnit`, `dispatchUnscopedMultiWriteHooks` moved out of - * `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * `engine.ts` whole (split by #30012 and #31151). * * A MOVE, not a redesign. {@link HooksAndFunctionsFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index cc7c40cc50a..566b36a8bca 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -4,8 +4,8 @@ * [#29986 codemod] The "Write preparation and insert" section of `ObjectQL`: * the bodies of `staticReadonlyCreateStrip`, `updateByIdExpecting`, * `ownershipQueueService`, `assignment`, `readUpdatePriorRow`, `insert`, - * `insertMany` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `insertMany` moved out of `engine.ts` whole (split + * by #30012 and #31922). * * A MOVE, not a redesign. {@link InsertFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-master-detail-related.ts b/packages/objectql/src/engine-master-detail-related.ts index 609f4c40dee..9545c102e2d 100644 --- a/packages/objectql/src/engine-master-detail-related.ts +++ b/packages/objectql/src/engine-master-detail-related.ts @@ -51,7 +51,7 @@ * exist. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. * diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index 9f13bff9a1c..cb100e1df1d 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -8,8 +8,8 @@ * `executeWithMiddleware`, `buildReferentialFieldClear`, * `claimReferentialCascadeDelete`, `probeInstallOrganizations`, * `invalidateOrganizationProbe`, `resolveSystemInsertOrganization`, - * `transactionCoversDriverFor` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `transactionCoversDriverFor` moved out of `engine.ts` whole (split + * by #30012). * * A MOVE, not a redesign. {@link MiddlewareAndContextFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-migration-flags.ts b/packages/objectql/src/engine-migration-flags.ts index 9af9ed2f40d..01237bb6144 100644 --- a/packages/objectql/src/engine-migration-flags.ts +++ b/packages/objectql/src/engine-migration-flags.ts @@ -45,7 +45,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-migration-state.ts b/packages/objectql/src/engine-migration-state.ts index f55df71c64c..af661b19ac4 100644 --- a/packages/objectql/src/engine-migration-state.ts +++ b/packages/objectql/src/engine-migration-state.ts @@ -10,7 +10,7 @@ * `readMigrationFlagRowMemoized`, `valueShapeViolationsAdmitted`, * `admittedViolationSink`, `recordObservedDeviation`, * `retractCreationAttestation`, `invalidateDataMigrationFlags`, `destroy` moved - * out of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * out of `engine.ts` whole (split by #30012 and #30987). * * A MOVE, not a redesign. {@link MigrationStateFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-object-repository.ts b/packages/objectql/src/engine-object-repository.ts index ea31e5583d4..97a79f3d07d 100644 --- a/packages/objectql/src/engine-object-repository.ts +++ b/packages/objectql/src/engine-object-repository.ts @@ -5,7 +5,7 @@ * context" section: the bodies of `ObjectRepository`'s methods `find`, * `findOne`, `insert`, `create`, `update`, `updateById`, `delete`, * `deleteById`, `count`, `aggregate`, `execute` moved out of `engine.ts` whole - * by `scripts/codemod-split-engine.mjs` (its second pass). + * (split by #30264, the codemod's second pass). * * A MOVE, not a redesign. {@link ObjectRepositoryFacet} is a stateless facet of * `ObjectRepository`: each static method of it is the body of the diff --git a/packages/objectql/src/engine-package-registration.ts b/packages/objectql/src/engine-package-registration.ts index 6dba7f9c0c3..4b5b6481968 100644 --- a/packages/objectql/src/engine-package-registration.ts +++ b/packages/objectql/src/engine-package-registration.ts @@ -51,7 +51,7 @@ * exist. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-query-lowering.ts b/packages/objectql/src/engine-query-lowering.ts index 89113c3f199..75728f1443e 100644 --- a/packages/objectql/src/engine-query-lowering.ts +++ b/packages/objectql/src/engine-query-lowering.ts @@ -55,7 +55,7 @@ * not exist. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-readable-ids-permission-formula.ts b/packages/objectql/src/engine-readable-ids-permission-formula.ts index 4bf1bd361dc..b471b134100 100644 --- a/packages/objectql/src/engine-readable-ids-permission-formula.ts +++ b/packages/objectql/src/engine-readable-ids-permission-formula.ts @@ -59,7 +59,7 @@ * bundles both files into one, where the cycle does not exist. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. * diff --git a/packages/objectql/src/engine-realtime-publish.ts b/packages/objectql/src/engine-realtime-publish.ts index 6532996e904..ec7f4c79a1b 100644 --- a/packages/objectql/src/engine-realtime-publish.ts +++ b/packages/objectql/src/engine-realtime-publish.ts @@ -39,7 +39,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-reference-name-visible.ts b/packages/objectql/src/engine-reference-name-visible.ts index 41e1d09b03e..d81e5dbe159 100644 --- a/packages/objectql/src/engine-reference-name-visible.ts +++ b/packages/objectql/src/engine-reference-name-visible.ts @@ -64,7 +64,7 @@ * at run time, and nothing re-exports it. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ @@ -268,7 +268,7 @@ async function servableNameField( /** * [#30020 codemod] The `formulaReadsReference` slot of the host * `ObjectQL#serveReferenceNames` hands {@link serveReferenceNames}: moved here - * whole by `--hand-slots` of `scripts/codemod-split-engine.mjs`, and the slot + * whole by the codemod's `--hand-slots` (split by #30987), and the slot * names it. */ export const formulaReadsReference: ReferenceNameVisibleHost['formulaReadsReference'] = (name, def, fields) => { diff --git a/packages/objectql/src/engine-references-and-master-detail.ts b/packages/objectql/src/engine-references-and-master-detail.ts index 53a8dc843b8..2fb73a40a3d 100644 --- a/packages/objectql/src/engine-references-and-master-detail.ts +++ b/packages/objectql/src/engine-references-and-master-detail.ts @@ -10,8 +10,8 @@ * `callerReadableReferenceExists`, `resolveMasterDetailParent`, * `resolveMasterDetailParents`, `materializeParentHeader`, * `masterDeclaredFields`, `inspectDanglingReferences`, `inspectCascadeDelete`, - * `getCascadeDeleteObjects` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `getCascadeDeleteObjects` moved out of `engine.ts` whole (split + * by #30012 and #30463). * * A MOVE, not a redesign. {@link ReferencesAndMasterDetailFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-referential-integrity.ts b/packages/objectql/src/engine-referential-integrity.ts index ffa5f04153e..8ff2422dc11 100644 --- a/packages/objectql/src/engine-referential-integrity.ts +++ b/packages/objectql/src/engine-referential-integrity.ts @@ -45,7 +45,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-registration.ts b/packages/objectql/src/engine-registration.ts index 546bd9ddebf..054b8a2ac51 100644 --- a/packages/objectql/src/engine-registration.ts +++ b/packages/objectql/src/engine-registration.ts @@ -9,7 +9,7 @@ * `registerDatasourceDef`, `applyExternalDriverFloor`, `listDatasourceDefs`, * `markDatasourceUnavailable`, `clearDatasourceUnavailable`, * `getDefaultDriverName`, `listUnavailableDatasources`, `assertWriteAllowed` - * moved out of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * moved out of `engine.ts` whole (split by #30012 and #30716). * `isExternalWriteForbidden` (#30370) was written here, beside the gate whose * verdict it answers. * diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 879222275c4..e2491e6e4ee 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -5,8 +5,8 @@ * transactions" section: the bodies of `ScopedContext`'s methods `object`, * `sudo`, `withRunAs`, `[SEED_USER_GRANTS]`, `transaction`, * `releaseJoinedHandle`, `txDriver`, `beginTransaction`, `commitTransaction`, - * `rollbackTransaction`, `serveFormulaField` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs` (its second pass). + * `rollbackTransaction`, `serveFormulaField` moved out of `engine.ts` whole (split + * by #30264 and #31665, the codemod's second pass). * The bodies of `derive` and `[APP_AUTHORED_HOOK_API]` moved by hand * (#30975): each writes the private `appAuthored` of the instance it builds, * which the codemod refuses to move (`foreign-private`), so each writes it diff --git a/packages/objectql/src/engine-scoped-hosts.ts b/packages/objectql/src/engine-scoped-hosts.ts index 6f05b52d377..5a372b07265 100644 --- a/packages/objectql/src/engine-scoped-hosts.ts +++ b/packages/objectql/src/engine-scoped-hosts.ts @@ -11,7 +11,7 @@ * a body assigns it), so a body reads and writes the instance exactly as * the method did. * - * Written by `scripts/codemod-split-engine.mjs` (its second pass). It imports + * Written by the engine codemod's second pass (split by #30264). It imports * types only, so it forms no evaluation cycle and is evaluated before the * classes whichever module loads first. `index.ts` re-exports nothing from * this module. diff --git a/packages/objectql/src/engine-secret-internal-fields.ts b/packages/objectql/src/engine-secret-internal-fields.ts index 2c8afad5a92..e4fe27a4457 100644 --- a/packages/objectql/src/engine-secret-internal-fields.ts +++ b/packages/objectql/src/engine-secret-internal-fields.ts @@ -57,7 +57,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30341), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/engine-secrets-and-routing.ts b/packages/objectql/src/engine-secrets-and-routing.ts index d56b9931bff..7fc2ee546cc 100644 --- a/packages/objectql/src/engine-secrets-and-routing.ts +++ b/packages/objectql/src/engine-secrets-and-routing.ts @@ -8,7 +8,7 @@ * `resolveObjectName`, `judgeFilter`, `isSystemLedgerObject`, * `resolveDatasourceBinding`, `resolveEffectiveDatasource`, * `resolveMappedDatasource`, `setDatasourceMapping`, `init` moved out of - * `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * `engine.ts` whole (split by #30012 and #30571). * * A MOVE, not a redesign. {@link SecretsAndRoutingFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-security-resolvers.ts b/packages/objectql/src/engine-security-resolvers.ts index c66a13d2d3e..5b6eff5d0e9 100644 --- a/packages/objectql/src/engine-security-resolvers.ts +++ b/packages/objectql/src/engine-security-resolvers.ts @@ -10,7 +10,7 @@ * `composeReadableIdsAtBoundary`, `refuseUncomposableReadableIdsClasses`, * `uncomposableReadableIdsParent`, `resolveFormulaRelated`, * `serveFormulaField`, `formulaOptionLabels`, `formulaFaultSink` moved out of - * `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * `engine.ts` whole (split by #30012 and #30987). * * A MOVE, not a redesign. {@link SecurityResolversFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 154914f15ad..dcfaef8d0bb 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -7,7 +7,7 @@ * `buildSummaryIndex`, `ensureSummaryIndexes`, `getSummaryDescriptors`, * `summaryForeignKeyColumns`, `getOwnedSummaryDescriptors`, * `initializeSummaryFields`, `recomputeSummaries`, `expandRelatedRecords` moved - * out of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * out of `engine.ts` whole (split by #30012 and #30987). * * A MOVE, not a redesign. {@link SummariesAndExpansionFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 705972c2fe2..1638ab8d1b2 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -1,7 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29986 codemod] The top-level declarations ahead of `ObjectQL` in -// `engine.ts` that moved out whole by `scripts/codemod-split-engine.mjs` (lever +// `engine.ts` that moved out whole (split by #30012; lever // (b) of ruling 6591753301). // // A MOVE, not a redesign: each declaration below is its `engine.ts` text diff --git a/packages/objectql/src/engine-transactions-section.ts b/packages/objectql/src/engine-transactions-section.ts index 58cb7b9b9f7..20d4b0047f3 100644 --- a/packages/objectql/src/engine-transactions-section.ts +++ b/packages/objectql/src/engine-transactions-section.ts @@ -3,8 +3,8 @@ /** * [#29986 codemod] The "Transactions" section of `ObjectQL`: the bodies of * `transaction`, `runOpenedUnit`, `isClosedUnitHandle`, `newTransactionScope`, - * `datasourceNameOf` moved out of `engine.ts` whole by - * `scripts/codemod-split-engine.mjs`. + * `datasourceNameOf` moved out of `engine.ts` whole (split + * by #30012). * * A MOVE, not a redesign. {@link TransactionsSectionFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 92f0c059204..59f9c42bf33 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -2,7 +2,7 @@ /** * [#29986 codemod] The "Update" section of `ObjectQL`: the bodies of `update` - * moved out of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * moved out of `engine.ts` whole (split by #32046). * * A MOVE, not a redesign. {@link UpdateFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` diff --git a/packages/objectql/src/engine-validation-messages.ts b/packages/objectql/src/engine-validation-messages.ts index 499a0f0a28d..1f8e4dc5715 100644 --- a/packages/objectql/src/engine-validation-messages.ts +++ b/packages/objectql/src/engine-validation-messages.ts @@ -40,7 +40,7 @@ * move. * * [#30053 codemod] A PRIVATE method's docblock has since moved here, - * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`), + * onto its function (`--hand-docs`, split by #30415), * and the class keeps none for it; a public or protected method's docblock * stays on the class, the contract, and its function keeps the placeholder. */ diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 03a0182ab3a..9853ce87827 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -111,7 +111,7 @@ interface Row { } /** - * engine.ts and the modules `scripts/codemod-split-engine.mjs` (#29986) split + * engine.ts and the modules split by #30012 (the #29986 codemod) * out of it. A method there may keep its signature in engine.ts and its body in * one of these, so a {@link Row.via} helper is looked up across the set. */ diff --git a/packages/spec/scripts/conversions-major18-merge.test.ts b/packages/spec/scripts/conversions-major18-merge.test.ts index 9b1db37d7c5..9d6e63e09ed 100644 --- a/packages/spec/scripts/conversions-major18-merge.test.ts +++ b/packages/spec/scripts/conversions-major18-merge.test.ts @@ -22,7 +22,7 @@ // the lit controls — each MUST conflict, or a clean result would be equally // explained by a harness that cannot see a conflict at all. // -// [#29987 codemod] Since the codemod split (`scripts/codemod-split-conversions-registry.mjs`) +// [#29987 codemod] Since the registry was split by #29993, // each conversion is DEFINED in a module of its own, `src/conversions/entries/18/.ts`, // which a retirement adds as a new file and which therefore never conflicts. What a // retirement still edits in `registry.ts` is two lines: the import of its conversion and diff --git a/packages/spec/src/conversions/entries/11/flow-node-crud-filter-alias.ts b/packages/spec/src/conversions/entries/11/flow-node-crud-filter-alias.ts index 35a42a62439..4cfaa181de6 100644 --- a/packages/spec/src/conversions/entries/11/flow-node-crud-filter-alias.ts +++ b/packages/spec/src/conversions/entries/11/flow-node-crud-filter-alias.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-crud-filter-alias` conversion (`toMajor: -// 11`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 11`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/11/flow-node-http-callout-rename.ts b/packages/spec/src/conversions/entries/11/flow-node-http-callout-rename.ts index 7eb475ff354..8e2f448f524 100644 --- a/packages/spec/src/conversions/entries/11/flow-node-http-callout-rename.ts +++ b/packages/spec/src/conversions/entries/11/flow-node-http-callout-rename.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-http-callout-rename` conversion (`toMajor: -// 11`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 11`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/11/page-kind-jsx-to-html.ts b/packages/spec/src/conversions/entries/11/page-kind-jsx-to-html.ts index 625b154add4..cac8c3c725d 100644 --- a/packages/spec/src/conversions/entries/11/page-kind-jsx-to-html.ts +++ b/packages/spec/src/conversions/entries/11/page-kind-jsx-to-html.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-kind-jsx-to-html` conversion (`toMajor: 11`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/15/page-component-visibility-to-visibleWhen.ts b/packages/spec/src/conversions/entries/15/page-component-visibility-to-visibleWhen.ts index f5e8109da99..50a095505ea 100644 --- a/packages/spec/src/conversions/entries/15/page-component-visibility-to-visibleWhen.ts +++ b/packages/spec/src/conversions/entries/15/page-component-visibility-to-visibleWhen.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-component-visibility-to-visibleWhen` conversion -// (`toMajor: 15`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 15`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/15/view-visibleOn-to-visibleWhen.ts b/packages/spec/src/conversions/entries/15/view-visibleOn-to-visibleWhen.ts index 02110233cfb..d13e42808df 100644 --- a/packages/spec/src/conversions/entries/15/view-visibleOn-to-visibleWhen.ts +++ b/packages/spec/src/conversions/entries/15/view-visibleOn-to-visibleWhen.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-visibleOn-to-visibleWhen` conversion (`toMajor: -// 15`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 15`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/datasource-driver-mongo-to-mongodb.ts b/packages/spec/src/conversions/entries/17/datasource-driver-mongo-to-mongodb.ts index 87ba3052516..547b19e707a 100644 --- a/packages/spec/src/conversions/entries/17/datasource-driver-mongo-to-mongodb.ts +++ b/packages/spec/src/conversions/entries/17/datasource-driver-mongo-to-mongodb.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `datasource-driver-mongo-to-mongodb` conversion -// (`toMajor: 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-connector-config-lift.ts b/packages/spec/src/conversions/entries/17/flow-node-connector-config-lift.ts index c89301d3ba2..1e42be6bb3b 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-connector-config-lift.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-connector-config-lift.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-connector-config-lift` conversion (`toMajor: -// 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-crud-object-alias.ts b/packages/spec/src/conversions/entries/17/flow-node-crud-object-alias.ts index ab2331ea7b7..4334d7d27d7 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-crud-object-alias.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-crud-object-alias.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-crud-object-alias` conversion (`toMajor: -// 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-map-flow-alias.ts b/packages/spec/src/conversions/entries/17/flow-node-map-flow-alias.ts index 81c142d4d7b..75e61186ac4 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-map-flow-alias.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-map-flow-alias.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-map-flow-alias` conversion (`toMajor: 17`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-notify-config-aliases.ts b/packages/spec/src/conversions/entries/17/flow-node-notify-config-aliases.ts index 33e543e4588..c306e9640ea 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-notify-config-aliases.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-notify-config-aliases.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-notify-config-aliases` conversion (`toMajor: -// 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-script-config-aliases.ts b/packages/spec/src/conversions/entries/17/flow-node-script-config-aliases.ts index 891d1469158..9e7d456d770 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-script-config-aliases.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-script-config-aliases.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-script-config-aliases` conversion (`toMajor: -// 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-subflow-flow-alias.ts b/packages/spec/src/conversions/entries/17/flow-node-subflow-flow-alias.ts index 7a660a2787d..f570259f88e 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-subflow-flow-alias.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-subflow-flow-alias.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-subflow-flow-alias` conversion (`toMajor: -// 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/flow-node-wait-event-config-lift.ts b/packages/spec/src/conversions/entries/17/flow-node-wait-event-config-lift.ts index 83c1408542e..7d6f8fc7f30 100644 --- a/packages/spec/src/conversions/entries/17/flow-node-wait-event-config-lift.ts +++ b/packages/spec/src/conversions/entries/17/flow-node-wait-event-config-lift.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-node-wait-event-config-lift` conversion (`toMajor: -// 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/inline-action-api-params-to-body-extra.ts b/packages/spec/src/conversions/entries/17/inline-action-api-params-to-body-extra.ts index fb51ffb693c..42261c5f700 100644 --- a/packages/spec/src/conversions/entries/17/inline-action-api-params-to-body-extra.ts +++ b/packages/spec/src/conversions/entries/17/inline-action-api-params-to-body-extra.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `inline-action-api-params-to-body-extra` conversion -// (`toMajor: 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/page-header-subtitle-alias.ts b/packages/spec/src/conversions/entries/17/page-header-subtitle-alias.ts index ed0802a6fda..04376f7d579 100644 --- a/packages/spec/src/conversions/entries/17/page-header-subtitle-alias.ts +++ b/packages/spec/src/conversions/entries/17/page-header-subtitle-alias.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-header-subtitle-alias` conversion (`toMajor: 17`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/retry-policy-converged.ts b/packages/spec/src/conversions/entries/17/retry-policy-converged.ts index 2fde65a9ff2..df8d38c3c73 100644 --- a/packages/spec/src/conversions/entries/17/retry-policy-converged.ts +++ b/packages/spec/src/conversions/entries/17/retry-policy-converged.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `retry-policy-converged` conversion (`toMajor: 17`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/17/sharing-rule-access-level-full-to-edit.ts b/packages/spec/src/conversions/entries/17/sharing-rule-access-level-full-to-edit.ts index 3c9ef5d18fc..f6dc33f8478 100644 --- a/packages/spec/src/conversions/entries/17/sharing-rule-access-level-full-to-edit.ts +++ b/packages/spec/src/conversions/entries/17/sharing-rule-access-level-full-to-edit.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `sharing-rule-access-level-full-to-edit` conversion -// (`toMajor: 17`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 17`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/action-aria-removed.ts b/packages/spec/src/conversions/entries/18/action-aria-removed.ts index aab8c8bbbc5..bf5fef55e16 100644 --- a/packages/spec/src/conversions/entries/18/action-aria-removed.ts +++ b/packages/spec/src/conversions/entries/18/action-aria-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `action-aria-removed` conversion (`toMajor: 18`), moved -// out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/action-block-endpoint-to-target.ts b/packages/spec/src/conversions/entries/18/action-block-endpoint-to-target.ts index 23c12d7b193..43568106510 100644 --- a/packages/spec/src/conversions/entries/18/action-block-endpoint-to-target.ts +++ b/packages/spec/src/conversions/entries/18/action-block-endpoint-to-target.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `action-block-endpoint-to-target` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/add-record-enabled-defaulted.ts b/packages/spec/src/conversions/entries/18/add-record-enabled-defaulted.ts index a4f59e37f80..d75c986fb2d 100644 --- a/packages/spec/src/conversions/entries/18/add-record-enabled-defaulted.ts +++ b/packages/spec/src/conversions/entries/18/add-record-enabled-defaulted.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `add-record-enabled-defaulted` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/add-record-mode-form-view-removed.ts b/packages/spec/src/conversions/entries/18/add-record-mode-form-view-removed.ts index ccd50e3ed0d..162413b7893 100644 --- a/packages/spec/src/conversions/entries/18/add-record-mode-form-view-removed.ts +++ b/packages/spec/src/conversions/entries/18/add-record-mode-form-view-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `add-record-mode-form-view-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/agent-lifecycle-removed.ts b/packages/spec/src/conversions/entries/18/agent-lifecycle-removed.ts index 6a28beaaada..7caa9cc8c61 100644 --- a/packages/spec/src/conversions/entries/18/agent-lifecycle-removed.ts +++ b/packages/spec/src/conversions/entries/18/agent-lifecycle-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `agent-lifecycle-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/agent-memory-long-term-store-removed.ts b/packages/spec/src/conversions/entries/18/agent-memory-long-term-store-removed.ts index 63d2af94c70..1a323a4754b 100644 --- a/packages/spec/src/conversions/entries/18/agent-memory-long-term-store-removed.ts +++ b/packages/spec/src/conversions/entries/18/agent-memory-long-term-store-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `agent-memory-long-term-store-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/agent-structured-output-refused-members-removed.ts b/packages/spec/src/conversions/entries/18/agent-structured-output-refused-members-removed.ts index 7a5466a41c3..ee2873bc89c 100644 --- a/packages/spec/src/conversions/entries/18/agent-structured-output-refused-members-removed.ts +++ b/packages/spec/src/conversions/entries/18/agent-structured-output-refused-members-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `agent-structured-output-refused-members-removed` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/api-endpoint-cache-ttl-to-cache-ttl-seconds.ts b/packages/spec/src/conversions/entries/18/api-endpoint-cache-ttl-to-cache-ttl-seconds.ts index 8f7c9d39be8..6a8179fd111 100644 --- a/packages/spec/src/conversions/entries/18/api-endpoint-cache-ttl-to-cache-ttl-seconds.ts +++ b/packages/spec/src/conversions/entries/18/api-endpoint-cache-ttl-to-cache-ttl-seconds.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `api-endpoint-cache-ttl-to-cache-ttl-seconds` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/cbp-master-detail-required-defaulted.ts b/packages/spec/src/conversions/entries/18/cbp-master-detail-required-defaulted.ts index 2a996a1d0f7..f6317c8bb47 100644 --- a/packages/spec/src/conversions/entries/18/cbp-master-detail-required-defaulted.ts +++ b/packages/spec/src/conversions/entries/18/cbp-master-detail-required-defaulted.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `cbp-master-detail-required-defaulted` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/chart-config-aria-removed.ts b/packages/spec/src/conversions/entries/18/chart-config-aria-removed.ts index 9016a13dafd..87815eea4f5 100644 --- a/packages/spec/src/conversions/entries/18/chart-config-aria-removed.ts +++ b/packages/spec/src/conversions/entries/18/chart-config-aria-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `chart-config-aria-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/connector-connection-timeout-ms-removed.ts b/packages/spec/src/conversions/entries/18/connector-connection-timeout-ms-removed.ts index 656d3b4a9ea..5bb93dcf522 100644 --- a/packages/spec/src/conversions/entries/18/connector-connection-timeout-ms-removed.ts +++ b/packages/spec/src/conversions/entries/18/connector-connection-timeout-ms-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `connector-connection-timeout-ms-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/connector-error-mapping-removed.ts b/packages/spec/src/conversions/entries/18/connector-error-mapping-removed.ts index e94bdf6896f..fd164ec5df0 100644 --- a/packages/spec/src/conversions/entries/18/connector-error-mapping-removed.ts +++ b/packages/spec/src/conversions/entries/18/connector-error-mapping-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `connector-error-mapping-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/connector-resilience-keys-removed.ts b/packages/spec/src/conversions/entries/18/connector-resilience-keys-removed.ts index 2c5ef3fab01..2c631be8da3 100644 --- a/packages/spec/src/conversions/entries/18/connector-resilience-keys-removed.ts +++ b/packages/spec/src/conversions/entries/18/connector-resilience-keys-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `connector-resilience-keys-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/connector-sync-keys-removed.ts b/packages/spec/src/conversions/entries/18/connector-sync-keys-removed.ts index 98d86333f82..c683b769e7d 100644 --- a/packages/spec/src/conversions/entries/18/connector-sync-keys-removed.ts +++ b/packages/spec/src/conversions/entries/18/connector-sync-keys-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `connector-sync-keys-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/connector-triggers-removed.ts b/packages/spec/src/conversions/entries/18/connector-triggers-removed.ts index e4358d14ca5..ab70179ac60 100644 --- a/packages/spec/src/conversions/entries/18/connector-triggers-removed.ts +++ b/packages/spec/src/conversions/entries/18/connector-triggers-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `connector-triggers-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/cube-join-sql-and-relationship-removed.ts b/packages/spec/src/conversions/entries/18/cube-join-sql-and-relationship-removed.ts index 7d9a9f82026..fa874306c21 100644 --- a/packages/spec/src/conversions/entries/18/cube-join-sql-and-relationship-removed.ts +++ b/packages/spec/src/conversions/entries/18/cube-join-sql-and-relationship-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `cube-join-sql-and-relationship-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/cube-member-inner-name-removed.ts b/packages/spec/src/conversions/entries/18/cube-member-inner-name-removed.ts index 9e3f8684207..b3880180770 100644 --- a/packages/spec/src/conversions/entries/18/cube-member-inner-name-removed.ts +++ b/packages/spec/src/conversions/entries/18/cube-member-inner-name-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `cube-member-inner-name-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/cube-refresh-key-removed.ts b/packages/spec/src/conversions/entries/18/cube-refresh-key-removed.ts index d8a9947932b..09c4d418799 100644 --- a/packages/spec/src/conversions/entries/18/cube-refresh-key-removed.ts +++ b/packages/spec/src/conversions/entries/18/cube-refresh-key-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `cube-refresh-key-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/cube-sub-day-granularities-removed.ts b/packages/spec/src/conversions/entries/18/cube-sub-day-granularities-removed.ts index de26ccad620..c5870ac1fa8 100644 --- a/packages/spec/src/conversions/entries/18/cube-sub-day-granularities-removed.ts +++ b/packages/spec/src/conversions/entries/18/cube-sub-day-granularities-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `cube-sub-day-granularities-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/currency-config-dynamic-default-currency-removed.ts b/packages/spec/src/conversions/entries/18/currency-config-dynamic-default-currency-removed.ts index aeaf4168d89..cc31f9aab04 100644 --- a/packages/spec/src/conversions/entries/18/currency-config-dynamic-default-currency-removed.ts +++ b/packages/spec/src/conversions/entries/18/currency-config-dynamic-default-currency-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `currency-config-dynamic-default-currency-removed` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/currency-config-precision-removed.ts b/packages/spec/src/conversions/entries/18/currency-config-precision-removed.ts index acf3dc39f65..0d1672db761 100644 --- a/packages/spec/src/conversions/entries/18/currency-config-precision-removed.ts +++ b/packages/spec/src/conversions/entries/18/currency-config-precision-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `currency-config-precision-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/dashboard-refresh-interval-to-refresh-interval-seconds.ts b/packages/spec/src/conversions/entries/18/dashboard-refresh-interval-to-refresh-interval-seconds.ts index 810fe659d46..34a7ee8d18c 100644 --- a/packages/spec/src/conversions/entries/18/dashboard-refresh-interval-to-refresh-interval-seconds.ts +++ b/packages/spec/src/conversions/entries/18/dashboard-refresh-interval-to-refresh-interval-seconds.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `dashboard-refresh-interval-to-refresh-interval-seconds` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/dashboard-widget-chart-config-structure-removed.ts b/packages/spec/src/conversions/entries/18/dashboard-widget-chart-config-structure-removed.ts index c241bd970f7..60c8e8929b4 100644 --- a/packages/spec/src/conversions/entries/18/dashboard-widget-chart-config-structure-removed.ts +++ b/packages/spec/src/conversions/entries/18/dashboard-widget-chart-config-structure-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `dashboard-widget-chart-config-structure-removed` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/dataset-count-measure-empty-field-removed.ts b/packages/spec/src/conversions/entries/18/dataset-count-measure-empty-field-removed.ts index 5a262fc0a10..af66126eb84 100644 --- a/packages/spec/src/conversions/entries/18/dataset-count-measure-empty-field-removed.ts +++ b/packages/spec/src/conversions/entries/18/dataset-count-measure-empty-field-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `dataset-count-measure-empty-field-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/declared-index-unique-scope.ts b/packages/spec/src/conversions/entries/18/declared-index-unique-scope.ts index a5188393449..fe8742c61a7 100644 --- a/packages/spec/src/conversions/entries/18/declared-index-unique-scope.ts +++ b/packages/spec/src/conversions/entries/18/declared-index-unique-scope.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `declared-index-unique-scope` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/element-filter-removed.ts b/packages/spec/src/conversions/entries/18/element-filter-removed.ts index 275880dd264..bcabdb4cbe0 100644 --- a/packages/spec/src/conversions/entries/18/element-filter-removed.ts +++ b/packages/spec/src/conversions/entries/18/element-filter-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `element-filter-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/element-flat-data-binding-to-data-source.ts b/packages/spec/src/conversions/entries/18/element-flat-data-binding-to-data-source.ts index cce63e3600a..f26a99a3558 100644 --- a/packages/spec/src/conversions/entries/18/element-flat-data-binding-to-data-source.ts +++ b/packages/spec/src/conversions/entries/18/element-flat-data-binding-to-data-source.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `element-flat-data-binding-to-data-source` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/element-form-removed.ts b/packages/spec/src/conversions/entries/18/element-form-removed.ts index 0c9845ad3be..448cd30369d 100644 --- a/packages/spec/src/conversions/entries/18/element-form-removed.ts +++ b/packages/spec/src/conversions/entries/18/element-form-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `element-form-removed` conversion (`toMajor: 18`), moved -// out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/element-input-target-variable-removed.ts b/packages/spec/src/conversions/entries/18/element-input-target-variable-removed.ts index 58bf0945c8d..edb7f2040b2 100644 --- a/packages/spec/src/conversions/entries/18/element-input-target-variable-removed.ts +++ b/packages/spec/src/conversions/entries/18/element-input-target-variable-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `element-input-target-variable-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/element-text-variant-heading-levels.ts b/packages/spec/src/conversions/entries/18/element-text-variant-heading-levels.ts index 47b8c7c99a1..8fb64938995 100644 --- a/packages/spec/src/conversions/entries/18/element-text-variant-heading-levels.ts +++ b/packages/spec/src/conversions/entries/18/element-text-variant-heading-levels.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `element-text-variant-heading-levels` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/email-template-category-is-system-removed.ts b/packages/spec/src/conversions/entries/18/email-template-category-is-system-removed.ts index e15b77055b6..7e7bd9b421c 100644 --- a/packages/spec/src/conversions/entries/18/email-template-category-is-system-removed.ts +++ b/packages/spec/src/conversions/entries/18/email-template-category-is-system-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `email-template-category-is-system-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/field-column-lists-canonicalized.ts b/packages/spec/src/conversions/entries/18/field-column-lists-canonicalized.ts index dab902d4a5e..593ecbaa338 100644 --- a/packages/spec/src/conversions/entries/18/field-column-lists-canonicalized.ts +++ b/packages/spec/src/conversions/entries/18/field-column-lists-canonicalized.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `field-column-lists-canonicalized` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/field-malformed-scale-precision-removed.ts b/packages/spec/src/conversions/entries/18/field-malformed-scale-precision-removed.ts index 834963e080e..88391a34108 100644 --- a/packages/spec/src/conversions/entries/18/field-malformed-scale-precision-removed.ts +++ b/packages/spec/src/conversions/entries/18/field-malformed-scale-precision-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `field-malformed-scale-precision-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/field-reference-to-alias.ts b/packages/spec/src/conversions/entries/18/field-reference-to-alias.ts index 2b896ec6f69..14af7e24f5f 100644 --- a/packages/spec/src/conversions/entries/18/field-reference-to-alias.ts +++ b/packages/spec/src/conversions/entries/18/field-reference-to-alias.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `field-reference-to-alias` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/flow-decision-mode-inclusive-explicit.ts b/packages/spec/src/conversions/entries/18/flow-decision-mode-inclusive-explicit.ts index cf263173c03..2ac1bc4a182 100644 --- a/packages/spec/src/conversions/entries/18/flow-decision-mode-inclusive-explicit.ts +++ b/packages/spec/src/conversions/entries/18/flow-decision-mode-inclusive-explicit.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `flow-decision-mode-inclusive-explicit` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-field-public-picker-removed.ts b/packages/spec/src/conversions/entries/18/form-field-public-picker-removed.ts index be9fbe76fad..38b2f1bbbf4 100644 --- a/packages/spec/src/conversions/entries/18/form-field-public-picker-removed.ts +++ b/packages/spec/src/conversions/entries/18/form-field-public-picker-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-field-public-picker-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-layout-inline-grid-to-vertical.ts b/packages/spec/src/conversions/entries/18/form-layout-inline-grid-to-vertical.ts index 41f117c5528..8ddb6adfb2d 100644 --- a/packages/spec/src/conversions/entries/18/form-layout-inline-grid-to-vertical.ts +++ b/packages/spec/src/conversions/entries/18/form-layout-inline-grid-to-vertical.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-layout-inline-grid-to-vertical` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-view-buttons-reset-removed.ts b/packages/spec/src/conversions/entries/18/form-view-buttons-reset-removed.ts index 03d7aa4505c..b37cf1073fc 100644 --- a/packages/spec/src/conversions/entries/18/form-view-buttons-reset-removed.ts +++ b/packages/spec/src/conversions/entries/18/form-view-buttons-reset-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-view-buttons-reset-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-view-drawer-keys-removed.ts b/packages/spec/src/conversions/entries/18/form-view-drawer-keys-removed.ts index ab5ab1c1695..cb22b38d458 100644 --- a/packages/spec/src/conversions/entries/18/form-view-drawer-keys-removed.ts +++ b/packages/spec/src/conversions/entries/18/form-view-drawer-keys-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-view-drawer-keys-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-view-option-default-removed.ts b/packages/spec/src/conversions/entries/18/form-view-option-default-removed.ts index 43517ef41d5..7c670d16384 100644 --- a/packages/spec/src/conversions/entries/18/form-view-option-default-removed.ts +++ b/packages/spec/src/conversions/entries/18/form-view-option-default-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-view-option-default-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-view-presentation-types-removed.ts b/packages/spec/src/conversions/entries/18/form-view-presentation-types-removed.ts index 9d5bfb1d8ce..dc8a17e3077 100644 --- a/packages/spec/src/conversions/entries/18/form-view-presentation-types-removed.ts +++ b/packages/spec/src/conversions/entries/18/form-view-presentation-types-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-view-presentation-types-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/form-view-subform-columns-canonicalized.ts b/packages/spec/src/conversions/entries/18/form-view-subform-columns-canonicalized.ts index a9800895185..3fa44826c02 100644 --- a/packages/spec/src/conversions/entries/18/form-view-subform-columns-canonicalized.ts +++ b/packages/spec/src/conversions/entries/18/form-view-subform-columns-canonicalized.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `form-view-subform-columns-canonicalized` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/hook-timeout-to-timeout-ms.ts b/packages/spec/src/conversions/entries/18/hook-timeout-to-timeout-ms.ts index 7a52aa414ad..c175bfd0806 100644 --- a/packages/spec/src/conversions/entries/18/hook-timeout-to-timeout-ms.ts +++ b/packages/spec/src/conversions/entries/18/hook-timeout-to-timeout-ms.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `hook-timeout-to-timeout-ms` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/job-timeout-to-timeout-ms.ts b/packages/spec/src/conversions/entries/18/job-timeout-to-timeout-ms.ts index 76b330aae60..849aed69b7f 100644 --- a/packages/spec/src/conversions/entries/18/job-timeout-to-timeout-ms.ts +++ b/packages/spec/src/conversions/entries/18/job-timeout-to-timeout-ms.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `job-timeout-to-timeout-ms` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/list-view-options-bag-folded.ts b/packages/spec/src/conversions/entries/18/list-view-options-bag-folded.ts index cc8514b6041..b16e9e2ceab 100644 --- a/packages/spec/src/conversions/entries/18/list-view-options-bag-folded.ts +++ b/packages/spec/src/conversions/entries/18/list-view-options-bag-folded.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `list-view-options-bag-folded` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/list-view-sort-string-clause-to-array.ts b/packages/spec/src/conversions/entries/18/list-view-sort-string-clause-to-array.ts index fa83ecc5c74..030cd64fa00 100644 --- a/packages/spec/src/conversions/entries/18/list-view-sort-string-clause-to-array.ts +++ b/packages/spec/src/conversions/entries/18/list-view-sort-string-clause-to-array.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `list-view-sort-string-clause-to-array` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/manifest-packaging-manifest-deps-removed.ts b/packages/spec/src/conversions/entries/18/manifest-packaging-manifest-deps-removed.ts index e63ee94d124..efffdb2471e 100644 --- a/packages/spec/src/conversions/entries/18/manifest-packaging-manifest-deps-removed.ts +++ b/packages/spec/src/conversions/entries/18/manifest-packaging-manifest-deps-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `manifest-packaging-manifest-deps-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/manifest-permissions-string-list-removed.ts b/packages/spec/src/conversions/entries/18/manifest-permissions-string-list-removed.ts index 4a1d41f7b3c..2bce4a0cb3e 100644 --- a/packages/spec/src/conversions/entries/18/manifest-permissions-string-list-removed.ts +++ b/packages/spec/src/conversions/entries/18/manifest-permissions-string-list-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `manifest-permissions-string-list-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/mapping-lookup-params-removed.ts b/packages/spec/src/conversions/entries/18/mapping-lookup-params-removed.ts index 99e356e0c60..450dea9acda 100644 --- a/packages/spec/src/conversions/entries/18/mapping-lookup-params-removed.ts +++ b/packages/spec/src/conversions/entries/18/mapping-lookup-params-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `mapping-lookup-params-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/memory-persistence-auto-save-interval-to-ms.ts b/packages/spec/src/conversions/entries/18/memory-persistence-auto-save-interval-to-ms.ts index 6cc48f57b3c..ccf994036d3 100644 --- a/packages/spec/src/conversions/entries/18/memory-persistence-auto-save-interval-to-ms.ts +++ b/packages/spec/src/conversions/entries/18/memory-persistence-auto-save-interval-to-ms.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `memory-persistence-auto-save-interval-to-ms` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/metric-filters-removed.ts b/packages/spec/src/conversions/entries/18/metric-filters-removed.ts index 32f3bccaf4f..763df6c6583 100644 --- a/packages/spec/src/conversions/entries/18/metric-filters-removed.ts +++ b/packages/spec/src/conversions/entries/18/metric-filters-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `metric-filters-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/navigation-mode-overlay-values-removed.ts b/packages/spec/src/conversions/entries/18/navigation-mode-overlay-values-removed.ts index fe4fc6cdb70..d2c7e185d69 100644 --- a/packages/spec/src/conversions/entries/18/navigation-mode-overlay-values-removed.ts +++ b/packages/spec/src/conversions/entries/18/navigation-mode-overlay-values-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `navigation-mode-overlay-values-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-external-sharing-model-removed.ts b/packages/spec/src/conversions/entries/18/object-external-sharing-model-removed.ts index 440a1ffe586..afd7bac3c96 100644 --- a/packages/spec/src/conversions/entries/18/object-external-sharing-model-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-external-sharing-model-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-external-sharing-model-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-grid-default-filters-removed.ts b/packages/spec/src/conversions/entries/18/object-grid-default-filters-removed.ts index e959173f5d1..7ff403108d6 100644 --- a/packages/spec/src/conversions/entries/18/object-grid-default-filters-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-grid-default-filters-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-grid-default-filters-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-grid-default-sort-removed.ts b/packages/spec/src/conversions/entries/18/object-grid-default-sort-removed.ts index 9c05942a03a..550ff46096f 100644 --- a/packages/spec/src/conversions/entries/18/object-grid-default-sort-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-grid-default-sort-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-grid-default-sort-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-grid-resizable-columns-removed.ts b/packages/spec/src/conversions/entries/18/object-grid-resizable-columns-removed.ts index 02475d300df..02d2ddc49af 100644 --- a/packages/spec/src/conversions/entries/18/object-grid-resizable-columns-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-grid-resizable-columns-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-grid-resizable-columns-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-kanban-quick-add-removed.ts b/packages/spec/src/conversions/entries/18/object-kanban-quick-add-removed.ts index ac9584f21d8..0e36b13e4f5 100644 --- a/packages/spec/src/conversions/entries/18/object-kanban-quick-add-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-kanban-quick-add-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-kanban-quick-add-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-master-detail-form-detail-sort-field-removed.ts b/packages/spec/src/conversions/entries/18/object-master-detail-form-detail-sort-field-removed.ts index be42c2078b6..3181f121e89 100644 --- a/packages/spec/src/conversions/entries/18/object-master-detail-form-detail-sort-field-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-master-detail-form-detail-sort-field-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-master-detail-form-detail-sort-field-removed` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/object-tenancy-organization-field-removed.ts b/packages/spec/src/conversions/entries/18/object-tenancy-organization-field-removed.ts index 0a1dde65c0c..0d27156318e 100644 --- a/packages/spec/src/conversions/entries/18/object-tenancy-organization-field-removed.ts +++ b/packages/spec/src/conversions/entries/18/object-tenancy-organization-field-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `object-tenancy-organization-field-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-action-block-variant-destructive-to-danger.ts b/packages/spec/src/conversions/entries/18/page-action-block-variant-destructive-to-danger.ts index 5c603b45298..6af1f3311fa 100644 --- a/packages/spec/src/conversions/entries/18/page-action-block-variant-destructive-to-danger.ts +++ b/packages/spec/src/conversions/entries/18/page-action-block-variant-destructive-to-danger.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-action-block-variant-destructive-to-danger` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-action-row-navigation-executor-to-url.ts b/packages/spec/src/conversions/entries/18/page-action-row-navigation-executor-to-url.ts index 65a0e960685..203dfd15e8e 100644 --- a/packages/spec/src/conversions/entries/18/page-action-row-navigation-executor-to-url.ts +++ b/packages/spec/src/conversions/entries/18/page-action-row-navigation-executor-to-url.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-action-row-navigation-executor-to-url` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-action-row-patch-removed.ts b/packages/spec/src/conversions/entries/18/page-action-row-patch-removed.ts index a3027b2324a..b8a64fec233 100644 --- a/packages/spec/src/conversions/entries/18/page-action-row-patch-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-action-row-patch-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-action-row-patch-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-assigned-profiles-removed.ts b/packages/spec/src/conversions/entries/18/page-assigned-profiles-removed.ts index 078a2f4617c..bc3d8b20707 100644 --- a/packages/spec/src/conversions/entries/18/page-assigned-profiles-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-assigned-profiles-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-assigned-profiles-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-component-filter-record-to-rule-array.ts b/packages/spec/src/conversions/entries/18/page-component-filter-record-to-rule-array.ts index d9e2831f5db..abf12f5bf70 100644 --- a/packages/spec/src/conversions/entries/18/page-component-filter-record-to-rule-array.ts +++ b/packages/spec/src/conversions/entries/18/page-component-filter-record-to-rule-array.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-component-filter-record-to-rule-array` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-component-responsive-removed.ts b/packages/spec/src/conversions/entries/18/page-component-responsive-removed.ts index 3c088defad9..8bc78f0a9dc 100644 --- a/packages/spec/src/conversions/entries/18/page-component-responsive-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-component-responsive-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-component-responsive-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-header-breadcrumb-removed.ts b/packages/spec/src/conversions/entries/18/page-header-breadcrumb-removed.ts index b18adf4646c..cb490e9f384 100644 --- a/packages/spec/src/conversions/entries/18/page-header-breadcrumb-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-header-breadcrumb-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-header-breadcrumb-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-header-show-star-removed.ts b/packages/spec/src/conversions/entries/18/page-header-show-star-removed.ts index e500db9919d..b3748407e76 100644 --- a/packages/spec/src/conversions/entries/18/page-header-show-star-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-header-show-star-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-header-show-star-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-is-default-off-record-page-removed.ts b/packages/spec/src/conversions/entries/18/page-is-default-off-record-page-removed.ts index bf5d7be6b31..14c8ea47958 100644 --- a/packages/spec/src/conversions/entries/18/page-is-default-off-record-page-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-is-default-off-record-page-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-is-default-off-record-page-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-list-view-object-name-view-type-to-data-type.ts b/packages/spec/src/conversions/entries/18/page-list-view-object-name-view-type-to-data-type.ts index 0e344ab38ab..a8cb0ce29d8 100644 --- a/packages/spec/src/conversions/entries/18/page-list-view-object-name-view-type-to-data-type.ts +++ b/packages/spec/src/conversions/entries/18/page-list-view-object-name-view-type-to-data-type.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-list-view-object-name-view-type-to-data-type` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-main-region-width-removed.ts b/packages/spec/src/conversions/entries/18/page-main-region-width-removed.ts index 1e5270b86c8..0d39adbfd85 100644 --- a/packages/spec/src/conversions/entries/18/page-main-region-width-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-main-region-width-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-main-region-width-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-requires-non-compiled-kind-removed.ts b/packages/spec/src/conversions/entries/18/page-requires-non-compiled-kind-removed.ts index 4f4db1dcaf8..904d9f47d1c 100644 --- a/packages/spec/src/conversions/entries/18/page-requires-non-compiled-kind-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-requires-non-compiled-kind-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-requires-non-compiled-kind-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-slots-tabs-removed.ts b/packages/spec/src/conversions/entries/18/page-slots-tabs-removed.ts index 45b7355c7c7..90abf315bd5 100644 --- a/packages/spec/src/conversions/entries/18/page-slots-tabs-removed.ts +++ b/packages/spec/src/conversions/entries/18/page-slots-tabs-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-slots-tabs-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/page-template-full-width-to-default.ts b/packages/spec/src/conversions/entries/18/page-template-full-width-to-default.ts index 88f36279216..f913375c379 100644 --- a/packages/spec/src/conversions/entries/18/page-template-full-width-to-default.ts +++ b/packages/spec/src/conversions/entries/18/page-template-full-width-to-default.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `page-template-full-width-to-default` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/permission-admin-scope-binding-authoring-removed.ts b/packages/spec/src/conversions/entries/18/permission-admin-scope-binding-authoring-removed.ts index a5f4a903586..cd899053bc0 100644 --- a/packages/spec/src/conversions/entries/18/permission-admin-scope-binding-authoring-removed.ts +++ b/packages/spec/src/conversions/entries/18/permission-admin-scope-binding-authoring-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `permission-admin-scope-binding-authoring-removed` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/permission-allow-restore-purge-removed.ts b/packages/spec/src/conversions/entries/18/permission-allow-restore-purge-removed.ts index 132c687ea4c..f90a246c9ac 100644 --- a/packages/spec/src/conversions/entries/18/permission-allow-restore-purge-removed.ts +++ b/packages/spec/src/conversions/entries/18/permission-allow-restore-purge-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `permission-allow-restore-purge-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/permission-modify-all-allow-delete-false-to-true.ts b/packages/spec/src/conversions/entries/18/permission-modify-all-allow-delete-false-to-true.ts index 078f6ba9a87..41d6575c90a 100644 --- a/packages/spec/src/conversions/entries/18/permission-modify-all-allow-delete-false-to-true.ts +++ b/packages/spec/src/conversions/entries/18/permission-modify-all-allow-delete-false-to-true.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `permission-modify-all-allow-delete-false-to-true` -// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// conversion (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/permission-rls-tags-removed.ts b/packages/spec/src/conversions/entries/18/permission-rls-tags-removed.ts index fe80ef798d9..c4b6f618ac8 100644 --- a/packages/spec/src/conversions/entries/18/permission-rls-tags-removed.ts +++ b/packages/spec/src/conversions/entries/18/permission-rls-tags-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `permission-rls-tags-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/permission-set-managed-by-removed.ts b/packages/spec/src/conversions/entries/18/permission-set-managed-by-removed.ts index a613bd8f9a7..16ce98f32d1 100644 --- a/packages/spec/src/conversions/entries/18/permission-set-managed-by-removed.ts +++ b/packages/spec/src/conversions/entries/18/permission-set-managed-by-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `permission-set-managed-by-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/record-chatter-position-vocabulary.ts b/packages/spec/src/conversions/entries/18/record-chatter-position-vocabulary.ts index cdbe0ff0000..dcf7b403d6f 100644 --- a/packages/spec/src/conversions/entries/18/record-chatter-position-vocabulary.ts +++ b/packages/spec/src/conversions/entries/18/record-chatter-position-vocabulary.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `record-chatter-position-vocabulary` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/record-highlights-field-icon-removed.ts b/packages/spec/src/conversions/entries/18/record-highlights-field-icon-removed.ts index 78c1eede377..3588977e467 100644 --- a/packages/spec/src/conversions/entries/18/record-highlights-field-icon-removed.ts +++ b/packages/spec/src/conversions/entries/18/record-highlights-field-icon-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `record-highlights-field-icon-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/report-joined-chart-removed.ts b/packages/spec/src/conversions/entries/18/report-joined-chart-removed.ts index bc246b274f9..d425911f00d 100644 --- a/packages/spec/src/conversions/entries/18/report-joined-chart-removed.ts +++ b/packages/spec/src/conversions/entries/18/report-joined-chart-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `report-joined-chart-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/time-default-utc-suffix-dropped.ts b/packages/spec/src/conversions/entries/18/time-default-utc-suffix-dropped.ts index 3d6ddafc1b1..468bf075f4d 100644 --- a/packages/spec/src/conversions/entries/18/time-default-utc-suffix-dropped.ts +++ b/packages/spec/src/conversions/entries/18/time-default-utc-suffix-dropped.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `time-default-utc-suffix-dropped` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/translation-component-submit-label-removed.ts b/packages/spec/src/conversions/entries/18/translation-component-submit-label-removed.ts index 280d1d2dad4..a2e719398bd 100644 --- a/packages/spec/src/conversions/entries/18/translation-component-submit-label-removed.ts +++ b/packages/spec/src/conversions/entries/18/translation-component-submit-label-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `translation-component-submit-label-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/translation-locale-tag-canonicalized.ts b/packages/spec/src/conversions/entries/18/translation-locale-tag-canonicalized.ts index e53d5341663..6d51dac319d 100644 --- a/packages/spec/src/conversions/entries/18/translation-locale-tag-canonicalized.ts +++ b/packages/spec/src/conversions/entries/18/translation-locale-tag-canonicalized.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `translation-locale-tag-canonicalized` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/translation-locale-tag-case-folded.ts b/packages/spec/src/conversions/entries/18/translation-locale-tag-case-folded.ts index c4274e40325..33c91fe6e97 100644 --- a/packages/spec/src/conversions/entries/18/translation-locale-tag-case-folded.ts +++ b/packages/spec/src/conversions/entries/18/translation-locale-tag-case-folded.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `translation-locale-tag-case-folded` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/translation-per-app-settings-removed.ts b/packages/spec/src/conversions/entries/18/translation-per-app-settings-removed.ts index 35beed62bd0..f1add11eaec 100644 --- a/packages/spec/src/conversions/entries/18/translation-per-app-settings-removed.ts +++ b/packages/spec/src/conversions/entries/18/translation-per-app-settings-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `translation-per-app-settings-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/translation-widget-sub-caption-removed.ts b/packages/spec/src/conversions/entries/18/translation-widget-sub-caption-removed.ts index 36fff0a8a5f..5196cfbcdd0 100644 --- a/packages/spec/src/conversions/entries/18/translation-widget-sub-caption-removed.ts +++ b/packages/spec/src/conversions/entries/18/translation-widget-sub-caption-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `translation-widget-sub-caption-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/turso-config-encryption-key-removed.ts b/packages/spec/src/conversions/entries/18/turso-config-encryption-key-removed.ts index 5d184791ec8..0deb1f12d0f 100644 --- a/packages/spec/src/conversions/entries/18/turso-config-encryption-key-removed.ts +++ b/packages/spec/src/conversions/entries/18/turso-config-encryption-key-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `turso-config-encryption-key-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/turso-config-timeout-to-timeout-ms.ts b/packages/spec/src/conversions/entries/18/turso-config-timeout-to-timeout-ms.ts index ade418795be..c3797094372 100644 --- a/packages/spec/src/conversions/entries/18/turso-config-timeout-to-timeout-ms.ts +++ b/packages/spec/src/conversions/entries/18/turso-config-timeout-to-timeout-ms.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `turso-config-timeout-to-timeout-ms` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/view-item-owner-hidden-removed.ts b/packages/spec/src/conversions/entries/18/view-item-owner-hidden-removed.ts index 3aa2b28603b..f4da920823d 100644 --- a/packages/spec/src/conversions/entries/18/view-item-owner-hidden-removed.ts +++ b/packages/spec/src/conversions/entries/18/view-item-owner-hidden-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-item-owner-hidden-removed` conversion (`toMajor: -// 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/view-list-filterable-fields-removed.ts b/packages/spec/src/conversions/entries/18/view-list-filterable-fields-removed.ts index 0aab9077852..fd74c8728aa 100644 --- a/packages/spec/src/conversions/entries/18/view-list-filterable-fields-removed.ts +++ b/packages/spec/src/conversions/entries/18/view-list-filterable-fields-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-list-filterable-fields-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/view-list-tabs-removed.ts b/packages/spec/src/conversions/entries/18/view-list-tabs-removed.ts index 66310ea06e3..18fedb9b399 100644 --- a/packages/spec/src/conversions/entries/18/view-list-tabs-removed.ts +++ b/packages/spec/src/conversions/entries/18/view-list-tabs-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-list-tabs-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/view-overlay-owner-hidden-removed.ts b/packages/spec/src/conversions/entries/18/view-overlay-owner-hidden-removed.ts index 8cf8b2f1810..bd8eef3035d 100644 --- a/packages/spec/src/conversions/entries/18/view-overlay-owner-hidden-removed.ts +++ b/packages/spec/src/conversions/entries/18/view-overlay-owner-hidden-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-overlay-owner-hidden-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/view-page-mount-removed.ts b/packages/spec/src/conversions/entries/18/view-page-mount-removed.ts index 81d7c0a6b1b..a8c198d5b72 100644 --- a/packages/spec/src/conversions/entries/18/view-page-mount-removed.ts +++ b/packages/spec/src/conversions/entries/18/view-page-mount-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-page-mount-removed` conversion (`toMajor: 18`), -// moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/18/view-personal-declarations-removed.ts b/packages/spec/src/conversions/entries/18/view-personal-declarations-removed.ts index ef62314f229..c79f6d1ce01 100644 --- a/packages/spec/src/conversions/entries/18/view-personal-declarations-removed.ts +++ b/packages/spec/src/conversions/entries/18/view-personal-declarations-removed.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The `view-personal-declarations-removed` conversion -// (`toMajor: 18`), moved out of `conversions/registry.ts` whole by -// `scripts/codemod-split-conversions-registry.mjs` (ruling 6583399215: +// (`toMajor: 18`), moved out of `conversions/registry.ts` whole +// (split by #29993; ruling 6583399215: // per-entry files). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/entries/shared.ts b/packages/spec/src/conversions/entries/shared.ts index 9f756e1d50a..1bca4ea3070 100644 --- a/packages/spec/src/conversions/entries/shared.ts +++ b/packages/spec/src/conversions/entries/shared.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // [#29987 codemod] The top-level helpers of `conversions/registry.ts` that two -// or more conversions read, moved out whole by -// `scripts/codemod-split-conversions-registry.mjs` (lever (b) of ruling +// or more conversions read, moved out whole +// (split by #29993; lever (b) of ruling // 6591753301). // // A MOVE, not a redesign: each declaration below is its `registry.ts` text diff --git a/packages/spec/src/conversions/registry.ts b/packages/spec/src/conversions/registry.ts index e4ed37b5226..37f041c2953 100644 --- a/packages/spec/src/conversions/registry.ts +++ b/packages/spec/src/conversions/registry.ts @@ -18,7 +18,7 @@ import type { MetadataConversion } from './types.js'; // [#29987 codemod] Every conversion below moved to a module of its own under -// `./entries/` (`scripts/codemod-split-conversions-registry.mjs`). Imported in +// `./entries/` (split by #29993). Imported in // the order the definitions stood in this file, and listed in the tables below // exactly as before. import { flowNodeHttpRename } from './entries/11/flow-node-http-callout-rename.js'; diff --git a/scripts/check-adr-0087-registration.mjs b/scripts/check-adr-0087-registration.mjs index 4ae52449acb..8d4a4dd59ff 100644 --- a/scripts/check-adr-0087-registration.mjs +++ b/scripts/check-adr-0087-registration.mjs @@ -572,8 +572,8 @@ export const MIGRATION_LEDGER_ENTRY_DIRS = [ ]; /** - * Where `LEDGER_SOURCES[1]`'s conversions live since the #29987 codemod split - * (`scripts/codemod-split-conversions-registry.mjs`): one module per conversion + * Where `LEDGER_SOURCES[1]`'s conversions live since the #29987 codemod + * (split by #29993): one module per conversion * under this directory, plus the shared helpers. `registry.ts` itself still * exists and lists them, but no conversion's `id:` line is in it any more. A rev * that tracks no `.ts` file here is a rev from before the split, and the diff --git a/scripts/check-durability-degradation-log-level.mjs b/scripts/check-durability-degradation-log-level.mjs index 1580658b0a0..0b211c77411 100644 --- a/scripts/check-durability-degradation-log-level.mjs +++ b/scripts/check-durability-degradation-log-level.mjs @@ -3435,7 +3435,7 @@ function viaHostParameter(call) { * [#30147] The catch side's cross-file hop through the `sql-driver.ts` facade. * * `collectLoggedLevels` follows a catch's log helper to its body by NAME, in - * the same file. The sql-driver codemod (`scripts/codemod-split-sql-driver.mjs`, + * the same file. The sql-driver codemod (split by #30139; * #30105) moves a `SqlDriver` method's body into a stateless facet class in a * `sql-driver-*.ts` section module and leaves a one-call stub behind, so that * lookup met the move twice, and both times read a loud catch as silent: diff --git a/scripts/check-stack-collection-maps.mjs b/scripts/check-stack-collection-maps.mjs index f5b66c3f430..89f61ad572e 100644 --- a/scripts/check-stack-collection-maps.mjs +++ b/scripts/check-stack-collection-maps.mjs @@ -586,7 +586,7 @@ const SITES = [ // available alternative and is what #5870 did for `capabilities`; it is // what left the other four undiffed.) // - // #29986: the codemod split of `engine.ts` (`scripts/codemod-split-engine.mjs`) + // #29986: the codemod split of `engine.ts` (split by #30012) // moved its top-level declarations, this list among them, into the leaf // `engine-top-level.ts`; both seams still read the one copy there. id: 'METADATA_ARRAY_KEYS', diff --git a/scripts/codemod-split-conversions-registry.mjs b/scripts/codemod-split-conversions-registry.mjs deleted file mode 100644 index fbc32641daa..00000000000 --- a/scripts/codemod-split-conversions-registry.mjs +++ /dev/null @@ -1,1367 +0,0 @@ -#!/usr/bin/env node -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * codemod-split-conversions-registry — move every conversion entry of - * `packages/spec/src/conversions/registry.ts` into a module of its own, - * deterministically, and prove the move. - * - * node scripts/codemod-split-conversions-registry.mjs # plan: print the module table, write nothing - * node scripts/codemod-split-conversions-registry.mjs --write # apply the split, then verify it - * node scripts/codemod-split-conversions-registry.mjs --verify --base REF - * # re-prove a split on disk against registry.ts at REF - * node scripts/codemod-split-conversions-registry.mjs --arrays --base REF - * # load both registries and compare what they export - * node scripts/codemod-split-conversions-registry.mjs --dts BEFORE_DIST AFTER_DIST - * # the declaration-file bar on two built dists - * node scripts/codemod-split-conversions-registry.mjs --self-test - * node scripts/codemod-split-conversions-registry.mjs --help - * - * ## Why a script, and what it does - * - * Ruling A on the large-file programme (`6583399215`) splits `registry.ts` - * into per-entry files by a script, so the split is REGENERATED on the latest - * `main` at landing instead of rebased. The file is a table, not a class: a - * run of conversion definitions and the helpers they share, then the tables - * that list them (`MAJOR_18_CONVERSIONS`, `CONVERSIONS_BY_MAJOR`, - * `ALL_CONVERSIONS`). The shape, mechanically: - * - * - Each conversion (a top-level `const NAME: MetadataConversion = { id, toMajor, … }`) - * moves WHOLE, with the comments above it, to `entries//.ts`, - * which ends with one generated `export { NAME };` (the declaration's own - * text is not touched). - * - A top-level helper every one of whose readers moves moves too (pilot - * ruling `6591753301` lever (b): out-of-class top-level helpers move whole - * into leaf modules). A helper that only one conversion reaches moves into - * that conversion's module; a helper two or more reach moves into one - * shared leaf, `entries/shared.ts`. Every module keeps its statements in - * base order. - * - Everything else stays in `registry.ts`, byte for byte: the module - * docblock, `OrderedConversion`, `inApplicationOrder`, and the three tables - * with every `@__PURE__` marker. Its import declarations are regenerated: - * the base imports it still reads, then one import per conversion, in the - * order the definitions stood in the file (so a retirement's import line - * lands where its definition used to, and two in flight still spread over - * different gaps). - * - Leaves: `entries/shared.ts` imports neither `registry.ts` nor a - * conversion's module, and a conversion's module imports neither - * `registry.ts` nor another conversion's module. Nothing forms a cycle, so - * evaluation order is the import order of `registry.ts`, and every table - * reads modules already evaluated. - * - Nothing a consumer can reach changes: `registry.ts` exports the same two - * names (`CONVERSIONS_BY_MAJOR`, `ALL_CONVERSIONS`) at the same import - * path, both explicitly typed, and no generated `export` is re-exported by - * an entry point. - * - * ⛔ The moved text is not re-indented and not formatted: each statement is - * its base text exactly (`getFullText()`: its leading comments and the blank - * lines above it included), so byte-identity is equality of text. - * - * ## The proof (`--write` runs it on its own output; `--verify` re-runs it) - * - * 1. Byte-identity: every statement of every generated module, the - * generated imports and the generated `export { … }` aside, is the base - * statement of the same name, exactly, in base order; every statement that - * stayed is its base text exactly; every base statement is found exactly - * once; and putting the moved statements back between the ones that stayed - * (base's import declarations in place of the generated ones) rebuilds the - * base `registry.ts` byte-for-byte. - * 2. Bindings: every name a generated import brings in resolves to the file - * the base import of that name resolved to, with the same `type`-ness; no - * generated import is unused; the leaves import as stated above; each - * conversion's module sits at `entries//.ts` read off its own - * literal and exports exactly that conversion; `registry.ts` exports what - * base exported. - * 3. `--arrays`: both registries loaded under `tsx` (base = this tree's - * `packages/spec/src` with `conversions/` taken from REF) export the same - * `ALL_CONVERSIONS` ids in the same order, the same majors in - * `CONVERSIONS_BY_MAJOR` with the same ids in the same order, and each - * conversion is the same value (a digest over its JSON with every - * function's source text). - * 4. `--dts`: the declaration-file bar of ruling `6348891160` item 1 on - * every `*.d.ts` / `*.d.mts` / `*.d.cts` of two built `dist/` trees: the - * same file set; each file byte-identical, or byte-identical after the - * ruling's one normalisation (string-literal union member order); the - * same export list; and a positive control (one injected change of kind) - * the bar must catch. A diff the union normaliser does not close is ruling - * `6441032442` B's case: its second normalisation is a report reading kept - * out of `scripts/` (item 3 there), so this mode reports the fork. - * - * ## Determinism - * - * The input is the text of `registry.ts`. It is parsed in an in-memory - * project (no `node_modules`, no build output, no clock); every collection is - * emitted in source order or sorted, so two runs on one input write - * byte-identical trees (`output tree sha256`). - * - * ## Regenerating (the landing window) - * - * On the latest `main`, from the repository root: - * - * node scripts/codemod-split-conversions-registry.mjs --write - * - * On a branch that already carries a split, take `main`'s `registry.ts` first - * (`git checkout origin/main -- packages/spec/src/conversions/registry.ts`): - * `--write` deletes the generated modules it does not write again, and refuses - * a file under `entries/` this script did not write. - * - * Exit codes: 0 done · 1 a proof failed (stop: the generated split is never - * hand-edited to pass) · 2 the script could not run (an unexpected statement - * shape, a missing prerequisite, bad arguments) · 3 an input does not parse - * (`ts-parse.mjs`'s refusal). - */ - -import { createHash } from 'node:crypto'; -import { execFileSync } from 'node:child_process'; -import { - cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync, -} from 'node:fs'; -import { createRequire } from 'node:module'; -import { join, posix } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -import { isEntrypoint } from './invoked-as.mjs'; -import { parseSourceFile } from './ts-parse.mjs'; - -const ROOT = join(fileURLToPath(new URL('.', import.meta.url)), '..'); -const SPEC_REL = 'packages/spec'; -const CONV_REL = `${SPEC_REL}/src/conversions`; -const CONV_DIR = join(ROOT, CONV_REL); -const HOST_BASENAME = 'registry.ts'; -const HOST_PATH = join(CONV_DIR, HOST_BASENAME); -const ENTRIES = 'entries'; -const SHARED_MODULE = `${ENTRIES}/shared.ts`; -const CARD = '#29987'; - -/** The marker every generated file carries; `--verify` and `--write` key on it. */ -const MARK = `[${CARD} codemod]`; - -/** The type annotation that makes a top-level `const` a conversion entry. */ -const ENTRY_TYPE = 'MetadataConversion'; - -/** - * An entry id is a file name: letters, digits and hyphens, nothing a path - * could misread (two ids already carry a camelCase key, `visibleOn`). Two ids - * equal but for case would share a file on a case-insensitive file system, so - * `plan` refuses them. - */ -const ID_SHAPE = /^[A-Za-z0-9][A-Za-z0-9-]*$/; - -let tsMorph = null; - -/** ts-morph from the root manifest's devDependencies; a missing install is exit 2, never a stack trace. */ -async function loadTsMorph() { - if (tsMorph) return tsMorph; - const manifest = join(ROOT, 'package.json'); - try { - const resolved = createRequire(manifest).resolve('ts-morph'); - const mod = await import(pathToFileURL(resolved).href); - tsMorph = mod.default ?? mod; - return tsMorph; - } catch (error) { - console.error( - `✗ codemod-split-conversions-registry: PREREQUISITE NOT MET — ts-morph does not resolve from ${manifest} ` + - `(${error && error.code ? error.code : 'error'}). Run \`pnpm install\` in this worktree.`, - ); - process.exit(2); - } -} - -/** A reason the script cannot run at all (exit 2) — never a verdict on the split. */ -class CodemodRefusal extends Error {} - -function refuse(message) { - throw new CodemodRefusal(message); -} - -/** - * One in-memory project per parse: no file system, no lib, no build output. - * The text goes through `ts-parse.mjs`'s checked parse first, which refuses a - * source with parse errors (its exit 3); ts-morph then reads the same text. - */ -function parse(tm, fileName, text) { - parseSourceFile(fileName, text); - const project = new tm.Project({ - useInMemoryFileSystem: true, - compilerOptions: { target: tm.ts.ScriptTarget.ES2020, strict: true, noLib: true, allowJs: false }, - }); - project.getFileSystem().writeFileSync(fileName, text); - const sf = project.addSourceFileAtPath(fileName); - return { sf, checker: project.getTypeChecker().compilerObject }; -} - -const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0); -const sha256 = (text) => createHash('sha256').update(text).digest('hex'); - -/** Lines as `wc -l` counts them: newline characters. */ -function lineCount(text) { - return text.split('\n').length - 1; -} - -// ── Reading a file ─────────────────────────────────────────────────────────── - -/** - * Every import of a file: `{ node, spec, typeOnly, elements: [{ local, text, typeOnly }] }`. - * A default or namespace import has no name a moved statement could take one - * at a time, so it stops the script. - */ -function readImports(tm, sf, fileName) { - const out = []; - for (const st of sf.getStatements()) { - if (!tm.Node.isImportDeclaration(st)) continue; - if (st.getDefaultImport() || st.getNamespaceImport()) refuse(`${fileName}: \`${st.getText()}\` is a default or namespace import`); - const elements = st.getNamedImports().map((el) => ({ - local: (el.getAliasNode() ?? el.getNameNode()).getText(), - text: el.getText(), - typeOnly: st.isTypeOnly() || el.isTypeOnly(), - })); - if (elements.length === 0) refuse(`${fileName}: \`${st.getText()}\` imports for side effects only`); - out.push({ node: st, spec: st.getModuleSpecifierValue(), typeOnly: st.isTypeOnly(), elements }); - } - return out; -} - -/** The names a top-level statement declares, or null when it declares none (an import, an `export { … }`). */ -function declaredNames(tm, st, fileName) { - const { Node } = tm; - if (Node.isImportDeclaration(st) || Node.isExportDeclaration(st)) return null; - if (Node.isVariableStatement(st)) { - return st.getDeclarations().map((d) => { - if (!Node.isIdentifier(d.getNameNode())) refuse(`${fileName}: a destructuring declaration (\`${d.getText().slice(0, 60)}\`)`); - return d.getName(); - }); - } - if (Node.isFunctionDeclaration(st) || Node.isInterfaceDeclaration(st) || Node.isTypeAliasDeclaration(st) - || Node.isClassDeclaration(st) || Node.isEnumDeclaration(st)) { - const name = st.getName(); - if (!name) refuse(`${fileName}: an anonymous declaration`); - return [name]; - } - refuse(`${fileName}: a top-level ${st.getKindName()} (\`${st.getText().slice(0, 60)}\`) — only declarations and imports are expected`); - return null; -} - -/** - * The top-level statement `decl` DECLARES, or null: a function, interface, - * type alias, class or enum directly in the file, or a variable of a - * top-level variable statement. A property, parameter or local declared - * inside some top-level statement is not one (a property access `x.name` can - * resolve to an object literal's property in another statement). - */ -function topStatementOf(ts, decl) { - const sk = ts.SyntaxKind; - if (decl.parent && decl.parent.kind === sk.SourceFile) return decl; - if (decl.kind === sk.VariableDeclaration && decl.parent?.kind === sk.VariableDeclarationList - && decl.parent.parent?.kind === sk.VariableStatement && decl.parent.parent.parent?.kind === sk.SourceFile) return decl.parent.parent; - return null; -} - -/** - * The module-scope names `st` reads: Map name -> 'import' | 'local'. Resolved - * through the checker, so a local that shadows a module name is not a read of - * it, and a shorthand `{ name }` is. - */ -function moduleRefs(tm, parsed, st, imports) { - const ts = tm.ts; - const { sf, checker } = parsed; - const sfNode = sf.compilerNode; - const importLocals = new Set(imports.flatMap((d) => d.elements.map((e) => e.local))); - const own = new Set(declaredNames(tm, st, sf.getFilePath()) ?? []); - const refs = new Map(); - const visit = (node) => { - if (node.kind === ts.SyntaxKind.Identifier) { - const parent = node.parent; - let sym = parent && parent.kind === ts.SyntaxKind.ShorthandPropertyAssignment && parent.name === node - ? checker.getShorthandAssignmentValueSymbol(parent) - : checker.getSymbolAtLocation(node); - if (sym) { - for (const decl of sym.declarations ?? []) { - if (decl.kind === ts.SyntaxKind.ImportSpecifier) { - const name = decl.name.text; - if (importLocals.has(name)) refs.set(name, 'import'); - break; - } - const top = topStatementOf(ts, decl); - if (top && top.parent === sfNode && top !== st.compilerNode) { - const name = node.text; - if (!own.has(name)) refs.set(name, 'local'); - break; - } - } - } - } - ts.forEachChild(node, visit); - }; - ts.forEachChild(st.compilerNode, visit); - return refs; -} - -/** `{ id, toMajor }` read off a conversion literal, or a refusal naming what is missing. */ -function entryKey(tm, decl, fileName) { - const { Node } = tm; - const init = decl.getInitializer(); - if (!init || !Node.isObjectLiteralExpression(init)) refuse(`${fileName}: ${decl.getName()} is typed ${ENTRY_TYPE} but is not an object literal`); - const prop = (name) => { - const p = init.getProperty(name); - if (!p || !Node.isPropertyAssignment(p)) refuse(`${fileName}: ${decl.getName()} has no \`${name}:\` property`); - return p.getInitializerOrThrow(); - }; - const id = prop('id'); - const toMajor = prop('toMajor'); - if (!Node.isStringLiteral(id)) refuse(`${fileName}: ${decl.getName()}'s \`id\` is not a string literal`); - if (!Node.isNumericLiteral(toMajor)) refuse(`${fileName}: ${decl.getName()}'s \`toMajor\` is not a number literal`); - const key = { id: id.getLiteralValue(), toMajor: toMajor.getLiteralValue() }; - if (!ID_SHAPE.test(key.id)) refuse(`${fileName}: ${decl.getName()}'s id '${key.id}' is not letters, digits and hyphens (it names a file)`); - if (!Number.isInteger(key.toMajor) || key.toMajor < 1) refuse(`${fileName}: ${decl.getName()}'s toMajor ${key.toMajor} is not a major`); - return key; -} - -/** Is `st` a conversion entry? Returns its `{ name, id, toMajor }` or null. */ -function asEntry(tm, st, fileName) { - if (!tm.Node.isVariableStatement(st)) return null; - const decls = st.getDeclarations(); - if (decls.length !== 1 || decls[0].getTypeNode()?.getText() !== ENTRY_TYPE) return null; - return { name: decls[0].getName(), ...entryKey(tm, decls[0], fileName) }; -} - -/** Does the statement carry its own `export` keyword? (A name listed in an `export { … }` does not count.) */ -function isExported(tm, st) { - return tm.Node.isExportable(st) && st.hasExportKeyword(); -} - -/** - * Read a file into `{ parsed, imports, statements }`. Each statement row: - * `{ node, names, label, fullText, exported, refs, entry }`. - */ -function readFile(tm, fileName, text) { - const parsed = parse(tm, fileName, text); - const imports = readImports(tm, parsed.sf, fileName); - const statements = []; - for (const st of parsed.sf.getStatements()) { - const names = declaredNames(tm, st, fileName); - if (names === null) continue; - statements.push({ - node: st, - names, - label: names.join(', '), - fullText: st.getFullText(), - exported: isExported(tm, st), - refs: moduleRefs(tm, parsed, st, imports), - entry: asEntry(tm, st, fileName), - }); - } - return { parsed, imports, statements, text }; -} - -// ── The plan ───────────────────────────────────────────────────────────────── - -/** `entries/18/some-id.ts` for a conversion. */ -const entryModuleOf = (entry) => `${ENTRIES}/${entry.toMajor}/${entry.id}.ts`; -const jsSpecifier = (moduleRel) => moduleRel.replace(/\.ts$/, '.js'); - -/** - * What moves where. Returns `{ base, rows, modules, hostRows, sharedRows }`: - * `modules` is a Map of module path -> rows in base order (the shared leaf - * among them when anything is shared); every row carries `module` (null for - * a statement that stays). - */ -function plan(tm, text) { - const base = readFile(tm, HOST_BASENAME, text); - const rows = base.statements; - if (text.includes(MARK)) refuse(`${HOST_BASENAME} already carries ${MARK}: run the script on an unsplit file (re-run on the latest main, never on its own output)`); - const byNameRow = new Map(); - for (const r of rows) for (const n of r.names) { - if (byNameRow.has(n)) refuse(`${HOST_BASENAME}: ${n} is declared twice`); - byNameRow.set(n, r); - } - const entries = rows.filter((r) => r.entry); - if (entries.length === 0) refuse(`${HOST_BASENAME}: no \`const NAME: ${ENTRY_TYPE} = { … }\` entry found`); - const seenIds = new Map(); - for (const r of entries) { - if (r.exported) refuse(`${HOST_BASENAME}: the entry ${r.entry.name} is exported; an exported entry is a published name, not a table row`); - const prev = seenIds.get(r.entry.id.toLowerCase()); - if (prev) refuse(`${HOST_BASENAME}: ${prev} and ${r.entry.name} share the id '${r.entry.id}' (compared without case: it names a file)`); - seenIds.set(r.entry.id.toLowerCase(), r.entry.name); - } - - // Readers: who reads each row. - const readers = new Map(rows.map((r) => [r, new Set()])); - for (const r of rows) for (const [n, kind] of r.refs) if (kind === 'local') readers.get(byNameRow.get(n)).add(r); - - // A helper moves when it is not exported, something reads it, and every - // reader moves — to a fixed point. - const moving = new Set(entries); - for (let grew = true; grew;) { - grew = false; - for (const r of rows) { - if (moving.has(r) || r.exported) continue; - const rs = readers.get(r); - if (rs.size > 0 && [...rs].every((x) => moving.has(x))) { moving.add(r); grew = true; } - } - } - // A conversion reads no other conversion: each module is a leaf of its own. - for (const r of entries) { - for (const [n, kind] of r.refs) { - if (kind === 'local' && byNameRow.get(n).entry) refuse(`${HOST_BASENAME}: the entry ${r.entry.name} reads the entry ${n}`); - } - } - // Which conversions reach each moving helper (its readers, transitively). - const owners = new Map(); - const ownersOf = (r) => { - if (r.entry) return new Set([r]); - if (owners.has(r)) return owners.get(r); - owners.set(r, new Set()); - const set = new Set(); - for (const x of readers.get(r)) for (const o of ownersOf(x)) set.add(o); - owners.set(r, set); - return set; - }; - for (const r of rows) { - if (!moving.has(r)) { r.module = null; continue; } - if (r.entry) { r.module = entryModuleOf(r.entry); continue; } - const os = ownersOf(r); - if (os.size === 0) refuse(`${HOST_BASENAME}: ${r.label} moves but no entry reaches it`); - r.module = os.size === 1 ? entryModuleOf([...os][0].entry) : SHARED_MODULE; - } - // A shared helper never reads an entry's own helper (its readers are a - // superset), so the shared module stays a leaf; check it anyway. - for (const r of rows) { - if (r.module !== SHARED_MODULE) continue; - for (const [n, kind] of r.refs) { - const dep = kind === 'local' ? byNameRow.get(n) : null; - if (dep && dep.module !== SHARED_MODULE) refuse(`${HOST_BASENAME}: the shared helper ${r.label} reads ${n}, which is not shared`); - } - } - const modules = new Map(); - for (const r of rows) { - if (!r.module) continue; - if (!modules.has(r.module)) modules.set(r.module, []); - modules.get(r.module).push(r); - } - return { - base, rows, byNameRow, modules, - hostRows: rows.filter((r) => !r.module), - sharedRows: modules.get(SHARED_MODULE) ?? [], - entries, - }; -} - -// ── Generating ─────────────────────────────────────────────────────────────── - -/** A base specifier (relative to `conversions/`) as `moduleRel` must spell it. */ -function rebase(spec, moduleRel) { - if (!spec.startsWith('.')) return spec; - const target = posix.normalize(spec); - let rel = posix.relative(posix.dirname(moduleRel), target); - if (!rel.startsWith('.')) rel = `./${rel}`; - return rel; -} - -/** `import { a, type B } from 'x';`, on one line when it fits in 120 characters. */ -function importStatement(typeOnly, elementTexts, specifier) { - const head = typeOnly ? 'import type' : 'import'; - const one = `${head} { ${elementTexts.join(', ')} } from '${specifier}';`; - if (one.length <= 120) return one; - return `${head} {\n${elementTexts.map((t) => ` ${t},`).join('\n')}\n} from '${specifier}';`; -} - -/** `export { a, type B };` on one line when it fits, else one name a line. */ -function exportStatement(elementTexts) { - const one = `export { ${elementTexts.join(', ')} };`; - if (one.length <= 120) return one; - return `export {\n${elementTexts.map((t) => ` ${t},`).join('\n')}\n};`; -} - -/** The base imports a set of rows reads, as `moduleRel` spells them, in base order. */ -function baseImportLines(base, rowsRead, moduleRel) { - const used = new Set(); - for (const r of rowsRead) for (const [n, kind] of r.refs) if (kind === 'import') used.add(n); - const out = []; - for (const d of base.imports) { - const els = d.elements.filter((e) => used.has(e.local)); - if (els.length === 0) continue; - // The statement keeps its own `import type` spelling; an element keeps its own `type`. - out.push(importStatement(d.typeOnly, els.map((e) => e.text), rebase(d.spec, moduleRel))); - } - return out; -} - -/** `type X` for a shared interface or type alias, `X` otherwise. */ -function sharedSpelling(tm, planned, name) { - const r = planned.byNameRow.get(name); - const typeOnly = tm.Node.isInterfaceDeclaration(r.node) || tm.Node.isTypeAliasDeclaration(r.node); - return typeOnly ? `type ${name}` : name; -} - -/** The shared names a set of rows reads. */ -function sharedNamesRead(planned, rowsRead) { - const names = new Set(); - for (const r of rowsRead) { - for (const [n, kind] of r.refs) { - if (kind === 'local' && planned.byNameRow.get(n).module === SHARED_MODULE) names.add(n); - } - } - return [...names].sort(byName); -} - -/** `text` wrapped into `// ` comment lines no wider than `width`. */ -function wrapLineComment(words, width = 80) { - const out = []; - let line = '//'; - for (const w of words) { - if (line.length + 1 + w.length > width && line !== '//') { out.push(line); line = '//'; } - line += ` ${w}`; - } - if (line !== '//') out.push(line); - return out; -} - -const words = (s) => s.split(/\s+/).filter(Boolean); - -/** - * A module's header is `//` lines, not a `/** *\/` docblock: a docblock that - * leads a module's first statement can be carried into a bundled `.d.ts`, - * and none of these modules has a published declaration to carry it to. - */ -function moduleHeader(lines) { - return ['// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.', '', ...lines]; -} - -function entryModuleText(tm, planned, moduleRel, rows) { - const entry = rows.find((r) => r.entry).entry; - const helpers = rows.filter((r) => !r.entry).map((r) => `\`${r.label}\``); - const out = moduleHeader([ - ...wrapLineComment(words(`${MARK} The \`${entry.id}\` conversion (\`toMajor: ${entry.toMajor}\`), moved out of` - + ' `conversions/registry.ts` whole by `scripts/codemod-split-conversions-registry.mjs`' - + ' (ruling 6583399215: per-entry files).')), - '//', - ...wrapLineComment(words('A MOVE, not a redesign: each declaration below is its `registry.ts` text exactly, with the' - + ' comments above it, in the order it stood there' - + (helpers.length ? ` (${helpers.length === 1 ? 'the helper' : 'the helpers'} ${helpers.join(', ')}` - + ` ${helpers.length === 1 ? 'is' : 'are'} read by this conversion alone).` : '.') - + ' A LEAF: it imports neither `registry.ts` nor another conversion\'s module. `registry.ts` imports' - + ` \`${entry.name}\` and lists it where it stood.`)), - '', - ]); - out.push(...baseImportLines(planned.base, rows, moduleRel)); - const shared = sharedNamesRead(planned, rows); - if (shared.length > 0) { - out.push(importStatement(false, shared.map((n) => sharedSpelling(tm, planned, n)), rebase(`./${jsSpecifier(SHARED_MODULE)}`, moduleRel))); - } - let text = out.join('\n'); - for (const r of rows) text += r.fullText; - text += `\n\n${exportStatement([entry.name])}\n`; - return text; -} - -function sharedModuleText(tm, planned) { - const rows = planned.sharedRows; - const out = moduleHeader([ - ...wrapLineComment(words(`${MARK} The top-level helpers of \`conversions/registry.ts\` that two or more conversions` - + ' read, moved out whole by `scripts/codemod-split-conversions-registry.mjs` (lever (b) of ruling 6591753301).')), - '//', - ...wrapLineComment(words('A MOVE, not a redesign: each declaration below is its `registry.ts` text exactly, with the' - + ' comments above it, in the order it stood there. A LEAF: it imports neither `registry.ts` nor any' - + ' conversion\'s module, so it is evaluated before every conversion that reads it.')), - '', - ]); - out.push(...baseImportLines(planned.base, rows, SHARED_MODULE)); - let text = out.join('\n'); - for (const r of rows) text += r.fullText; - const readOutside = new Set(); - for (const [moduleRel, mrows] of planned.modules) { - if (moduleRel === SHARED_MODULE) continue; - for (const n of sharedNamesRead(planned, mrows)) readOutside.add(n); - } - const exported = [...readOutside].sort(byName).map((n) => sharedSpelling(tm, planned, n)); - text += `\n\n// ${MARK} Declared above without \`export\`, and read by the conversions' modules.\n${exportStatement(exported)}\n`; - return text; -} - -/** - * The new `registry.ts`: base with every moved statement taken out - * (`getFullStart()` to `getEnd()`, so the statement after it keeps its own - * leading comments) and the import declarations regenerated. - */ -function hostText(planned) { - const { base, hostRows, entries } = planned; - const text = base.text; - const lines = baseImportLines(base, hostRows, HOST_BASENAME); - lines.push(''); - lines.push(...wrapLineComment(words(`${MARK} Every conversion below moved to a module of its own under \`./${ENTRIES}/\`` - + ' (`scripts/codemod-split-conversions-registry.mjs`). Imported in the order the definitions stood in this file,' - + ' and listed in the tables below exactly as before.'))); - for (const r of entries) lines.push(`import { ${r.entry.name} } from './${jsSpecifier(entryModuleOf(r.entry))}';`); - const first = base.imports[0].node; - const last = base.imports.at(-1).node; - const edits = [{ start: first.getStart(), end: last.getEnd(), text: lines.join('\n') }]; - for (const r of planned.rows) if (r.module) edits.push({ start: r.node.getFullStart(), end: r.node.getEnd(), text: '' }); - edits.sort((a, b) => b.start - a.start); - let out = text; - let floor = Infinity; - for (const e of edits) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - return out; -} - -/** Apply a plan: `{ host, modules }` — the new `registry.ts` and a Map of module path -> text. Pure. */ -function generate(tm, planned) { - if (planned.base.imports.length === 0) refuse(`${HOST_BASENAME} has no import declaration to regenerate`); - const modules = new Map(); - for (const [moduleRel, rows] of [...planned.modules].sort(([a], [b]) => byName(a, b))) { - modules.set(moduleRel, moduleRel === SHARED_MODULE ? sharedModuleText(tm, planned) : entryModuleText(tm, planned, moduleRel, rows)); - } - return { host: hostText(planned), modules }; -} - -// ── Proof 1 + 2: byte-identity and bindings ────────────────────────────────── - -/** The file a relative specifier of a file at `fromRel` (relative to `conversions/`) names. */ -function targetOf(spec, fromRel) { - if (!spec.startsWith('.')) return spec; - return posix.normalize(posix.join(posix.dirname(fromRel), spec)); -} - -/** - * Prove a split against its base from the texts alone (it shares no state with - * `plan` / `generate`). Returns `{ failures, readings }`; no failure = proved. - */ -function verify(tm, baseText, headHost, moduleTexts) { - const failures = []; - const fail = (m) => failures.push(m); - const base = readFile(tm, HOST_BASENAME, baseText); - const head = readFile(tm, HOST_BASENAME, headHost); - const baseByName = new Map(); - for (const r of base.statements) baseByName.set(r.label, r); - const baseImportOf = new Map(); - for (const d of base.imports) for (const e of d.elements) baseImportOf.set(e.local, { target: targetOf(d.spec, HOST_BASENAME), typeOnly: e.typeOnly }); - - if (!headHost.includes(MARK)) fail(`${HOST_BASENAME} carries no ${MARK}: it is not a generated split`); - - // Every module, read the same way. - const files = new Map([[HOST_BASENAME, head]]); - for (const [rel, text] of [...moduleTexts].sort(([a], [b]) => byName(a, b))) { - if (!rel.startsWith(`${ENTRIES}/`)) fail(`${rel}: a generated module outside ${ENTRIES}/`); - if (!text.includes(MARK)) fail(`${rel}: carries no ${MARK}`); - files.set(rel, readFile(tm, rel, text)); - } - - // 1. Each statement is its base text, found exactly once, in base order per file. - const placed = new Map(); - let bytesCompared = 0; - for (const [rel, f] of files) { - let lastIndex = -1; - for (const r of f.statements) { - const b = baseByName.get(r.label); - if (!b) { fail(`${rel}: ${r.label} is not a statement of the base ${HOST_BASENAME}`); continue; } - if (r.fullText !== b.fullText) fail(`${rel}: ${r.label} differs from its base text (sha256 ${sha256(r.fullText).slice(0, 12)} vs ${sha256(b.fullText).slice(0, 12)})`); - else bytesCompared += Buffer.byteLength(r.fullText); - if (placed.has(r.label)) fail(`${r.label} is declared in both ${placed.get(r.label)} and ${rel}`); - placed.set(r.label, rel); - const at = base.statements.indexOf(b); - if (at < lastIndex) fail(`${rel}: ${r.label} is out of base order`); - lastIndex = at; - } - } - for (const b of base.statements) if (!placed.has(b.label)) fail(`${b.label} (base) is in no file of the split`); - - // 1b. Undo: base's imports in place of the generated ones, every moved statement back between the ones that stayed. - let rebuilt = null; - if (head.imports.length > 0 && base.imports.length > 0 && failures.length === 0) { - const fullTextOf = (label) => { - const f = files.get(placed.get(label)); - return f.statements.find((r) => r.label === label).fullText; - }; - const headFirst = head.imports[0].node; - const lastHeadStmt = head.parsed.sf.getStatements().at(-1); - rebuilt = headHost.slice(0, headFirst.getStart()) - + baseText.slice(base.imports[0].node.getStart(), base.imports.at(-1).node.getEnd()) - + base.statements.map((b) => fullTextOf(b.label)).join('') - + headHost.slice(lastHeadStmt.getEnd()); - if (rebuilt !== baseText) { - let i = 0; - while (i < rebuilt.length && rebuilt[i] === baseText[i]) i += 1; - fail(`undoing the split does NOT rebuild the base ${HOST_BASENAME}: first difference at offset ${i}`); - } - } - - // 2. Bindings. - const entryModules = new Map(); - for (const [rel, f] of files) { - if (rel === HOST_BASENAME) continue; - const entries = f.statements.filter((r) => r.entry); - if (rel === SHARED_MODULE) { - if (entries.length > 0) fail(`${rel}: holds the entry ${entries[0].entry.name}`); - } else if (entries.length !== 1) { - fail(`${rel}: holds ${entries.length} entries, not 1`); - } else { - const e = entries[0].entry; - if (rel !== entryModuleOf(e)) fail(`${rel}: holds ${e.name} (id '${e.id}', toMajor ${e.toMajor}), which belongs at ${entryModuleOf(e)}`); - entryModules.set(rel, e); - } - const exportDecls = f.parsed.sf.getStatements().filter((s) => tm.Node.isExportDeclaration(s)); - const last = f.parsed.sf.getStatements().at(-1); - if (exportDecls.length !== 1 || exportDecls[0] !== last || last.getModuleSpecifier()) { - fail(`${rel}: does not end with exactly one generated \`export { … }\``); - } else if (rel !== SHARED_MODULE && entries.length === 1) { - const names = last.getNamedExports().map((x) => x.getName()); - if (names.join() !== entries[0].entry.name) fail(`${rel}: exports ${names.join(', ')}, not ${entries[0].entry.name}`); - } - for (const r of f.statements) if (r.exported) fail(`${rel}: ${r.label} carries its own \`export\` (the generated list exports)`); - } - const sharedExports = new Set(); - if (files.has(SHARED_MODULE)) { - const last = files.get(SHARED_MODULE).parsed.sf.getStatements().at(-1); - if (tm.Node.isExportDeclaration(last)) for (const x of last.getNamedExports()) sharedExports.add(x.getName()); - } - const sharedDeclared = new Set((files.get(SHARED_MODULE)?.statements ?? []).flatMap((r) => r.names)); - let importsChecked = 0; - for (const [rel, f] of files) { - const usedImports = new Set(); - for (const r of f.statements) for (const [n, kind] of r.refs) if (kind === 'import') usedImports.add(n); - const hostUsesEntries = new Set(); - if (rel === HOST_BASENAME) for (const r of f.statements) for (const [n] of r.refs) hostUsesEntries.add(n); - for (const d of f.imports) { - const target = targetOf(d.spec, rel); - for (const e of d.elements) { - importsChecked += 1; - const fromModule = [...files.keys()].find((k) => k !== HOST_BASENAME && jsSpecifier(k) === target); - if (fromModule) { - if (rel !== HOST_BASENAME && fromModule !== SHARED_MODULE) fail(`${rel}: imports ${e.local} from another conversion's module ${fromModule}`); - if (fromModule === SHARED_MODULE && !sharedExports.has(e.local)) fail(`${rel}: imports ${e.local} from ${SHARED_MODULE}, which does not export it`); - if (rel === HOST_BASENAME && fromModule === SHARED_MODULE) fail(`${rel}: imports ${e.local} from the shared leaf`); - if (rel === HOST_BASENAME && entryModules.get(fromModule)?.name !== e.local) fail(`${rel}: imports ${e.local} from ${fromModule}, which holds ${entryModules.get(fromModule)?.name ?? 'no entry'}`); - if (rel === SHARED_MODULE) fail(`${rel}: the shared leaf imports a generated module (${fromModule})`); - if (rel !== HOST_BASENAME && !usedImports.has(e.local)) fail(`${rel}: imports ${e.local}, which nothing in it reads`); - continue; - } - if (target === jsSpecifier(HOST_BASENAME)) { fail(`${rel}: imports ${e.local} from ${HOST_BASENAME} (a leaf never imports the host)`); continue; } - const b = baseImportOf.get(e.local); - if (!b) { fail(`${rel}: imports ${e.local}, which the base did not import`); continue; } - if (b.target !== target) fail(`${rel}: imports ${e.local} from ${target}, the base from ${b.target}`); - if (b.typeOnly !== e.typeOnly) fail(`${rel}: imports ${e.local} ${e.typeOnly ? 'as a type' : 'as a value'}, the base ${b.typeOnly ? 'as a type' : 'as a value'}`); - if (!usedImports.has(e.local)) fail(`${rel}: imports ${e.local}, which nothing in it reads`); - } - } - // Every module-scope name a statement reads is declared in the file or imported by it. - const declared = new Set(f.statements.flatMap((r) => r.names)); - const imported = new Set(f.imports.flatMap((d) => d.elements.map((e) => e.local))); - for (const r of f.statements) { - for (const n of baseByName.get(r.label)?.refs.keys() ?? []) { - if (!declared.has(n) && !imported.has(n)) fail(`${rel}: ${r.label} reads ${n}, which the file neither declares nor imports`); - } - } - if (rel === SHARED_MODULE) for (const n of sharedExports) if (!sharedDeclared.has(n)) fail(`${rel}: exports ${n}, which it does not declare`); - } - const baseExports = base.statements.filter((r) => r.exported).flatMap((r) => r.names).sort(byName); - const headExports = head.statements.filter((r) => r.exported).flatMap((r) => r.names).sort(byName); - if (baseExports.join() !== headExports.join()) fail(`${HOST_BASENAME} exports ${headExports.join(', ')}; the base exported ${baseExports.join(', ')}`); - const headEntryImports = new Set(head.imports.flatMap((d) => d.elements.map((e) => e.local)).filter((n) => [...entryModules.values()].some((e) => e.name === n))); - const baseEntries = base.statements.filter((r) => r.entry); - for (const r of baseEntries) if (!headEntryImports.has(r.entry.name)) fail(`${HOST_BASENAME} does not import the entry ${r.entry.name}`); - - const moved = base.statements.filter((b) => placed.get(b.label) && placed.get(b.label) !== HOST_BASENAME); - return { - failures, - readings: { - entries: baseEntries.length, - entriesMoved: moved.filter((b) => b.entry).length, - helpersMoved: moved.filter((b) => !b.entry).length, - helpersShared: files.get(SHARED_MODULE)?.statements.length ?? 0, - stayed: head.statements.length, - modules: moduleTexts.size, - statementsCompared: placed.size, - bytesCompared, - importsChecked, - linesBefore: lineCount(baseText), - linesAfter: lineCount(headHost), - rebuilt: rebuilt === baseText, - baseSha256: sha256(baseText), - }, - }; -} - -function printVerify(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - const r = v.readings; - console.log(`byte-identity: ${r.statementsCompared} statements compared (${r.bytesCompared} bytes), ` + - `${r.entriesMoved}/${r.entries} entries and ${r.helpersMoved} helpers moved (${r.helpersShared} into ${SHARED_MODULE}), ` + - `${r.stayed} stayed; ${r.modules} modules; ${r.importsChecked} import bindings checked; ` + - `${HOST_BASENAME} ${r.linesBefore} -> ${r.linesAfter} lines; undoing the split ${r.rebuilt ? 'does' : 'does NOT'} rebuild the base byte-for-byte`); -} - -// ── Proof 3: the exported tables, loaded ───────────────────────────────────── - -/** - * The probe `tsx` runs on a registry: every table it exports, as ids, plus a - * digest of each conversion's value (its JSON with every function as its - * source text, so `apply` and any fixture callback are compared too). - */ -const ARRAYS_PROBE = ` -import { createHash } from 'node:crypto'; -import { pathToFileURL } from 'node:url'; -const m = await import(pathToFileURL(process.argv[2]).href); -const source = (v) => { - const text = v.toString(); - if (/\\(0,\\s*import_[\\w$]+\\./.test(text)) throw new Error('arrays probe: a function was loaded as CommonJS (its imports are rewritten), so its source is not comparable'); - return 'fn:' + text; -}; -const digest = (c) => createHash('sha256').update(JSON.stringify(c, (k, v) => (typeof v === 'function' ? source(v) : v))).digest('hex'); -const byMajor = {}; -for (const k of Object.keys(m.CONVERSIONS_BY_MAJOR)) byMajor[k] = m.CONVERSIONS_BY_MAJOR[k].map((c) => c.id); -process.stdout.write(JSON.stringify({ - exports: Object.keys(m).sort(), - all: m.ALL_CONVERSIONS.map((c) => c.id), - byMajor, - digests: Object.fromEntries(m.ALL_CONVERSIONS.map((c) => [c.id, digest(c)])), -})); -`; - -function loadTables(registryPath, probePath) { - const tsx = join(ROOT, 'node_modules', '.bin', 'tsx'); - if (!existsSync(tsx)) refuse(`--arrays needs tsx at ${tsx} (run pnpm install)`); - return JSON.parse(execFileSync(tsx, [probePath, registryPath], { cwd: join(ROOT, SPEC_REL), encoding: 'utf8', maxBuffer: 1 << 28 })); -} - -function compareTables(before, after) { - const failures = []; - if (before.exports.join() !== after.exports.join()) failures.push(`exports differ: ${before.exports.join(', ')} vs ${after.exports.join(', ')}`); - if (JSON.stringify(before.all) !== JSON.stringify(after.all)) failures.push('ALL_CONVERSIONS ids differ (membership or order)'); - const majors = (t) => Object.keys(t.byMajor).join(); - if (majors(before) !== majors(after)) failures.push(`CONVERSIONS_BY_MAJOR majors differ: ${majors(before)} vs ${majors(after)}`); - for (const k of Object.keys(before.byMajor)) { - if (JSON.stringify(before.byMajor[k]) !== JSON.stringify(after.byMajor[k] ?? null)) failures.push(`CONVERSIONS_BY_MAJOR[${k}] differs (membership or order)`); - } - for (const [id, d] of Object.entries(before.digests)) if (after.digests[id] !== d) failures.push(`${id}: its value differs`); - return failures; -} - -function arraysProof(ref) { - const scratch = mkdtempSync(join(ROOT, SPEC_REL, '.codemod-arrays-')); - try { - const probe = join(scratch, 'probe.mts'); - writeFileSync(probe, ARRAYS_PROBE); - // Both trees load as ES modules. Under the spec package's CommonJS default the loader rewrites every - // imported call to `(0, import_x.name)(…)`, so a moved entry's function source would differ only by the - // loader's spelling of its import (measured on #29987: 93 of 112 digests). The probe refuses that spelling. - writeFileSync(join(scratch, 'package.json'), '{"type":"module"}\n'); - // Base: this tree's src, with conversions/ exactly as REF has it. - const baseSrc = join(scratch, 'base-src'); - cpSync(join(ROOT, SPEC_REL, 'src'), baseSrc, { recursive: true }); - rmSync(join(baseSrc, 'conversions'), { recursive: true, force: true }); - const tar = join(scratch, 'conversions.tar'); - execFileSync('git', ['archive', '--format=tar', '-o', tar, ref, `${CONV_REL}/`], { cwd: ROOT }); - const unpack = join(scratch, 'unpack'); - mkdirSync(unpack); - execFileSync('tar', ['-xf', tar, '-C', unpack]); - cpSync(join(unpack, CONV_REL), join(baseSrc, 'conversions'), { recursive: true }); - const before = loadTables(join(baseSrc, 'conversions', HOST_BASENAME), probe); - const headSrc = join(scratch, 'head-src'); - cpSync(join(ROOT, SPEC_REL, 'src'), headSrc, { recursive: true }); - const after = loadTables(join(headSrc, 'conversions', HOST_BASENAME), probe); - const failures = compareTables(before, after); - return { - failures, - readings: { - exports: after.exports, - all: after.all.length, - allSha256: sha256(JSON.stringify(after.all)), - byMajor: Object.fromEntries(Object.entries(after.byMajor).map(([k, ids]) => [k, ids.length])), - digestsEqual: Object.keys(before.digests).filter((id) => after.digests[id] === before.digests[id]).length, - }, - }; - } finally { - rmSync(scratch, { recursive: true, force: true }); - } -} - -// ── Proof 4: the declaration-file bar (ruling 6348891160 item 1) ───────────── - -/** The ruling's one normalisation, verbatim: sort the members of each run of string-literal union members in place. */ -function normaliseUnionOrder(text) { - return text.replace(/"[^"\n]*"(?:\s*\|\s*"[^"\n]*")+/g, (r) => r.split(/\s*\|\s*/).sort().join(' | ')); -} - -/** Export names of a bundled `.d.ts`: every `export { … }` list, plus `export Name`. */ -function dtsExportNames(text) { - const names = new Set(); - for (const m of text.matchAll(/^export\s*(?:type\s*)?\{([^}]*)\}/gm)) { - for (const part of m[1].split(',')) { - const t = part.trim().replace(/^type\s+/, ''); - if (!t) continue; - const as = /\bas\s+([\w$]+)$/.exec(t); - names.add(as ? as[1] : t); - } - } - for (const m of text.matchAll(/^export\s+(?:declare\s+)?(?:abstract\s+)?(?:class|interface|type|function|const|let|var|enum|namespace)\s+([\w$]+)/gm)) names.add(m[1]); - return [...names].sort(); -} - -/** - * One positive control on a declaration file: the first `private` member made - * public, else the first `readonly` dropped, else the first `: string` made - * `: number`. Returns null when none of the three occurs. - */ -function injectChange(text) { - const priv = text.search(/^ {4}private /m); - if (priv >= 0) return { kind: 'private member made public', text: text.slice(0, priv) + ' ' + text.slice(priv + ' private '.length) }; - const ro = text.search(/\breadonly /); - if (ro >= 0) return { kind: 'readonly dropped', text: text.slice(0, ro) + text.slice(ro + 'readonly '.length) }; - const str = text.indexOf(': string'); - if (str >= 0) return { kind: 'a string member retyped number', text: `${text.slice(0, str)}: number${text.slice(str + ': string'.length)}` }; - return null; -} - -/** The bar on one declaration file pair. Returns `{ failures, reading }`. */ -function dtsBarFor(file, before, after) { - const failures = []; - const raw = before === after; - const nb = normaliseUnionOrder(before); - const na = normaliseUnionOrder(after); - if (!raw && nb !== na) failures.push(`${file}: differs other than by union member order — ruling 6441032442 B's second normalisation is the report reading for this (a fork to report, never a widened normaliser here)`); - const eb = dtsExportNames(before); - const ea = dtsExportNames(after); - if (JSON.stringify(eb) !== JSON.stringify(ea)) failures.push(`${file}: the export list differs (${eb.length} at base, ${ea.length} at head)`); - return { - failures, - reading: { file, raw: raw ? 'identical' : 'differs', rawSha256: sha256(after).slice(0, 16), normalisedEqual: nb === na, exports: ea.length }, - }; -} - -function listDts(dir) { - const out = []; - const walk = (d, rel) => { - for (const name of readdirSync(d).sort()) { - const p = join(d, name); - const r = rel ? `${rel}/${name}` : name; - if (statSync(p).isDirectory()) walk(p, r); - else if (/\.d\.[cm]?ts$/.test(name)) out.push(r); - } - }; - walk(dir, ''); - return out; -} - -function dtsBar(beforeDir, afterDir) { - const failures = []; - const readings = []; - const fb = listDts(beforeDir); - const fa = listDts(afterDir); - if (fb.join('\n') !== fa.join('\n')) { - const onlyB = fb.filter((f) => !fa.includes(f)); - const onlyA = fa.filter((f) => !fb.includes(f)); - failures.push(`the declaration file sets differ: only at base ${onlyB.length} (${onlyB.slice(0, 5).join(', ')}), only at head ${onlyA.length} (${onlyA.slice(0, 5).join(', ')})`); - } - let control = null; - for (const file of fb.filter((f) => fa.includes(f))) { - const before = readFileSync(join(beforeDir, file), 'utf8'); - const after = readFileSync(join(afterDir, file), 'utf8'); - const r = dtsBarFor(file, before, after); - failures.push(...r.failures); - readings.push(r.reading); - if (!control) { - const injected = injectChange(after); - if (injected) { - const caught = dtsBarFor(file, before, injected.text).failures.length > 0; - control = { file, kind: injected.kind, caught }; - } - } - } - if (!control) failures.push('no declaration file admits the positive control (INCONCLUSIVE)'); - else if (!control.caught) failures.push(`the positive control (${control.kind} in ${control.file}) passes the bar — the bar hides a change (INCONCLUSIVE)`); - return { failures, readings, control, files: fa.length }; -} - -// ── Disk ───────────────────────────────────────────────────────────────────── - -function gitShow(ref, path) { - return execFileSync('git', ['show', `${ref}:${path}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28 }); -} - -/** Every `.ts` file under `entries/`, as Map rel -> text. */ -function generatedModulesOnDisk() { - const out = new Map(); - const dir = join(CONV_DIR, ENTRIES); - if (!existsSync(dir)) return out; - const walk = (d, rel) => { - for (const name of readdirSync(d).sort()) { - const p = join(d, name); - const r = `${rel}/${name}`; - if (statSync(p).isDirectory()) walk(p, r); - else if (name.endsWith('.ts')) out.set(r, readFileSync(p, 'utf8')); - } - }; - walk(dir, ENTRIES); - return out; -} - -function treeHash(files) { - const h = createHash('sha256'); - for (const [name, text] of [...files].sort(([a], [b]) => byName(a, b))) h.update(`${name}\0${sha256(text)}\n`); - return h.digest('hex'); -} - -function planReport(planned) { - const out = []; - const majors = new Map(); - for (const r of planned.entries) majors.set(r.entry.toMajor, (majors.get(r.entry.toMajor) ?? 0) + 1); - out.push(`entries: ${planned.entries.length} conversions -> ${ENTRIES}//.ts (${[...majors].sort((a, b) => a[0] - b[0]).map(([m, n]) => `${m}: ${n}`).join(', ')})`); - const privateHelpers = planned.rows.filter((r) => r.module && !r.entry && r.module !== SHARED_MODULE); - out.push(`helpers read by one conversion (moved into its module): ${privateHelpers.length}`); - for (const r of privateHelpers) out.push(` ${r.label} -> ${r.module}`); - out.push(`helpers read by two or more conversions (moved into ${SHARED_MODULE}): ${planned.sharedRows.length}`); - out.push(` ${planned.sharedRows.map((r) => r.label).join(', ')}`); - out.push(`stay in ${HOST_BASENAME}: ${planned.hostRows.map((r) => r.label).join(', ')}`); - return out.join('\n'); -} - -// ── Entry ──────────────────────────────────────────────────────────────────── - -const USAGE = [ - 'usage: node scripts/codemod-split-conversions-registry.mjs [--write] plan (or apply) the split of an UNSPLIT registry.ts', - ' node scripts/codemod-split-conversions-registry.mjs --verify --base REF re-prove a split on disk against registry.ts at REF', - ' node scripts/codemod-split-conversions-registry.mjs --arrays --base REF load both registries and compare their tables', - ' node scripts/codemod-split-conversions-registry.mjs --dts BEFORE_DIST AFTER_DIST the declaration-file bar on two built dists', - ' node scripts/codemod-split-conversions-registry.mjs --self-test', - ' node scripts/codemod-split-conversions-registry.mjs --help', -].join('\n'); - -function baseRef(argv) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--verify and --arrays need --base REF'); - return ref; -} - -async function main(argv) { - if (argv.includes('--help') || argv.includes('-h')) { - console.log(USAGE); - return 0; - } - if (argv.includes('--self-test')) { - await selfTest(); - if (process.exitCode === 1) return 1; - if (!selfTestReachedVerdict) { - console.error('\n✗ codemod-split-conversions-registry self-test: selfTest() returned without reaching its verdict,\n' + - 'so no success line was printed. Exiting 0 here would report a self-test that never\n' + - 'finished as a self-test that passed.'); - return 1; - } - return 0; - } - if (argv.includes('--dts')) { - const i = argv.indexOf('--dts'); - const [before, after] = [argv[i + 1], argv[i + 2]]; - if (!before || !after) refuse('--dts needs BEFORE_DIST AFTER_DIST'); - const { failures, readings, control, files } = dtsBar(before, after); - const differing = readings.filter((r) => r.raw !== 'identical'); - console.log(`declaration files: ${files}; raw-identical ${readings.length - differing.length}; differing ${differing.length}`); - for (const r of differing) console.log(JSON.stringify(r)); - if (control) console.log(`positive control: ${control.kind} in ${control.file} — ${control.caught ? 'caught' : 'NOT caught'}`); - for (const f of failures) console.error(` ✗ ${f}`); - console.log(failures.length === 0 ? '✓ declaration-file bar: PASS' : `✗ declaration-file bar: FAIL (${failures.length})`); - return failures.length === 0 ? 0 : 1; - } - if (argv.includes('--arrays')) { - const { failures, readings } = arraysProof(baseRef(argv)); - console.log(`tables: ${JSON.stringify(readings)}`); - for (const f of failures) console.error(` ✗ ${f}`); - console.log(failures.length === 0 ? '✓ tables: base = head' : `✗ tables: ${failures.length} difference(s)`); - return failures.length === 0 ? 0 : 1; - } - const tm = await loadTsMorph(); - if (argv.includes('--verify')) { - const ref = baseRef(argv); - const v = verify(tm, gitShow(ref, `${CONV_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), generatedModulesOnDisk()); - printVerify(v); - return v.failures.length === 0 ? 0 : 1; - } - const input = readFileSync(HOST_PATH, 'utf8'); - const planned = plan(tm, input); - console.log(planReport(planned)); - const out = generate(tm, planned); - const files = new Map([[HOST_BASENAME, out.host], ...out.modules]); - console.log(`output tree sha256: ${treeHash(files)} (input sha256 ${sha256(input)})`); - const v = verify(tm, input, out.host, out.modules); - printVerify(v); - if (v.failures.length > 0) { - console.error('✗ the generated split fails its proof: nothing written. Report the fork; never hand-edit the split.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - const onDisk = generatedModulesOnDisk(); - for (const [rel, text] of onDisk) if (!text.includes(MARK)) refuse(`${CONV_REL}/${rel} exists and was not written by this script`); - for (const [rel] of onDisk) if (!out.modules.has(rel)) unlinkSync(join(CONV_DIR, rel)); - writeFileSync(HOST_PATH, out.host); - for (const [rel, text] of out.modules) { - mkdirSync(join(CONV_DIR, posix.dirname(rel)), { recursive: true }); - writeFileSync(join(CONV_DIR, rel), text); - } - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} module(s) under ${CONV_REL}/${ENTRIES}`); - return 0; -} - -// ── Self-test ──────────────────────────────────────────────────────────────── -// -// The proofs above are this script's whole value, and a proof that cannot fail -// proves nothing, so the self-test feeds each one an input it must REFUSE. The -// roster pins battery NAMES with a floor each, the roster's own size is pinned, -// and the verdict sets a flag the dispatch reads (AGENTS.md, "Writing a -// `--self-test`"), so a battery that stops running, or a `return` above the -// verdict, cannot read as a pass. - -let selfTestReachedVerdict = false; - -const SELF_TEST_BATTERIES = Object.freeze({ - 'plan': 9, - 'generation': 6, - 'byte-identity proof': 9, - 'declaration bar': 5, - 'tables': 4, - 'refusals': 7, -}); -const SELF_TEST_BATTERY_FLOOR = 6; - -/** A registry in the real file's shape: two majors, a private helper, two shared ones, the tables. */ -function fixtureRegistry() { - return `// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * A fixture table. - */ - -import type { ConversionApplication, MetadataConversion } from './types.js'; -import { mapPages, renameKey } from './walk.js'; -import { isFilterAST, parseFilterAST } from '../data/filter.zod.js'; - -type Dict = Record; -const isDict = (v: unknown): v is Dict => typeof v === 'object' && v !== null; -type Emit = (detail: ConversionApplication) => void; - -/** Read by one conversion. */ -function onlyForA(x: Dict, emit: Emit): Dict { - return isDict(x) ? renameKey(x, 'a', 'b', 'p', emit) : x; -} - -/** The first conversion. */ -const convA: MetadataConversion = { - id: 'conv-a', - toMajor: 11, - surface: 's', - summary: 's', - apply(stack, emit) { - return mapPages(stack, (p) => onlyForA(p as Dict, emit)); - }, - fixture: { before: {}, after: {}, expectedNotices: 0 }, -}; - -// A comment between two statements, kept with the one below it. -const convB: MetadataConversion = { - id: 'conv-b', - toMajor: 18, - surface: 's', - summary: 's', - apply(stack) { - const isDict = 1; // a local that shadows the module name is not a read of it - return isFilterAST(stack) && isDict ? parseFilterAST(stack) as never : stack; - }, - fixture: { before: {}, after: {}, expectedNotices: 0 }, -}; - -const convC: MetadataConversion = { - id: 'conv-c', - toMajor: 18, - surface: 's', - summary: 's', - apply(stack, emit) { - const e: Emit = emit; - const bag = { convA: 1 }; - return isDict(stack) ? (e && bag.convA && stack) : stack; - }, - fixture: { before: {}, after: {}, expectedNotices: 0 }, -}; - -interface OrderedConversion { - readonly conversion: MetadataConversion; - readonly order: number; -} - -function inApplicationOrder(list: readonly OrderedConversion[]): MetadataConversion[] { - return [...list].sort((a, b) => a.order - b.order).map((o) => o.conversion); -} - -const MAJOR_18_CONVERSIONS: readonly OrderedConversion[] = [ - { conversion: convB, order: 2 }, - { conversion: convC, order: 1 }, -]; - -export const CONVERSIONS_BY_MAJOR: Readonly> = { - 11: [convA], - 18: /* @__PURE__ */ inApplicationOrder(MAJOR_18_CONVERSIONS), -}; - -export const ALL_CONVERSIONS: readonly MetadataConversion[] = /* @__PURE__ */ Object.keys(CONVERSIONS_BY_MAJOR) - .map(Number) - .flatMap((major) => CONVERSIONS_BY_MAJOR[major]!); -`; -} - -async function selfTest() { - const tm = await loadTsMorph(); - const batterySeen = new Map(); - let battery = null; - let failed = 0; - let cases = 0; - const open = (name) => { battery = name; }; - const check = (label, ok, detail = '') => { - batterySeen.set(battery, (batterySeen.get(battery) ?? 0) + 1); - cases += 1; - if (ok) console.log(` ✓ [${battery}] ${label}`); - else { failed += 1; console.error(` ✗ [${battery}] ${label}${detail ? ` — ${detail}` : ''}`); } - }; - const refused = (fn) => { try { fn(); return false; } catch (e) { return e instanceof CodemodRefusal; } }; - - const input = fixtureRegistry(); - const planned = plan(tm, input); - const moduleOf = (label) => planned.rows.find((r) => r.label === label)?.module; - - open('plan'); - { - check('each conversion goes to entries//.ts', - moduleOf('convA') === 'entries/11/conv-a.ts' && moduleOf('convB') === 'entries/18/conv-b.ts' && moduleOf('convC') === 'entries/18/conv-c.ts'); - check('a helper one conversion reads moves into that conversion\'s module', moduleOf('onlyForA') === 'entries/11/conv-a.ts'); - check('helpers two conversions read move into the shared leaf', ['Dict', 'isDict', 'Emit'].every((n) => moduleOf(n) === SHARED_MODULE), - ['Dict', 'isDict', 'Emit'].map(moduleOf).join(' | ')); - check('the tables and their helpers stay', ['OrderedConversion', 'inApplicationOrder', 'MAJOR_18_CONVERSIONS', 'CONVERSIONS_BY_MAJOR', 'ALL_CONVERSIONS'] - .every((n) => moduleOf(n) === null)); - const b = planned.rows.find((r) => r.label === 'convB'); - check('a local that shadows a module name is not a read of it', !b.refs.has('isDict'), [...b.refs.keys()].join(', ')); - check('a property named like a module name is not a read of it', !planned.rows.find((r) => r.label === 'convC').refs.has('convA')); - check('a type-position read is a read', planned.rows.find((r) => r.label === 'convC').refs.get('Emit') === 'local'); - check('an import read is recorded as an import', b.refs.get('isFilterAST') === 'import' && b.refs.get('parseFilterAST') === 'import'); - check('the plan names every statement once', planned.rows.length === 12, String(planned.rows.length)); - } - - open('generation'); - const out = generate(tm, planned); - { - const a = out.modules.get('entries/11/conv-a.ts') ?? ''; - const shared = out.modules.get(SHARED_MODULE) ?? ''; - check('an entry module imports its base imports rebased, and the shared leaf', - a.includes("import type { MetadataConversion } from '../../types.js';") - && a.includes("import { mapPages, renameKey } from '../../walk.js';") - && a.includes("import { type Dict, type Emit, isDict } from '../shared.js';"), a.slice(0, 900)); - check('an entry module ends with its one generated export', a.endsWith('\n\nexport { convA };\n')); - check('the shared leaf exports what the modules read, types spelled as types', - shared.includes('export { type Dict, type Emit, isDict };') && !/from '\.\.?\/(?:registry|1|11|18)/.test(shared), shared); - check('the host keeps the imports it still reads and imports each conversion in definition order', - /import type \{ MetadataConversion \} from '\.\/types\.js';\n\n\/\/ \[#29987 codemod\][^]*?\nimport \{ convA \} from '\.\/entries\/11\/conv-a\.js';\nimport \{ convB \} from '\.\/entries\/18\/conv-b\.js';\nimport \{ convC \} from '\.\/entries\/18\/conv-c\.js';\n/.test(out.host), - out.host.slice(0, 900)); - check('the host keeps its docblock and its tables byte for byte', - out.host.startsWith(input.slice(0, input.indexOf('import type'))) && out.host.endsWith(input.slice(input.indexOf('\ninterface OrderedConversion')))); - const again = generate(tm, plan(tm, input)); - check('two runs write byte-identical trees', - treeHash(new Map([[HOST_BASENAME, again.host], ...again.modules])) === treeHash(new Map([[HOST_BASENAME, out.host], ...out.modules]))); - } - - open('byte-identity proof'); - { - const ok = verify(tm, input, out.host, out.modules); - check('the generated split proves', ok.failures.length === 0 && ok.readings.rebuilt, ok.failures.join(' | ')); - const mutate = (rel, from, to) => new Map([...out.modules].map(([k, t]) => [k, k === rel ? t.replace(from, to) : t])); - const failsWith = (label, host, modules, needle) => { - const v = verify(tm, input, host, modules); - check(label, v.failures.some((f) => f.includes(needle)), v.failures.join(' | ') || 'no failure'); - }; - failsWith('an edited moved statement fails', out.host, mutate('entries/11/conv-a.ts', "summary: 's',", "summary: 't',"), 'differs from its base text'); - failsWith('a re-indented moved statement fails', out.host, mutate('entries/18/conv-c.ts', ' apply(stack, emit) {', ' apply(stack, emit) {'), 'differs from its base text'); - failsWith('a dropped comment above a moved statement fails', out.host, mutate('entries/18/conv-b.ts', '// A comment between two statements, kept with the one below it.\n', ''), 'differs from its base text'); - failsWith('an edited staying table fails', out.host.replace('order: 2', 'order: 3'), out.modules, 'differs from its base text'); - failsWith('a lost conversion module fails', out.host, new Map([...out.modules].filter(([k]) => k !== 'entries/18/conv-b.ts')), 'is in no file of the split'); - failsWith('a conversion filed under the wrong major fails', out.host, - new Map([...out.modules].map(([k, t]) => [k === 'entries/11/conv-a.ts' ? 'entries/18/conv-a.ts' : k, t])), 'which belongs at entries/11/conv-a.ts'); - failsWith('an import re-pointed at another file fails', out.host, mutate('entries/18/conv-b.ts', "from '../../../data/filter.zod.js'", "from '../../walk.js'"), 'the base from'); - failsWith('a leaf importing the host fails', out.host, - mutate('entries/18/conv-c.ts', "import type { MetadataConversion } from '../../types.js';", "import type { MetadataConversion } from '../../registry.js';"), 'a leaf never imports the host'); - } - - open('declaration bar'); - { - const base = 'export declare class A {\n private x;\n t: "b" | "a";\n}\nexport { A };\n'; - check('identical files pass', dtsBarFor('f', base, base).failures.length === 0); - check('a union-member swap passes (the ruling\'s one normalisation)', dtsBarFor('f', base, base.replace('"b" | "a"', '"a" | "b"')).failures.length === 0); - check('a retyped member fails', dtsBarFor('f', base, base.replace('"b" | "a"', '"b" | "c"')).failures.length > 0); - const control = injectChange(base); - check('the positive control makes a private member public, and the bar catches it', - control?.kind === 'private member made public' && dtsBarFor('f', base, control.text).failures.length > 0); - check('a changed export list fails', dtsBarFor('f', base, base.replace('export { A };', 'export { A as B };')).failures.length > 0); - } - - open('tables'); - { - const t = { exports: ['ALL_CONVERSIONS', 'CONVERSIONS_BY_MAJOR'], all: ['a', 'b', 'c'], byMajor: { 11: ['a'], 18: ['b', 'c'] }, digests: { a: '1', b: '2', c: '3' } }; - const clone = () => JSON.parse(JSON.stringify(t)); - check('equal tables compare equal', compareTables(t, clone()).length === 0); - const reordered = clone(); reordered.all = ['a', 'c', 'b']; reordered.byMajor[18] = ['c', 'b']; - check('a reorder is a difference', compareTables(t, reordered).length === 2); - const changed = clone(); changed.digests.b = '9'; - check('a changed value under the same id is a difference', compareTables(t, changed).some((f) => f.startsWith('b:'))); - const dropped = clone(); delete dropped.byMajor[11]; - check('a dropped major is a difference', compareTables(t, dropped).length > 0); - } - - open('refusals'); - { - check('a split file is refused as input', refused(() => plan(tm, out.host))); - check('an entry without a literal id is refused', refused(() => plan(tm, input.replace("id: 'conv-a',", 'id: String(1),')))); - check('an id a path could misread is refused', refused(() => plan(tm, input.replace("id: 'conv-a',", "id: 'conv/a',")))); - check('two entries sharing an id are refused', refused(() => plan(tm, input.replace("id: 'conv-b',", "id: 'conv-a',")))); - check('two ids equal but for case are refused', refused(() => plan(tm, input.replace("id: 'conv-b',", "id: 'Conv-A',")))); - check('an entry reading another entry is refused', refused(() => plan(tm, input.replace('const e: Emit = emit;', 'const e: Emit = emit; void convA;')))); - check('a top-level expression statement is refused', refused(() => plan(tm, input.replace('\ninterface OrderedConversion', '\nconsole.log(1);\ninterface OrderedConversion')))); - } - - const declared = Object.keys(SELF_TEST_BATTERIES); - if (declared.length < SELF_TEST_BATTERY_FLOOR) { - failed += 1; - console.error(`✗ self-test floor: ${declared.length} batteries declared, below the pinned ${SELF_TEST_BATTERY_FLOOR}`); - } - for (const [name, count] of batterySeen) { - if (!declared.includes(name)) { failed += 1; console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s) but is not declared`); } - } - for (const name of declared) { - const count = batterySeen.get(name) ?? 0; - if (count < SELF_TEST_BATTERIES[name]) { - failed += 1; - console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s), below its pinned ${SELF_TEST_BATTERIES[name]}`); - } - } - if (failed > 0) { - console.error(`\n✗ codemod-split-conversions-registry self-test: ${failed} failure(s) (cases and floor).`); - process.exitCode = 1; - selfTestReachedVerdict = true; - return; - } - console.log(`\n✓ codemod-split-conversions-registry self-test: ${cases} cases in ${declared.length} batteries pass.`); - selfTestReachedVerdict = true; -} - -if (isEntrypoint(import.meta.url)) { - main(process.argv.slice(2)).then( - (code) => process.exit(code), - (error) => { - if (error instanceof CodemodRefusal) { - console.error(`✗ codemod-split-conversions-registry: ${error.message}`); - process.exit(2); - } - console.error(error); - process.exit(2); - }, - ); -} diff --git a/scripts/codemod-split-engine.mjs b/scripts/codemod-split-engine.mjs deleted file mode 100644 index 15c7f145fe8..00000000000 --- a/scripts/codemod-split-engine.mjs +++ /dev/null @@ -1,7452 +0,0 @@ -#!/usr/bin/env node -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * codemod-split-engine — move whole sections of `ObjectQL`'s method bodies out - * of `packages/objectql/src/engine.ts` into section modules, move the - * top-level declarations ahead of the class into one leaf module, - * deterministically, and prove the move. - * - * node scripts/codemod-split-engine.mjs # plan: print the section table, write nothing - * node scripts/codemod-split-engine.mjs --write # apply the split, then verify it - * node scripts/codemod-split-engine.mjs --verify --base - * # re-prove a split on disk against engine.ts at - * node scripts/codemod-split-engine.mjs --scoped [--write] - * # the second pass (#30052): plan (or apply) ObjectRepository and ScopedContext - * node scripts/codemod-split-engine.mjs --scoped --verify --base - * # re-prove the second pass on disk against engine.ts at - * node scripts/codemod-split-engine.mjs --scoped --members [--write] - * # the second pass's members mode (#30020): move named scoped methods onto the split class - * node scripts/codemod-split-engine.mjs --scoped --members --verify --base - * # re-prove the members mode on disk against engine.ts and its scoped modules at - * node scripts/codemod-split-engine.mjs --hand-docs [--modules ] [--write] - * # the third pass (#30053): plan (or apply) the hand series' private docblocks - * node scripts/codemod-split-engine.mjs --hand-docs --verify --base - * # re-prove the third pass on disk against engine.ts and its hand modules at - * node scripts/codemod-split-engine.mjs --members [--write] - * # the fourth pass (#30055): plan (or apply) moving the named methods onto the split class - * node scripts/codemod-split-engine.mjs --members --verify --base - * # re-prove the fourth pass on disk against engine.ts and its modules at - * node scripts/codemod-split-engine.mjs --self-test - * node scripts/codemod-split-engine.mjs --help # this usage, on any tree (split or not) - * - * ## Why a script, and what it repeats - * - * The large-file programme's ruling A (`6583399215`) splits each file by a - * deterministic codemod that applies the file's existing cut pattern to whole - * sections, regenerated on the latest `main` at landing instead of rebased. - * `scripts/codemod-split-sql-driver.mjs` is the pilot; this is the same - * programme for `engine.ts`, and it applies the cut pattern THIS file's hand - * series (21 cuts, 25 `engine-*.ts` modules) already uses, which is the - * pilot's pattern too: - * - * - The method stays on the class with its docblock, modifiers and signature - * byte-for-byte, so the published `.d.ts` keeps its names and positions and - * an instance spy or a subclass override is still the one callers reach. - * Only `async` is dropped from a stub, as every async stub of the series did. - * - The body moves, unedited, into an exported function of the same name in - * `engine-
.ts`, whose `this` is one named host: the `ObjectQL` - * members the body reads, typed AS the class members (`ObjectQL['x']`). - * A private member is reached the same way as a public one: the indexed - * access type names it, and the stub, inside the class, reads it. - * - The stub hands the body that host: a method as a closure that calls it on - * the engine at call time, a field or accessor as a GETTER that reads it - * when the body reads it. Since #30051 the host is ONE object per facet and - * engine (`HOSTS_MODULE`, built on first use by a factory the class's static - * block installs), so a stub is one line, `Facet.x.call(xHost.of(this), …)`, - * instead of a host literal built on every call. - * - * Ruling `6591753301` (option A) widened the pattern two ways, and this script - * applies both, as the pilot does: - * - * - (a) A section module may import VALUES from `engine.ts`. A staying - * top-level name a moved body reads is exported for it by one generated - * `export { … }` list (the declaration's own text is not touched), and - * `index.ts` re-exports by name, so none reaches the package. Every such - * use is inside a function body, so the cycle is never read at evaluation. - * - (b) The top-level declarations ahead of the class (`const` / `function` / - * `interface` / `type`) move WHOLE, with the comments above them, into one - * leaf module, `LEAF_MODULE`, in base order. The leaf never imports - * `engine.ts` or an `engine-*` module: a declaration that names the class, - * an `engine-*` import or a declaration that stays, stays itself. `engine.ts` - * imports back what it still reads and re-exports, by name, every moved - * declaration it exported, so every importer of `./engine.js` (`index.ts`, - * the hand-series modules, the tests) reads what it read. - * - * Two things this file needs that the pilot's did not: - * - * - SECTIONS BY ANCHOR. `engine.ts` has five banners in a 17,000-line class, - * so a section is named by its FIRST member, in `SECTION_ANCHORS` (the - * `protocol.ts` codemod's form): a member belongs to the last anchor at or - * above it. An anchor the class does not declare, or anchors out of class - * order, stop the script (exit 2): a new section is a decision someone - * writes here, never a name the script makes up. - * - AN IMPORT PRUNE. The package compiles with `noUnusedLocals`, so an import - * binding only moved text read is dropped from `engine.ts` - * (`pruneImports`). It is the one edit the undo cannot read back from the - * head; the proof recomputes it from the head and requires every pruned - * name to occur in a moved body or a moved declaration. - * - * ⛔ The moved text is not re-indented and not formatted: the body is the - * method's `{ … }` exactly as it stood, so byte-identity is equality of text, - * not equality after a transform. - * - * ## What stays, and why (each reason is mechanical) - * - * A method stays whole on the class when moving it would change what it does, - * what the published `.d.ts` says, or what a gate or test that reads - * `engine.ts` BY PATH sees. `STAY_REASONS` lists every reason for a method and - * `TOP_STAY_REASONS` every reason for a top-level declaration; the plan prints - * every one that stayed and why. The reasons that are tables rather than rules - * are `PATH_READER_PINS` (a name whose text a reader extracts from `engine.ts` - * by path), `PATH_READER_NEEDLES` (literal text a reader requires to find - * there) and `CLASS_PATH_READER_NEEDLES` (the same, for a reader that also - * reads the leaf, so only a method carrying it stays). Ruling `6597555122` - * item 3: a reader that can read the new modules gains them in its reading - * list in the same PR instead, and needs no row here. - * - * ## The proof (`--write` runs it on its own output; `--verify` re-runs it) - * - * 1. Byte-identity: every generated function's body, parameters and return - * type are the base method's text, exactly; every leaf declaration is its - * base statement's text with the comments above it, exactly; and putting - * every body back (and `async` back on its stub), taking the generated - * imports and exports out, and splicing the leaf back between the - * statements that stayed rebuilds the base `engine.ts` byte-for-byte once - * the base's import bindings the head no longer reads are pruned from it - * (the prune above), so nothing else in it moved. The leaf's relative - * VALUE imports are followed on disk: none may reach `engine.ts` or an - * `engine-*` module. - * 2. The declaration-file bar of ruling `6348891160`, judged by ruling - * `6441032442` B's second normalisation (ruling `6597555122` item 2), is a - * report reading on two built dists, never a `scripts/` file (that - * ruling's item 3); the PR reports it. The pilot's `--dts` reads only - * `index.d.ts`, which here re-exports a hashed shared chunk - * (`util-.d.ts`) that holds the declarations, so this script does - * not carry it. - * - * ## Determinism - * - * The input is the text of `engine.ts`. It is parsed in an in-memory project - * (no `node_modules`, no build output, no clock), every collection is emitted - * in source order or sorted, and the output is a pure function of the input: - * two runs on one input write byte-identical trees (the plan prints the output - * tree's sha256). Only the proof's leaf-reach walk reads sibling files. - * - * ## The second pass: `ObjectRepository` and `ScopedContext` (#30052) - * - * `engine.ts` declares two more classes after `ObjectQL`, the repository a - * hook reaches as `ctx.api.object(name)` and the context it reaches as - * `ctx.api`. `--scoped` facades them with this pass's cut pattern, stay rules - * and byte-identity proof, one facet module per class (`SCOPED_CLASSES`) and - * one host per INSTANCE (`SCOPED_HOSTS_MODULE`, #30051's shape keyed by the - * instance), and it touches no other byte: its input is the `engine.ts` the - * first pass left, and it is proved against that file, so it is re-run on the - * latest `main` at landing like the first. Its marker is `SCOPED_MARK`, so the - * two passes' stubs and files are told apart. Two stay reasons are its own: - * a body that reads a private member off another instance (`foreign-private`: - * the class body may, a module function may not) and one that reads a - * non-public static (`private-static`: the statics route is `ObjectQL`'s). - * - * `--scoped --members Class#member,…` is that pass's members mode (#30020): on - * the split file, it moves a scoped method a stay rule held then into its - * class's written facet, with the identity port on the instance's host (a bare - * `this` reads `this.facade`, the instance itself) and R9, a symbol key - * (`[SEED_USER_GRANTS]` moves into the facet member `seedUserGrants`). Its - * section below states what it grows, what it refuses and the undo proof. - * - * ## The third pass: the hand series' private docblocks (#30053) - * - * `--hand-docs` moves a private hand-series stub's docblock into its hand - * module, onto the function the stub calls, as the first two passes move a - * private method's docblock with its body; a public or protected one stays on - * the class. Its section below (`HAND_STUB_MARK`) states the rule, the slices - * (`--modules`) and the proof, the undo of every move. - * - * ## The fourth pass: named methods onto the split class (#30055) - * - * The first pass runs on an unsplit file only, so a method a stay rule held - * when `main` was split (a path pin since retired, a return type since - * spelled) moves by `--members`: on the split file, as the first pass would - * have moved it, into the facet module it wrote. Its section below - * (`MEMBERS_CARD`) states what it grows, what it refuses and the undo proof, - * and the three rules #30020 added to it for a body that hands the engine on. - * - * ## The fifth pass: a hand stub's computing host slot (#30020) - * - * `--hand-slots` moves a slot that computes out of a hand-series stub's host - * literal into the stub's hand module, so the stub is a delegation. Its - * section below (`HAND_SLOTS_CARD`) states the rule and the undo proof. - * - * ts-morph is a root devDependency, resolved from the root manifest, as the - * pilot takes it. - * - * Exit codes: 0 done · 1 a proof failed (stop: the generated split is never - * hand-edited to pass) · 2 the script could not run (unknown anchor, missing - * prerequisite, bad arguments) · 3 an input does not parse (`ts-parse.mjs`'s - * refusal, which names the parse errors). - */ - -import { createHash } from 'node:crypto'; -import { execFileSync } from 'node:child_process'; -import { existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { createRequire } from 'node:module'; -import { dirname, join, relative, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -import { isEntrypoint } from './invoked-as.mjs'; -import { parseSourceFile } from './ts-parse.mjs'; - -const ROOT = join(fileURLToPath(new URL('.', import.meta.url)), '..'); -const SRC_REL = 'packages/objectql/src'; -const SRC_DIR = join(ROOT, SRC_REL); -const HOST_BASENAME = 'engine.ts'; -const HOST_PATH = join(SRC_DIR, HOST_BASENAME); -const CLASS_NAME = 'ObjectQL'; -const CARD = '#29986'; -const SCRIPT = 'scripts/codemod-split-engine.mjs'; - -/** The marker every generated file and stub carries; `--verify` keys on it. */ -const MARK = `[${CARD} codemod]`; - -/** A generated or hand-series section module of `engine.ts`, by its import specifier. */ -const SEAM_SPECIFIER = /^\.\/engine-[a-z0-9-]+\.js$/; - -/** - * The sections of `ObjectQL`, top to bottom, each named by its first member - * (a field or a method), mapped to the module its movable bodies go to. - * `null` keeps the section on the class. No module shares a file with a - * hand-written one: the script refuses to write over a file it did not - * generate, and the hand series' 25 module names are not reused. - */ -const SECTION_ANCHORS = Object.freeze([ - ['txStore', 'Class head: units, hooks, functions, body runners, hook dispatch', 'engine-hooks-and-functions.ts'], - ['registerAction', 'Action system and packaged-action activation', 'engine-actions.ts'], - ['_heldFileResolver', 'Registration seams, readable-ids security, formula and default permissions', 'engine-security-resolvers.ts'], - ['writeEpoch', 'Authz invalidation, middleware, session, driver options, posture, organization probe', 'engine-middleware-and-context.ts'], - ['resolveNowDefault', 'Field defaults and autonumbers', 'engine-defaults-and-autonumbers.ts'], - ['registrationConversionWarned', 'Package, app, plugin, driver and datasource registration', 'engine-registration.ts'], - ['setRealtimeService', 'Realtime, i18n, home amounts, validation messages, references, master-detail', 'engine-references-and-master-detail.ts'], - ['setCryptoProvider', 'Crypto, secrets, internal fields, schema and datasource routing, init', 'engine-secrets-and-routing.ts'], - ['objectHasMediaField', 'Migration flags, value-shape deviations, creation attestations, destroy', 'engine-migration-state.ts'], - ['MAX_EXPAND_DEPTH', 'Summary indexes, related-record expansion, file and reference hydration', 'engine-summaries-and-expansion.ts'], - ['resolveWhereTokens', 'Query lowering, search, find and findOne', 'engine-find.ts'], - ['staticReadonlyCreateStrip', 'Write preparation and insert', 'engine-insert.ts'], - ['update', 'Update', 'engine-update.ts'], - ['planCascadeAtomicity', 'Cascade and referential delete planning', 'engine-cascade-planning.ts'], - ['delete', 'Delete, count, aggregate and execute', 'engine-delete-and-aggregate.ts'], - ['transaction', 'Transactions', 'engine-transactions-section.ts'], - ['registerObject', 'Compatibility / convenience API', 'engine-compatibility-section.ts'], -]); - -/** - * The leaf the top-level declarations ahead of the class move to, whole - * (lever (b) of ruling `6591753301`). A leaf: it never imports `engine.ts` or - * any `engine-*` module, so it is evaluated before the class and forms no - * cycle with it. - */ -const LEAF_MODULE = 'engine-top-level.ts'; - -/** - * The module that holds each facet's host, one per engine (#30051): a - * `FacetHost` per facet module, built on first use by the factory the class's - * static block installs and kept for the engine's life. It imports types only, - * so it is evaluated before the class whichever module is loaded first, and - * the class's static block can install into it. - */ -const HOSTS_MODULE = 'engine-facet-hosts.ts'; -const HOSTS_CLASS = 'FacetHost'; - -/** - * Names whose text a reader takes out of `engine.ts` BY PATH. Moving it would - * leave that reader reading a stub, or nothing. A class method or a top-level - * declaration of the name stays. Each row names the reader. A row naming - * nothing the file declares stops the script (exit 2), so the table cannot rot - * into names nobody reads. - */ -const PATH_READER_PINS = Object.freeze({ - // Empty since #30055: the six rows the #4918 query-options erasure guard - // held here (its per-file baseline names `engine.ts`, so a moved `as any` - // site would have red `pnpm lint`) retired once their sites were typed, and - // the fourth pass (`--members`) moved the six bodies. -}); - -/** - * Literal text a reader requires to find in `engine.ts` BY PATH. A class - * method or a top-level declaration whose text carries one stays, so the - * reader still finds it where it looks. Each row names the reader. A needle - * the file no longer carries stops the script (exit 2). - */ -const PATH_READER_NEEDLES = Object.freeze({ -}); - -/** - * Literal text a reader requires to find in `engine.ts` OR the leaf, but reads - * in no section module. A method whose text carries one stays on the class; a - * top-level declaration carrying one moves as any other, because the reader - * reads the leaf it moves to. The same stale-needle refusal applies. - */ -const CLASS_PATH_READER_NEEDLES = Object.freeze({ -}); - -/** - * The `ObjectQL` methods a host hands its body as a BOUND reference - * (`this.m.bind(this)`) rather than as a closure that calls it. The pilot - * needed one for a gate that refuses an unbound builder call; no gate reads - * `engine.ts` that way, so the set is empty and every method goes as a - * closure. - */ -const BOUND_HOST_METHODS = new Set(); - -/** Every reason a method stays, with the one-line why the plan prints. */ -const STAY_REASONS = Object.freeze({ - 'no-section': 'declared above the first section anchor', - 'section-kept': 'its section maps to no module', - 'static-this': 'a static method whose body reads `this` (the class; a facet static has its own)', - 'static-name-shared': 'a static method whose name an instance member also takes (one facet cannot hold both)', - 'no-body': 'an overload signature or abstract member', - 'generator': 'a generator', - 'overloaded': 'an overloaded method', - 'decorated': 'a decorated method', - 'not-identifier-name': 'a computed, string or #private name', - 'inferred-return-type': 'a non-private method whose return type is inferred (the .d.ts would infer it through the module)', - 'parameter-shape': 'a destructured or `this` parameter (the stub cannot forward it unchanged)', - 'comment-in-parameters': 'a comment inside its parameter list (one-line parameters would drop it)', - 'path-reader': 'a reader takes its text out of engine.ts by path (PATH_READER_PINS / PATH_READER_NEEDLES / CLASS_PATH_READER_NEEDLES)', - 'arguments': 'its body reads `arguments`', - 'super': 'its body reads `super`', - 'new-target': 'its body reads `new.target`', - 'this-type': 'it names the polymorphic `this` type', - 'bare-this': 'it uses `this` other than as `this.member`', - 'unknown-member': 'it reads a `this.member` the class does not declare', - 'this-write': 'it assigns a `this.member` that is not a field, or deletes one (the host carries a setter for a field only)', - 'method-as-value': 'it reads a method as a value instead of calling it', - 'field-call': 'it calls a field or accessor as a function (the host would change its receiver)', - 'overloaded-host-method': 'it calls an overloaded method (the host closure cannot be typed)', - 'static-write': 'its static reads go through ObjectQLStatics and it assigns a static (the forwarder is read-only)', - 'static-as-value': 'its static reads go through ObjectQLStatics and it reads a static method as a value (a forwarder is another function)', - 'static-field-call': 'its static reads go through ObjectQLStatics and it calls a static field or accessor (the receiver would change)', - 'overloaded-static': 'its static reads go through ObjectQLStatics and it calls an overloaded static (one forwarder cannot carry the overloads)', - 'static-route-conflict': 'its facet module reads the statics through ObjectQLStatics, imported AS `ObjectQL`, and it names `ObjectQL` other than as `ObjectQL.`', - 'module-write': 'it assigns a module-scope binding of engine.ts (an import is read-only)', - 'already-moved': 'its body is already a hand-series seam stub', - 'parameter-shadows': 'a parameter shadows a stub local (`host`, `readX`, `writeX`)', - 'foreign-private': 'it reads a private or protected instance member off a receiver other than `this` (a module function cannot)', - 'private-static': 'it reads a non-public static of its class (the statics route is `ObjectQL`\'s alone; the scoped classes declare none)', - 'facade-taken': 'it hands the engine on, and the class declares a member named `facade` (the identity port would shadow it)', - 'ctor-facet-name': 'a class that declares a member of the name a moved constructor body takes in its facet', - 'definite-assignment': 'a constructor that writes a field only a constructor may assign (TS2564) other than as R8 carries it: a leading `this.F = EXPR;` whose EXPR reads no `this` and no top-level name of engine.ts', -}); - -/** - * The fourth pass's identity port (#30020 R1): the host entry a moved body - * reads the engine itself through, where the method read a bare `this` - * (`ql: this`, `new ScopedContext(ctx, this)`, `(this as any)._flag`). The - * host factory hands it as the engine (`facade: engine`), so at each such site - * the body sees the same object the method saw. - */ -const FACADE_MEMBER = 'facade'; -const FACADE_DOC = ' /** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */'; -const facadeIfaceLine = (classType) => `${FACADE_DOC}\n readonly ${FACADE_MEMBER}: ${classType};`; -const FACADE_INSTALL_LINE = ` ${FACADE_MEMBER}: engine,`; -/** The same port on a scoped class's instance host (#30020 S1): `facade: instance`. */ -const SCOPED_FACADE_DOC = ' /** The instance itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */'; -const SCOPED_FACADE_INSTALL_LINE = ` ${FACADE_MEMBER}: instance,`; - -/** Every reason a top-level declaration ahead of the class stays in engine.ts. */ -const TOP_STAY_REASONS = Object.freeze({ - 'top-kind': 'not a const / function / interface / type declaration of plain names', - 'merged-declaration': 'its name is declared by more than one statement (an overload set or a merged declaration)', - 'path-reader': 'a reader takes its text out of engine.ts by path (PATH_READER_PINS / PATH_READER_NEEDLES)', - 'class-reference': 'it names a class engine.ts declares (the leaf would import engine.ts back)', - 'seam-import': 'it uses an import from an engine-* module (the leaf would reach engine.ts back through it)', - 'needs-stayer': 'it names a declaration that stays (the leaf would import engine.ts back)', -}); - -// ── Loading ts-morph ───────────────────────────────────────────────────────── - -let tsMorph = null; - -/** ts-morph from the root manifest's devDependencies; a missing install is exit 2, never a stack trace. */ -async function loadTsMorph() { - if (tsMorph) return tsMorph; - const manifest = join(ROOT, 'package.json'); - try { - const resolved = createRequire(manifest).resolve('ts-morph'); - const mod = await import(pathToFileURL(resolved).href); - tsMorph = mod.default ?? mod; - return tsMorph; - } catch (error) { - console.error( - `✗ codemod-split-engine: PREREQUISITE NOT MET — ts-morph does not resolve from ${manifest} ` + - `(${error && error.code ? error.code : 'error'}). Run \`pnpm install\` in this worktree.`, - ); - process.exit(2); - } -} - -/** - * One in-memory project per parse: no file system, no lib, no build output. - * The text goes through `ts-parse.mjs`'s checked parse first, which refuses a - * source with parse errors (its exit 3) instead of handing back a recovered - * partial tree; ts-morph then reads the same text, already vouched for. - */ -function parse(tm, fileName, text) { - parseSourceFile(fileName, text); - const project = new tm.Project({ - useInMemoryFileSystem: true, - compilerOptions: { target: tm.ts.ScriptTarget.ES2020, strict: true, noLib: true, allowJs: false }, - }); - project.getFileSystem().writeFileSync(fileName, text); - return project.addSourceFileAtPath(fileName); -} - -/** A reason the script cannot run at all (exit 2) — never a verdict on the split. */ -class CodemodRefusal extends Error {} - -function refuse(message) { - throw new CodemodRefusal(message); -} - -// ── Reading the sections ───────────────────────────────────────────────────── - -/** - * Each member's section: the last anchor at or above it. Refuses an anchor the - * class does not declare, a duplicate anchor, or anchors out of class order. - * Returns a function from a member node to its `[anchor, title, module]` row, - * or null above the first anchor. - */ -function readSections(cls, anchors) { - const firstStart = new Map(); - for (const m of cls.getMembers()) { - const name = typeof m.getName === 'function' ? m.getName() : null; - if (name && !firstStart.has(name)) firstStart.set(name, m.getStart()); - } - const rows = []; - const seen = new Set(); - for (const row of anchors) { - const [anchor] = row; - if (seen.has(anchor)) refuse(`SECTION_ANCHORS names ${anchor} twice`); - seen.add(anchor); - if (!firstStart.has(anchor)) refuse(`SECTION_ANCHORS names ${anchor}, which ${CLASS_NAME} does not declare`); - rows.push({ row, at: firstStart.get(anchor) }); - } - for (let i = 1; i < rows.length; i += 1) { - if (rows[i].at <= rows[i - 1].at) refuse(`SECTION_ANCHORS out of class order: ${rows[i].row[0]} is declared above ${rows[i - 1].row[0]}`); - } - return (member) => { - let hit = null; - for (const r of rows) if (r.at <= member.getStart()) hit = r.row; - return hit; - }; -} -// ── Analysis ───────────────────────────────────────────────────────────────── - -/** The names engine.ts binds at module scope, and which of them it exports. */ -function moduleScope(tm, sf) { - const { Node } = tm; - const bindings = new Map(); // name -> { kind: 'import' | 'local', specifier?, form?, imported?, typeOnly? } - const exported = new Set(); - const importOrder = new Map(); // specifier -> first position among the import declarations - for (const st of sf.getStatements()) { - if (Node.isImportDeclaration(st)) { - const specifier = st.getModuleSpecifierValue(); - const order = importOrder.has(specifier) ? importOrder.get(specifier) : importOrder.size; - importOrder.set(specifier, order); - const declTypeOnly = st.isTypeOnly(); - const def = st.getDefaultImport(); - if (def) bindings.set(def.getText(), { kind: 'import', specifier, form: 'default', typeOnly: declTypeOnly }); - const ns = st.getNamespaceImport(); - if (ns) bindings.set(ns.getText(), { kind: 'import', specifier, form: 'namespace', typeOnly: declTypeOnly }); - for (const spec of st.getNamedImports()) { - bindings.set((spec.getAliasNode() ?? spec.getNameNode()).getText(), { - kind: 'import', specifier, form: 'named', imported: spec.getNameNode().getText(), - typeOnly: declTypeOnly || spec.isTypeOnly(), - }); - } - continue; - } - if (Node.isExportDeclaration(st)) { - if (!st.getModuleSpecifier()) for (const spec of st.getNamedExports()) exported.add(spec.getNameNode().getText()); - continue; - } - const isExported = Node.isExportable(st) && st.isExported(); - const names = []; - if (Node.isVariableStatement(st)) { - for (const decl of st.getDeclarations()) { - for (const id of [decl.getNameNode(), ...decl.getNameNode().getDescendantsOfKind(tm.SyntaxKind.Identifier)]) { - if (Node.isIdentifier(id)) names.push(id.getText()); - } - } - } else if (typeof st.getName === 'function' && st.getName()) { - names.push(st.getName()); - } - for (const name of names) { - bindings.set(name, { kind: 'local' }); - if (isExported) exported.add(name); - } - } - return { bindings, exported, importOrder }; -} - -/** Is `node` inside a type node, below `stop`? */ -function inTypePosition(tm, node, stop) { - for (let n = node.getParent(); n && n !== stop; n = n.getParent()) { - if (tm.ts.isTypeNode(n.compilerNode)) return true; - } - return false; -} - -/** The node that binds the `this` a `this` keyword at `node` reads. */ -function thisContainer(tm, node) { - const { Node } = tm; - for (let n = node.getParent(); n; n = n.getParent()) { - if ( - Node.isFunctionDeclaration(n) || Node.isFunctionExpression(n) || Node.isMethodDeclaration(n) || - Node.isConstructorDeclaration(n) || Node.isGetAccessorDeclaration(n) || Node.isSetAccessorDeclaration(n) || - Node.isClassDeclaration(n) || Node.isClassExpression(n) || Node.isClassStaticBlockDeclaration(n) - ) return n; - } - return null; -} - -/** Is the property access `pa` written (assigned, updated, deleted, destructured into)? */ -function isWritten(tm, pa) { - const { Node, SyntaxKind } = tm; - let target = pa; - for (let p = target.getParent(); p; target = p, p = p.getParent()) { - if ( - Node.isParenthesizedExpression(p) || Node.isArrayLiteralExpression(p) || Node.isObjectLiteralExpression(p) || - Node.isPropertyAssignment(p) || Node.isShorthandPropertyAssignment(p) || Node.isSpreadElement(p) || - Node.isSpreadAssignment(p) - ) continue; - break; - } - const parent = target.getParent(); - if (!parent) return false; - if (Node.isBinaryExpression(parent) && parent.getLeft() === target) { - const op = parent.getOperatorToken().getKind(); - return op >= SyntaxKind.FirstAssignment && op <= SyntaxKind.LastAssignment; - } - if (target === pa && (Node.isPrefixUnaryExpression(parent) || Node.isPostfixUnaryExpression(parent))) { - const op = parent.getOperatorToken(); - return op === SyntaxKind.PlusPlusToken || op === SyntaxKind.MinusMinusToken; - } - if (target === pa && Node.isDeleteExpression(parent)) return true; - if ((Node.isForOfStatement(parent) || Node.isForInStatement(parent)) && parent.getInitializer() === target) return true; - return false; -} - -/** The class's instance members by name: `{ kind: 'method' | 'field' | 'getter' | 'setter', overloaded }`. */ -function instanceMembers(tm, cls) { - const { Node } = tm; - const members = new Map(); - const note = (name, kind, extra = {}) => { - const prev = members.get(name); - if (prev && prev.kind === 'setter' && kind === 'getter') { members.set(name, { kind: 'getter', ...extra }); return; } - if (prev && prev.kind === 'getter' && kind === 'setter') return; - members.set(name, { kind, ...extra }); - }; - for (const m of cls.getMembers()) { - if (Node.isConstructorDeclaration(m)) { - for (const p of m.getParameters()) if (p.isParameterProperty()) note(p.getName(), 'field'); - continue; - } - if (typeof m.isStatic === 'function' && m.isStatic()) continue; - const nameNode = typeof m.getNameNode === 'function' ? m.getNameNode() : null; - if (!nameNode || !Node.isIdentifier(nameNode)) continue; - const name = nameNode.getText(); - if (Node.isMethodDeclaration(m)) note(name, 'method', { overloaded: m.getOverloads().length > 0 }); - else if (Node.isPropertyDeclaration(m)) note(name, 'field'); - else if (Node.isGetAccessorDeclaration(m)) note(name, 'getter'); - else if (Node.isSetAccessorDeclaration(m)) note(name, 'setter'); - } - return members; -} - -/** - * Read one method: why it must stay (empty = it moves), what its body reads - * through the host, and which imports its module needs. - */ -function readMethod(tm, ctx, m, { skip = [] } = {}) { - const { Node, SyntaxKind } = tm; - // The constructor (#30020 R8) is read as a method is, with the statements - // R8 keeps on the class (`skip`, source ranges) left out of the reading. - const isCtor = Node.isConstructorDeclaration(m); - const skipped = (node) => skip.some(([s, e]) => node.getStart() >= s && node.getEnd() <= e); - const reasons = []; - const add = (code, detail) => { - const tag = detail ? `${code}: ${detail}` : code; - if (!reasons.includes(tag)) reasons.push(tag); - }; - const host = new Map(); // member -> 'method' | 'getter' | 'facade' - const writes = new Set(); // fields the body assigns: the host carries a setter for each - const imports = new Map(); // local -> { value } - const moduleRefs = new Map(); // engine.ts top-level name -> { value } - // The identity port (#30020 R1, the fourth pass only): the start of every - // bare `this` in the body, each of which the facet member reads as - // `this.facade`, the host entry that hands the engine itself. - const identity = []; - // The private-static-through-host rule: the statics the body reads as - // `ObjectQL.x`, whether one is non-public (that takes the route), what the - // route cannot carry, and whether the body names `ObjectQL` any other way. - const classStatics = new Map(); // static -> 'method' | 'getter' - const routeBlockers = []; - let readsNonPublicStatic = false; - let classOther = false; - // The parameters the body reads (a constructor's facet takes only those: R8). - const paramsRead = new Set(); - const result = () => ({ reasons, host, writes, imports, moduleRefs, classStatics, routeBlockers, readsNonPublicStatic, classOther, identity, paramsRead }); - - if (!isCtor && m.isStatic() && ctx.members.has(m.getName())) add('static-name-shared'); - if (!m.getBody()) add('no-body'); - if (m.isAbstract && m.isAbstract()) add('no-body'); - if (!isCtor && m.isGenerator()) add('generator'); - if (m.getOverloads().length > 0) add('overloaded'); - if (!isCtor && m.getDecorators().length > 0) add('decorated'); - const nameNode = isCtor ? null : m.getNameNode(); - // R9 (#30020, the second pass's members mode only): a method keyed by a - // symbol binding (`[SEED_USER_GRANTS]`) moves under that binding's facet name. - const symbolKey = !isCtor && ctx.symbolKeys ? symbolKeyOf(tm, ctx, m) : null; - if (!isCtor && !Node.isIdentifier(nameNode) && !symbolKey) { add('not-identifier-name'); return result(); } - const name = isCtor ? 'constructor' : nameNode.getText(); - if (!isCtor && !m.getReturnTypeNode() && m.getScope() !== 'private') add('inferred-return-type'); - for (const p of m.getParameters()) { - // A defaulted identifier forwards as it is: the stub keeps the default and - // hands the body the value it produced. - if (!Node.isIdentifier(p.getNameNode()) || p.getName() === 'this') add('parameter-shape', p.getName()); - } - const body = m.getBody(); - if (!body) return result(); - - // A comment between the parentheses that no parameter's own text carries. - const params = m.getParameters(); - const open = m.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken); - const close = m.getFirstChildByKindOrThrow(SyntaxKind.CloseParenToken); - let between = ctx.text.slice(open.getEnd(), close.getStart()); - for (const p of [...params].reverse()) { - between = between.slice(0, p.getStart() - open.getEnd()) + between.slice(p.getEnd() - open.getEnd()); - } - if (/\/\/|\/\*/.test(between)) add('comment-in-parameters'); - - const methodText = m.getText(); - for (const needle of Object.keys(ctx.needles)) if (methodText.includes(needle)) add('path-reader', JSON.stringify(needle)); - for (const needle of Object.keys(ctx.classNeedles)) if (methodText.includes(needle)) add('path-reader', JSON.stringify(needle)); - if (Object.prototype.hasOwnProperty.call(ctx.pins, name)) add('path-reader', name); - - const regions = [...m.getTypeParameters(), ...params, m.getReturnTypeNode(), body].filter(Boolean); - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - for (const region of regions) { - const nodes = [region, ...region.getDescendants()]; - for (const node of nodes) { - if (skip.length > 0 && skipped(node)) continue; - const kind = node.getKind(); - if (kind === SyntaxKind.SuperKeyword) add('super'); - if (kind === SyntaxKind.ThisType) add('this-type'); - if (Node.isMetaProperty(node) && node.getKeywordToken() === SyntaxKind.NewKeyword) add('new-target'); - if (Node.isPropertyAccessExpression(node) && node.getExpression().getKind() !== SyntaxKind.ThisKeyword) { - // `other.x` where `x` is a private or protected INSTANCE member of the - // class: legal in the class body, refused in a module function. (A - // static is the statics route's question, not this one.) - const foreign = foreignNonPublicMember(tm, ctx, checker, node); - if (foreign) add('foreign-private', foreign); - } - if (kind === SyntaxKind.ThisKeyword) { - if (thisContainer(tm, node) !== m) continue; - if (!isCtor && m.isStatic()) { add('static-this'); continue; } - const parent = node.getParent(); - const inBody = region === body && !inTypePosition(tm, node, m); - if (ctx.identityPort && inBody && Node.isElementAccessExpression(parent) && parent.getExpression() === node) { - // R3 (#30020): `this[k]`, `k` typed as string literals each naming a - // field, reads (and writes) those fields through host getters (and - // setters); the body's text is unchanged. - const keys = literalFieldKeys(ctx, checker, parent.getArgumentExpression()); - if (!keys) { add('bare-this'); continue; } - const outer = parent.getParent(); - if (Node.isCallExpression(outer) && outer.getExpression() === parent) { add('field-call', keys.join('|')); continue; } - const written = isWritten(tm, parent); - if (written && Node.isDeleteExpression(outer)) { add('this-write', keys.join('|')); continue; } - for (const k of keys) { - host.set(k, 'getter'); - if (written) writes.add(k); - } - continue; - } - if (!Node.isPropertyAccessExpression(parent) || parent.getExpression() !== node) { - // R1 (#30020): a `this` that hands the engine on reads the host's - // `facade`, the engine itself. - if (ctx.identityPort && inBody && !Node.isElementAccessExpression(parent)) { - if (ctx.members.has(FACADE_MEMBER)) { add('facade-taken'); continue; } - identity.push(node.getStart()); - host.set(FACADE_MEMBER, 'facade'); - continue; - } - add('bare-this'); - continue; - } - const memberNameNode = parent.getNameNode(); - if (!Node.isIdentifier(memberNameNode)) { add('bare-this'); continue; } - const member = memberNameNode.getText(); - const info = ctx.members.get(member); - if (!info) { add('unknown-member', member); continue; } - if (isWritten(tm, parent)) { - // A field is written through a host setter; a method, an accessor or - // a `delete` cannot be. - if (info.kind === 'field' && !Node.isDeleteExpression(parent.getParent())) writes.add(member); - else add('this-write', member); - } - const outer = parent.getParent(); - const called = Node.isCallExpression(outer) && outer.getExpression() === parent; - if (info.kind === 'method') { - if (!called) add('method-as-value', member); - if (info.overloaded) add('overloaded-host-method', member); - host.set(member, 'method'); - } else if (info.kind === 'setter') { - add('this-write', member); - } else { - if (called) add('field-call', member); - host.set(member, 'getter'); - } - continue; - } - if (kind !== SyntaxKind.Identifier) continue; - // `typeof this` (its `this` is an identifier in a type query): with the - // identity port the value `this` beside it would read `this.facade` and - // the type would name the host, so the body stays as the polymorphic - // `this` type does. - if (ctx.identityPort && node.getText() === 'this' && Node.isTypeQuery(node.getParent())) add('this-type'); - if (node.getText() === 'arguments') { - const parent = node.getParent(); - const isName = Node.isPropertyAccessExpression(parent) && parent.getNameNode() === node; - if (!isName) add('arguments'); - } - const parent = node.getParent(); - let symbol; - if (Node.isShorthandPropertyAssignment(parent) && parent.getNameNode() === node) { - symbol = checker.getShorthandAssignmentValueSymbol(parent.compilerNode); - } else { - symbol = checker.getSymbolAtLocation(node.compilerNode); - } - if (!symbol || !symbol.declarations) continue; - for (const decl of symbol.declarations) { - if (decl.getSourceFile() !== ctx.sf.compilerNode) continue; - const ts = tm.ts; - const typePos = inTypePosition(tm, node, m); - if (ts.isParameter(decl) && decl.parent === m.compilerNode && region === body) paramsRead.add(node.getText()); - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const local = node.getText(); - const prev = imports.get(local); - imports.set(local, { value: Boolean(prev && prev.value) || !typePos }); - continue; - } - if (!isModuleScopeDecl(ts, decl)) continue; - // Lever (a) of ruling 6591753301: a module-scope name is imported — - // from the leaf when it moved there, from `engine.ts` (exported - // for it) when it stayed. Two things a module function cannot do: - // reach a non-public static of the class, and assign an import. - const declName = decl.name && ts.isIdentifier(decl.name) ? decl.name.text : node.getText(); - if (ts.isClassDeclaration(decl) && declName === (ctx.className ?? CLASS_NAME)) { - const access = node.getParent(); - const info = !typePos && Node.isPropertyAccessExpression(access) && access.getExpression() === node - ? ctx.statics.get(access.getName()) : null; - if (info) { - const member = access.getName(); - if (info.scope !== 'public') readsNonPublicStatic = true; - const outer = access.getParent(); - const called = Node.isCallExpression(outer) && outer.getExpression() === access; - const block = (tag) => { if (!routeBlockers.includes(tag)) routeBlockers.push(tag); }; - if (isWritten(tm, access) || info.kind === 'setter') block(`static-write: ${member}`); - if (info.kind === 'method' && !called) block(`static-as-value: ${member}`); - if (info.kind === 'method' && info.overloaded) block(`overloaded-static: ${member}`); - if (info.kind !== 'method' && called) block(`static-field-call: ${member}`); - classStatics.set(member, info.kind === 'method' ? 'method' : 'getter'); - } else { - classOther = true; - } - } - if (!typePos && isWritten(tm, node)) add('module-write', declName); - const prev = moduleRefs.get(declName); - moduleRefs.set(declName, { value: Boolean(prev && prev.value) || !typePos }); - } - } - } - - const binding = ctx.scope.bindings.get(name); - // A hand-series seam stub calls the `engine-*` import of its own name; a - // method that only shares the name (`ObjectRepository#count` beside the - // hand-series `count`) and never reads that import is not one. - if (binding && binding.kind === 'import' && SEAM_SPECIFIER.test(binding.specifier) && imports.has(name)) add('already-moved', binding.specifier); - for (const p of params) { - const pn = p.getName(); - if (pn === 'host' || /^(read|write)[A-Z]/.test(pn)) add('parameter-shadows', pn); - } - // A body that reads a non-public static takes the route; what the route - // cannot carry keeps it on the class. (A module another mover routes - // applies the same to every mover in it: `plan`.) - if (readsNonPublicStatic) { - for (const tag of routeBlockers) add(tag); - if (classOther) add('static-route-conflict'); - } - return result(); -} - -/** - * The fields of the class a strict compiler requires the constructor to - * assign (TS2564 when no constructor statement does): an instance property - * with a declared type, no initializer, no `?` and no `!`, whose type node is - * not `any`, `unknown` or a union naming `undefined`. Judged on the type - * node's text alone, so a type that admits `undefined` through an alias counts - * as required, which only ever keeps more on the class. - */ -function requiredFieldsOf(tm, cls) { - const { SyntaxKind } = tm; - const out = new Set(); - for (const p of cls.getProperties()) { - if (p.isStatic() || p.hasInitializer() || p.hasQuestionToken() || p.hasExclamationToken()) continue; - const t = p.getTypeNode(); - if (!t) continue; - const k = t.getKind(); - if (k === SyntaxKind.AnyKeyword || k === SyntaxKind.UnknownKeyword) continue; - if (k === SyntaxKind.UnionType && t.getTypeNodes().some((u) => u.getKind() === SyntaxKind.UndefinedKeyword)) continue; - out.add(p.getName()); - } - return out; -} - -/** The marker R8 leaves in the constructor's facet body where it kept a statement on the class. */ -const r8MarkerText = (field, fn) => `// ${MARK} R8: \`this.${field}\` is assigned on the class (\`${fn}\`).`; - -/** The facet member that returns the value R8 keeps a constructor assignment of `field` reading. */ -const r8FnName = (field) => `${CTOR_FACET_MEMBER}${field[0].toUpperCase()}${field.slice(1)}`; - -/** The facet member a moved constructor body becomes. */ -const CTOR_FACET_MEMBER = 'construct'; - -/** Is `name` one a moved constructor's facet member takes (`construct`, or R8's `constructF`)? */ -const isCtorFacetName = (name) => name === CTOR_FACET_MEMBER || new RegExp(`^${CTOR_FACET_MEMBER}[A-Z_$]`).test(name); - -/** - * R8 (#30020), definite-assignment wiring. A strict compiler accepts a field - * the constructor must assign (`requiredFieldsOf`) only when a constructor - * statement assigns it, so moving that statement into a facet is a TS2564 - * (and a TS2565 at every read after it). R8 keeps the assignment on the class - * and moves its right side: each LEADING statement of the body that is - * exactly `this.F = EXPR;`, F required, EXPR reading no `this` and no - * top-level name of `engine.ts` (its parameters, imports and globals only), - * stays as `this.F = Facet.constructF(params);`, and `constructF` returns - * EXPR. The facet body holds a marker line in its place, which the undo turns - * back into the statement. Any other write to a required field (after another - * statement, nested, or with a right side R8 cannot carry) keeps the - * constructor whole: `definite-assignment`. - * - * Returns `{ r8: [{ field, fn, start, end, exprText, imports, params }], reasons }`. - */ -function definiteAssignmentsOf(tm, ctx, ctor) { - const { Node, SyntaxKind } = tm; - const required = requiredFieldsOf(tm, ctx.cls); - const r8 = []; - const reasons = []; - const body = ctor.getBody(); - if (!body || required.size === 0) return { r8, reasons }; - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - const ts = tm.ts; - const carried = (stmt) => { - if (!Node.isExpressionStatement(stmt)) return null; - const e = stmt.getExpression(); - if (!Node.isBinaryExpression(e) || e.getOperatorToken().getKind() !== SyntaxKind.EqualsToken) return null; - const left = e.getLeft(); - if (!Node.isPropertyAccessExpression(left) || left.getExpression().getKind() !== SyntaxKind.ThisKeyword) return null; - const field = left.getName(); - if (!required.has(field)) return null; - const expr = e.getRight(); - if (stmt.getText() !== `this.${field} = ${expr.getText()};`) return null; - const imports = new Map(); - const params = new Set(); - for (const n of [expr, ...expr.getDescendants()]) { - const k = n.getKind(); - if (k === SyntaxKind.ThisKeyword || k === SyntaxKind.SuperKeyword) return null; - if (k !== SyntaxKind.Identifier) continue; - if (n.getText() === 'arguments') return null; - const symbol = checker.getSymbolAtLocation(n.compilerNode); - for (const decl of symbol?.declarations ?? []) { - if (decl.getSourceFile() !== ctx.sf.compilerNode) continue; - if (ts.isParameter(decl) && decl.parent === ctor.compilerNode) { params.add(n.getText()); continue; } - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const prev = imports.get(n.getText()); - imports.set(n.getText(), { value: Boolean(prev && prev.value) || !inTypePosition(tm, n, ctor) }); - continue; - } - if (isModuleScopeDecl(ts, decl)) return null; - } - } - if (ctx.members.has(r8FnName(field))) return null; - return { field, fn: r8FnName(field), start: stmt.getStart(), end: stmt.getEnd(), exprText: expr.getText(), imports, params }; - }; - const statements = body.getStatements(); - let i = 0; - for (; i < statements.length; i += 1) { - const hit = carried(statements[i]); - if (!hit) break; - r8.push(hit); - } - for (const st of statements.slice(i)) { - for (const pa of [st, ...st.getDescendants()].filter((n) => Node.isPropertyAccessExpression(n))) { - if (pa.getExpression().getKind() !== SyntaxKind.ThisKeyword || thisContainer(tm, pa.getExpression()) !== ctor) continue; - if (required.has(pa.getName()) && isWritten(tm, pa)) { - const tag = `definite-assignment: ${pa.getName()}`; - if (!reasons.includes(tag)) reasons.push(tag); - } - } - } - return { r8, reasons }; -} - -/** - * R3 (#30020): the fields a computed key `this[k]` can name, when `k`'s type - * is a string literal or a union of them and each one names a field of the - * class; null otherwise, and the body stays. - */ -function literalFieldKeys(ctx, checker, key) { - if (!key) return null; - const type = checker.getTypeAtLocation(key.compilerNode); - const parts = type.isUnion() ? type.types : [type]; - const keys = []; - for (const t of parts) { - if (!t.isStringLiteral()) return null; - const info = ctx.members.get(t.value); - if (!info || info.kind !== 'field') return null; - keys.push(t.value); - } - return keys.length > 0 ? [...new Set(keys)].sort() : null; -} - -/** The name of the class's non-public instance member `pa` reads, or null. */ -function foreignNonPublicMember(tm, ctx, checker, pa) { - const ts = tm.ts; - const nameNode = pa.getNameNode(); - if (!tm.Node.isIdentifier(nameNode)) return null; - const symbol = checker.getSymbolAtLocation(nameNode.compilerNode); - for (const decl of symbol?.declarations ?? []) { - const owner = ts.isParameter(decl) && decl.parent && ts.isConstructorDeclaration(decl.parent) ? decl.parent.parent : decl.parent; - if (owner !== ctx.cls.compilerNode) continue; - const flags = ts.getCombinedModifierFlags(decl); - if (flags & ts.ModifierFlags.Static) continue; - if (flags & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) return nameNode.getText(); - } - return null; -} - -/** - * R9 (#30020): a method keyed by a symbol binding, `[NAME]` where NAME is a - * binding of `engine.ts`'s module scope spelled SCREAMING_SNAKE, moves into the - * facet member named NAME in camelCase (`[SEED_USER_GRANTS]` -> - * `seedUserGrants`, the name the hand move of `[APP_AUTHORED_HOOK_API]` took). - * Its stub keeps the key; only the facet member is renamed. Null for any other - * name. - */ -function symbolKeyOf(tm, ctx, m) { - const { Node } = tm; - const nameNode = m.getNameNode(); - if (!Node.isComputedPropertyName(nameNode)) return null; - const expr = nameNode.getExpression(); - if (!Node.isIdentifier(expr)) return null; - const key = expr.getText(); - if (!ctx.scope.bindings.has(key) || !/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$/.test(key)) return null; - return { key, facetName: key.toLowerCase().replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase()) }; -} - -function isModuleScopeDecl(ts, decl) { - if (ts.isVariableDeclaration(decl)) { - const statement = decl.parent && decl.parent.parent; - return Boolean(statement && ts.isVariableStatement(statement) && ts.isSourceFile(statement.parent)); - } - if (ts.isBindingElement(decl)) { - let n = decl; - while (n && !ts.isVariableDeclaration(n)) n = n.parent; - return Boolean(n && isModuleScopeDecl(ts, n)); - } - return Boolean(decl.parent && ts.isSourceFile(decl.parent)) && - (ts.isFunctionDeclaration(decl) || ts.isClassDeclaration(decl) || ts.isInterfaceDeclaration(decl) || - ts.isTypeAliasDeclaration(decl) || ts.isEnumDeclaration(decl) || ts.isModuleDeclaration(decl)); -} - -// ── The plan ───────────────────────────────────────────────────────────────── - -/** `engine-transactions-section.ts` -> `TransactionsSectionHost`. */ -function hostNameOf(moduleFile) { - const slug = moduleFile.replace(/^engine-/, '').replace(/\.ts$/, ''); - return `${slug.split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join('')}Host`; -} - -/** `engine-transactions-section.ts` -> `TransactionsSectionFacet`: the stateless class the bodies move into. */ -function facetNameOf(moduleFile) { - return hostNameOf(moduleFile).replace(/Host$/, 'Facet'); -} - -/** `engine-transactions-section.ts` -> `transactionsSectionHost`: the module's `FacetHost` in `HOSTS_MODULE`. */ -function hostVarOf(moduleFile) { - const name = hostNameOf(moduleFile); - return `${name[0].toLowerCase()}${name.slice(1)}`; -} - -/** The object the class fills with forwarders to the statics the facets read, and its type. */ -const STATICS_NAME = `${CLASS_NAME}Statics`; -const STATICS_HOST_NAME = `${CLASS_NAME}StaticsHost`; -/** How a routed facet module names the class as a type: `ObjectQL` there is `ObjectQLStatics`. */ -const CLASS_TYPE_ALIAS = `${CLASS_NAME}Class`; - -/** The placeholder above a moved public or protected body: its docblock stays on the class. */ -const placeholderDoc = (name, className = CLASS_NAME) => `/** The body of \`${className}#${name}\`; the method's docblock there is its contract. */`; - -/** - * The statics block `engine.ts` carries for the routed facets: the type and - * the object ahead of the class, and the static block at the end of the class - * that fills the object. `kinds` maps each routed static to `method` (a - * forwarder that calls it on the class) or `getter` (read when read). Pure: - * `verify` rebuilds both texts from the base class and compares them. - */ -function staticsTexts(kinds) { - const members = [...kinds.keys()].sort(); - const ahead = [ - `// ${MARK} The statics of \`${CLASS_NAME}\` its facet modules read, private ones included, as`, - `// the class declares them (an indexed access on the class). The static block at the end of`, - `// the class fills \`${STATICS_NAME}\` with forwarders: a method is called on the class at`, - '// call time, a field or accessor is read when the body reads it. A facet module imports', - `// \`${STATICS_NAME}\` AS \`${CLASS_NAME}\`, so each moved body reads \`${CLASS_NAME}.x\` unedited;`, - '// `index.ts` re-exports neither, so neither reaches the package.', - `export interface ${STATICS_HOST_NAME} {`, - ...members.map((n) => ` readonly ${n}: (typeof ${CLASS_NAME})['${n}'];`), - '}', - `export const ${STATICS_NAME} = {} as ${STATICS_HOST_NAME};`, - ].join('\n'); - const block = [ - ` // ${MARK} Fills \`${STATICS_NAME}\` (declared above the class) for the facet modules.`, - ' static {', - ` Object.defineProperties(${STATICS_NAME}, {`, - ...members.map((n) => (kinds.get(n) === 'method' - ? ` ${n}: { value: (...args: Parameters) => ${CLASS_NAME}.${n}(...args) },` - : ` ${n}: { get: () => ${CLASS_NAME}.${n} },`)), - ' });', - ' }', - ].join('\n'); - return { ahead, block }; -} - -/** - * The facet hosts (#30051): `HOSTS_MODULE`'s text, and the static block at the - * end of the class that installs one host factory per facet into it. `facets` - * lists each facet module whose bodies read the class, with `members` (member - * -> `method` | `getter`, the union over its bodies) and `written` (the fields - * a body assigns). The host is the module's whole `
Host`, so every - * stub of the facet hands its body the same object, which carries every - * member any body of the facet reads (a `Pick` of it is what each body's - * `this` names). Each member forwards as the per-call literal did: a method - * as a closure that calls it on the engine at call time, a field or accessor - * as a getter read when the body reads it, a written field with a setter that - * assigns it on the engine. So a spy or subclass override installed after the - * host was built is still the one reached, and the only thing a body can tell - * apart is that two calls see the same host object, which no moved body can - * observe: a body that reads `this` bare stays on the class (`bare-this`). - * Pure: `verify` rebuilds both texts from the head's host interfaces and the - * base class, and compares them. - */ -function hostsTexts(facets) { - const sorted = [...facets].sort((a, b) => (a.moduleFile < b.moduleFile ? -1 : a.moduleFile > b.moduleFile ? 1 : 0)); - const module = [ - '// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.', - '', - '/**', - ` * ${MARK} The host of each facet of \`${CLASS_NAME}\`, built ONCE per engine (#30051):`, - ` * what every stub of a facet hands that facet's bodies as \`this\`, in place of`, - ' * a host literal built on every call. Each `FacetHost` below is filled by the', - ` * factory \`${CLASS_NAME}\`'s static block installs, the one place that can read`, - ' * the class\'s private members; the host is built on the first call that needs', - ' * it and kept for the engine\'s life. A method goes as a closure that calls it', - ' * on the engine at call time, a field or accessor as a getter (and a setter', - ' * when a body assigns it), so a body reads and writes the engine exactly as', - ' * the per-call literal let it.', - ' *', - ` * Written by \`${SCRIPT}\`; it imports types only, so it forms no`, - ' * evaluation cycle and is evaluated before the class whichever module loads', - ' * first. `index.ts` re-exports nothing from this module.', - ' */', - '', - `import type { ${CLASS_NAME} } from './engine.js';`, - ...sorted.map((f) => `import type { ${hostNameOf(f.moduleFile)} } from './${f.moduleFile.replace(/\.ts$/, '.js')}';`), - '', - `/** One facet's host for each engine: built on first use, kept for the engine's life. */`, - `export class ${HOSTS_CLASS} {`, - ` private readonly hosts = new WeakMap<${CLASS_NAME}, H>();`, - ` private build: ((engine: ${CLASS_NAME}) => H) | undefined;`, - '', - ' constructor(private readonly facet: string) {}', - '', - ` /** Called once, from \`${CLASS_NAME}\`'s static block. */`, - ` install(build: (engine: ${CLASS_NAME}) => H): void {`, - ' this.build = build;', - ' }', - '', - ' /** The host of `engine`, built on first use. */', - ` of(engine: ${CLASS_NAME}): H {`, - ' let host = this.hosts.get(engine);', - ' if (host === undefined) {', - ' if (this.build === undefined) {', - ` throw new Error(\`\${this.facet}: ${CLASS_NAME} has not installed its host factory\`);`, - ' }', - ' host = this.build(engine);', - ' this.hosts.set(engine, host);', - ' }', - ' return host;', - ' }', - '}', - '', - ...sorted.map((f) => `export const ${hostVarOf(f.moduleFile)} = new ${HOSTS_CLASS}<${hostNameOf(f.moduleFile)}>('${facetNameOf(f.moduleFile)}');`), - '', - ].join('\n'); - const block = [ - ` // ${MARK} Installs each facet's host factory (\`${HOSTS_MODULE}\`): a static block adds`, - ' // no member to the class, so the published `.d.ts` does not move.', - ' static {', - ...sorted.flatMap((f) => [ - ` ${hostVarOf(f.moduleFile)}.install((engine) => ({`, - ...hostInstallLines(f.members, f.written), - ' }));', - ]), - ' }', - ].join('\n'); - return { module, block }; -} - -/** The member lines of one facet's host factory, in its install call: sorted, a getter's setter after it. */ -function hostInstallLines(members, written) { - return [...members.keys()].sort().flatMap((member) => { - if (members.get(member) === 'facade') return [FACADE_INSTALL_LINE]; - if (members.get(member) === 'getter') { - return [` get ${member}() { return engine.${member}; },`, - ...(written.has(member) ? [` set ${member}(v) { engine.${member} = v; },`] : [])]; - } - if (BOUND_HOST_METHODS.has(member)) return [` get ${member}() { return engine.${member}.bind(engine); },`]; - return [` ${member}: (...a) => engine.${member}(...a),`]; - }); -} - -/** Is `node` inside a JSDoc comment? A `{@link X}` there is prose, not a use. */ -function inJsDoc(tm, node) { - for (let n = node.compilerNode; n; n = n.parent) { - if (n.kind >= tm.SyntaxKind.FirstJSDocNode && n.kind <= tm.SyntaxKind.LastJSDocNode) return true; - } - return false; -} - -/** The statement of `sf` (a direct child of the source file) a declaration belongs to. */ -function topStatementOf(ts, decl) { - let n = decl; - while (n.parent && !ts.isSourceFile(n.parent)) n = n.parent; - return n.parent ? n : null; -} - -/** The names a top-level statement declares, or null when one is not a plain identifier. */ -function declaredNames(tm, st) { - const { Node } = tm; - if (Node.isVariableStatement(st)) { - const names = []; - for (const d of st.getDeclarations()) { - if (!Node.isIdentifier(d.getNameNode())) return null; - names.push(d.getName()); - } - return names; - } - if (Node.isFunctionDeclaration(st) || Node.isInterfaceDeclaration(st) || Node.isTypeAliasDeclaration(st)) { - return st.getName() ? [st.getName()] : null; - } - return null; -} - -/** - * Lever (b): read every top-level statement between the last import and the - * class, and decide which move whole into the leaf. A mover never names the - * class, an `engine-*` module's import, or a statement that stays — so the - * leaf it lands in never imports `engine.ts` back. Pure. - */ -function planTopLevel(tm, ctx) { - const { Node, SyntaxKind } = tm; - const ts = tm.ts; - const stmts = ctx.sf.getStatements(); - const clsIndex = stmts.indexOf(ctx.cls); - let lastImport = -1; - stmts.forEach((st, i) => { if (Node.isImportDeclaration(st)) lastImport = i; }); - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - const nameCount = new Map(); - for (const st of stmts) { - for (const n of declaredNames(tm, st) ?? []) nameCount.set(n, (nameCount.get(n) ?? 0) + 1); - } - const records = []; - const byStatement = new Map(); - for (let i = lastImport + 1; i < clsIndex; i += 1) { - const st = stmts[i]; - const names = declaredNames(tm, st); - const record = { - node: st, names: names ?? [], label: names ? names.join(', ') : `(${st.getKindName()})`, - exported: Node.isExportable(st) && st.isExported(), reasons: [], - deps: new Set(), imports: new Map(), - startLine: st.getStartLineNumber(true), lines: st.getEndLineNumber() - st.getStartLineNumber(true) + 1, - typeOnly: Node.isInterfaceDeclaration(st) || Node.isTypeAliasDeclaration(st), - }; - const add = (code, detail) => { - const tag = detail ? `${code}: ${detail}` : code; - if (!record.reasons.includes(tag)) record.reasons.push(tag); - }; - if (!names || (Node.isVariableStatement(st) && st.hasDeclareKeyword()) || - (Node.isFunctionDeclaration(st) && (!st.getBody() || st.hasDeclareKeyword()))) add('top-kind'); - for (const n of record.names) if ((nameCount.get(n) ?? 0) > 1) add('merged-declaration', n); - for (const n of record.names) if (Object.prototype.hasOwnProperty.call(ctx.pins, n)) add('path-reader', n); - const fullText = st.getFullText(); - for (const needle of Object.keys(ctx.needles)) if (fullText.includes(needle)) add('path-reader', JSON.stringify(needle)); - for (const node of st.getDescendantsOfKind(SyntaxKind.Identifier)) { - if (inJsDoc(tm, node)) continue; - const parent = node.getParent(); - const symbol = Node.isShorthandPropertyAssignment(parent) && parent.getNameNode() === node - ? checker.getShorthandAssignmentValueSymbol(parent.compilerNode) - : checker.getSymbolAtLocation(node.compilerNode); - if (!symbol || !symbol.declarations) continue; - for (const decl of symbol.declarations) { - if (decl.getSourceFile() !== ctx.sf.compilerNode) continue; - const typePos = inTypePosition(tm, node, st); - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const local = node.getText(); - const binding = ctx.scope.bindings.get(local); - if (binding && (SEAM_SPECIFIER.test(binding.specifier) || binding.specifier === './engine.js')) add('seam-import', local); - const prev = record.imports.get(local); - record.imports.set(local, { value: Boolean(prev && prev.value) || !typePos }); - continue; - } - if (!isModuleScopeDecl(ts, decl)) continue; - const owner = topStatementOf(ts, decl); - if (!owner || owner === st.compilerNode) continue; - if (owner === ctx.cls.compilerNode) { add('class-reference'); continue; } - record.deps.add(owner); - } - } - records.push(record); - byStatement.set(st.compilerNode, record); - } - // A mover may not name a statement that stays: close over the stayers until stable. - for (let changed = true; changed;) { - changed = false; - for (const r of records) { - if (r.reasons.length > 0) continue; - for (const owner of r.deps) { - const dep = byStatement.get(owner); - if (!dep || dep.reasons.length > 0) { - const depName = dep ? dep.label : (declaredNames(tm, ctx.sf.getStatements().find((s) => s.compilerNode === owner)) ?? ['?']).join(', '); - r.reasons.push(`needs-stayer: ${depName}`); - changed = true; - break; - } - } - } - } - const movers = records.filter((r) => r.reasons.length === 0); - const moverNames = new Map(); - for (const r of movers) for (const n of r.names) moverNames.set(n, r); - return { records, movers, moverNames }; -} - -/** - * Which moved top-level names the text that STAYS in `engine.ts` still - * reads, value or type: everything outside the moved statements and the moved - * method bodies, JSDoc excepted. Those are what `engine.ts` imports back - * from the leaf. - */ -function hostUsesOfMovers(tm, ctx, top, methodRecords) { - const { SyntaxKind } = tm; - const ts = tm.ts; - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - const skip = []; - for (const r of top.movers) skip.push([r.node.getFullStart(), r.node.getEnd()]); - for (const r of methodRecords) if (r.reasons.length === 0) skip.push([r.node.getBody().getStart(), r.node.getBody().getEnd()]); - const uses = new Map(); - for (const node of ctx.sf.getDescendantsOfKind(SyntaxKind.Identifier)) { - const at = node.getStart(); - if (skip.some(([a, b]) => at >= a && at < b)) continue; - if (inJsDoc(tm, node)) continue; - const name = node.getText(); - if (!top.moverNames.has(name)) continue; - const symbol = checker.getSymbolAtLocation(node.compilerNode); - if (!symbol || !symbol.declarations) continue; - const mover = top.moverNames.get(name); - if (!symbol.declarations.some((d) => topStatementOf(ts, d) === mover.node.compilerNode)) continue; - const typePos = inTypePosition(tm, node, ctx.sf); - const prev = uses.get(name); - uses.set(name, { value: Boolean(prev && prev.value) || !typePos }); - } - return uses; -} - -/** - * The class's statics: scope, and what a forwarder in `ObjectQLStatics` would - * be (a method forwards as a function; a field or accessor as a getter). - */ -function classStaticsOf(tm, cls) { - const { Node } = tm; - const statics = new Map(); - for (const m of cls.getMembers()) { - if (typeof m.isStatic === 'function' && m.isStatic() && typeof m.getName === 'function') { - const prev = statics.get(m.getName()); - const kind = Node.isMethodDeclaration(m) ? 'method' : Node.isSetAccessorDeclaration(m) ? (prev ? prev.kind : 'setter') - : Node.isGetAccessorDeclaration(m) ? 'getter' : 'field'; - statics.set(m.getName(), { - scope: typeof m.getScope === 'function' ? m.getScope() : 'public', kind, - overloaded: Node.isMethodDeclaration(m) && m.getOverloads().length > 0, - }); - } - } - return statics; -} - -/** - * Read `text` (an `engine.ts`) and decide, per method, where its body goes, - * and per top-level declaration ahead of the class, whether it moves to the - * leaf. Pure: the same text gives the same plan. - */ -function plan(tm, text, { - anchors = SECTION_ANCHORS, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES, classNeedles = CLASS_PATH_READER_NEEDLES, -} = {}) { - const sf = parse(tm, HOST_PATH, text); - const cls = sf.getClass(CLASS_NAME); - if (!cls) refuse(`no class ${CLASS_NAME} in ${HOST_BASENAME}`); - const sectionOf = readSections(cls, anchors); - const ctx = { text, sf, cls, members: instanceMembers(tm, cls), scope: moduleScope(tm, sf), statics: classStaticsOf(tm, cls), pins, needles, classNeedles }; - for (const n of [STATICS_NAME, STATICS_HOST_NAME, ...SECTION_ANCHORS.filter((row) => row[2]).map((row) => facetNameOf(row[2]))]) { - if (ctx.scope.bindings.has(n)) refuse(`${HOST_BASENAME} already binds ${n}, a name this script generates`); - } - const methodNames = new Set(cls.getMethods().map((m) => m.getName())); - const stalePins = Object.keys(pins).filter((n) => !methodNames.has(n) && !ctx.scope.bindings.has(n)); - if (stalePins.length > 0) refuse(`PATH_READER_PINS names what ${HOST_BASENAME} no longer declares: ${stalePins.join(', ')}`); - const staleNeedles = Object.keys(needles).filter((n) => !text.includes(n)); - if (staleNeedles.length > 0) refuse(`PATH_READER_NEEDLES names text ${HOST_BASENAME} no longer carries: ${staleNeedles.map((n) => JSON.stringify(n)).join(', ')}`); - const staleClassNeedles = Object.keys(classNeedles).filter((n) => !text.includes(n)); - if (staleClassNeedles.length > 0) refuse(`CLASS_PATH_READER_NEEDLES names text ${HOST_BASENAME} no longer carries: ${staleClassNeedles.map((n) => JSON.stringify(n)).join(', ')}`); - - const top = planTopLevel(tm, ctx); - - const records = []; - for (const m of cls.getMethods()) { - const startLine = m.getStartLineNumber(true); - const section = sectionOf(m); - const read = readMethod(tm, ctx, m); - const name = m.getName(); - if (!section) read.reasons.unshift('no-section'); - else if (section[2] === null) read.reasons.unshift('section-kept'); - const lineCount = m.getEndLineNumber() - startLine + 1; - const body = m.getBody(); - const bodyLines = body ? body.getEndLineNumber() - body.getStartLineNumber() + 1 : 0; - // Docblock ownership (ruling 6624345766 item 1): a PRIVATE method's - // docblock moves with its body; a public or protected one stays on the - // facade, where the published surface prints it. - const docStart = m.getStart(true); - const doc = m.getScope() === 'private' && docStart < m.getStart() ? text.slice(docStart, m.getStart()) : null; - const record = { - name, node: m, section: section ? section[1] : null, module: section ? section[2] : null, - startLine, lineCount, bodyLines, doc, docLines: doc ? doc.split('\n').length - 1 : 0, ...read, - }; - if (section && section[2]) { - for (const p of m.getParameters()) if (p.getName() === facetNameOf(section[2])) read.reasons.push(`parameter-shadows: ${p.getName()}`); - } - if (record.reasons.length === 0) record.stubLines = stubBody(record, record.module, ' ').split('\n').length; - records.push(record); - } - - // The private-static-through-host rule, per facet module: once one mover - // reads the statics through `ObjectQLStatics` (imported AS `ObjectQL`), - // every mover in that module does, so what the route cannot carry keeps a - // mover on the class. A router itself never carries a blocker (readMethod - // already kept it), so the set of routed modules is stable. - for (let changed = true; changed;) { - changed = false; - for (const movers of groupMovers(records).values()) { - if (!movers.some((r) => r.readsNonPublicStatic)) continue; - for (const r of movers) { - const extra = [...r.routeBlockers, ...(r.classOther ? ['static-route-conflict'] : [])].filter((t) => !r.reasons.includes(t)); - if (extra.length > 0) { r.reasons.push(...extra); changed = true; } - } - } - } - const modules = groupMovers(records); - const routedModules = new Set(); - const routedStatics = new Map(); - for (const [moduleFile, movers] of modules) { - if (!movers.some((r) => r.readsNonPublicStatic)) continue; - routedModules.add(moduleFile); - for (const r of movers) for (const [member, kind] of r.classStatics) routedStatics.set(member, kind); - } - for (const [moduleFile, movers] of modules) { - const facet = facetNameOf(moduleFile); - for (const r of movers) { - for (const local of [...r.imports.keys(), ...r.moduleRefs.keys()]) { - if (local === facet || local === hostNameOf(moduleFile) || local === CLASS_TYPE_ALIAS) { - refuse(`${moduleFile}: ${r.name} reads ${local}, a name this script generates in that module`); - } - } - } - } - const hostUses = hostUsesOfMovers(tm, ctx, top, records); - - // What each side imports across the cut: the section modules read moved - // names from the leaf and staying names from engine.ts (lever (a)); - // engine.ts reads moved names from the leaf. - const sectionLeafNames = new Set(); - const hostExportsForSections = new Map(); // staying name -> { value } - for (const movers of modules.values()) { - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - if (top.moverNames.has(n)) { sectionLeafNames.add(n); continue; } - if (n === CLASS_NAME || ctx.scope.exported.has(n)) continue; - const prev = hostExportsForSections.get(n); - hostExportsForSections.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - } - const leafExports = []; - for (const r of top.movers) { - if (r.exported) continue; - for (const n of r.names) if (hostUses.has(n) || sectionLeafNames.has(n)) leafExports.push(n); - } - return { sf, cls, ctx, records, modules, top, hostUses, leafExports, hostExportsForSections, routedModules, routedStatics }; -} - -/** Movers grouped by module, modules in the order their first member appears. */ -function groupMovers(records) { - const byModule = new Map(); - for (const r of records) { - if (r.reasons.length > 0 || !r.module) continue; - if (!byModule.has(r.module)) byModule.set(r.module, []); - byModule.get(r.module).push(r); - } - return byModule; -} - -// ── Generation ─────────────────────────────────────────────────────────────── - - -const byName = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0); -const leafSpecifier = () => `./${LEAF_MODULE.replace(/\.ts$/, '.js')}`; - -/** - * One `import` / `export` statement over `names`: on one line when it fits in - * 120 columns, else one name per wrapped run, two-space indented. - */ -function namedStatement(head, names, tail) { - const one = `${head} { ${names.join(', ')} }${tail}`; - if (one.length <= 120) return one; - const out = [`${head} {`]; - let line = ' '; - for (const n of names) { - if (line.length + n.length + 2 > 118 && line !== ' ') { out.push(line); line = ' '; } - line += ` ${n},`; - } - out.push(line); - out.push(`}${tail}`); - return out.join('\n'); -} - -/** - * `import { … }` and `import type { … }` from one specifier, values first. - * `styles` keeps a statement a hand edit left on one line (`'line'`) on one - * line, however long; the first pass's own form (`'wrap'`, the default) is - * `namedStatement`'s. - */ -function importPair(specifier, uses, styles = {}) { - const out = []; - const entries = [...uses.entries()].sort(byName); - const values = entries.filter(([, u]) => u.value).map(([n]) => n); - const types = entries.filter(([, u]) => !u.value).map(([n]) => n); - const stmt = (head, names, style) => (style === 'line' - ? `${head} { ${names.join(', ')} } from '${specifier}';` : namedStatement(head, names, ` from '${specifier}';`)); - if (values.length > 0) out.push(stmt('import', values, styles.value)); - if (types.length > 0) out.push(stmt('import type', types, styles.type)); - return out; -} - -/** - * The form each statement of a leaf or `./engine.js` import run is in: - * `'wrap'` when it is `namedStatement`'s, `'line'` when a hand edit grew it on - * one line past the wrap width (#30227 left one so), each with its names - * sorted; null when a statement is in neither form. A move renders the run - * back in the forms it read, and so does the undo, so neither rewraps a line - * the hand wrote. - */ -function runStyles(text, decls, specifier) { - const styles = {}; - if (specifier !== leafSpecifier() && specifier !== './engine.js') return styles; - for (const d of decls) { - const stmt = text.slice(d.start, d.end); - const type = stmt.startsWith('import type '); - const head = type ? 'import type' : 'import'; - const names = [...d.bindings.keys()].sort(); - const tail = ` from '${specifier}';`; - let style; - if (stmt === namedStatement(head, names, tail)) style = 'wrap'; - else if (stmt === `${head} { ${names.join(', ')} }${tail}`) style = 'line'; - else return null; - const key = type ? 'type' : 'value'; - if (styles[key]) return null; - styles[key] = style; - } - return styles; -} - -/** - * The import lines a module needs: engine.ts's own imports it uses, in - * engine.ts's import order; then the moved top-level names, from the leaf; - * then what stayed in engine.ts (lever (a)), including the class. - */ -function importLines(scope, users, { needsHost = false, moduleRefs = new Map(), leafNames = new Map(), routed = false, className = CLASS_NAME } = {}) { - const bySpecifier = new Map(); - for (const r of users) { - for (const [local, use] of r.imports) { - const b = scope.bindings.get(local); - if (!b || b.kind !== 'import') refuse(`import binding ${local} not found`); - if (!bySpecifier.has(b.specifier)) bySpecifier.set(b.specifier, new Map()); - const slot = bySpecifier.get(b.specifier); - const prev = slot.get(local); - slot.set(local, { ...b, value: Boolean(prev && prev.value) || (use.value && !b.typeOnly) }); - } - } - const out = []; - const specifiers = [...bySpecifier.keys()].sort((a, b) => scope.importOrder.get(a) - scope.importOrder.get(b)); - for (const specifier of specifiers) out.push(...specifierImportLines(specifier, bySpecifier.get(specifier))); - const fromLeaf = new Map(); - const fromHost = new Map(); - for (const [n, use] of moduleRefs) (leafNames.has(n) ? fromLeaf : fromHost).set(n, use); - if (routed) { - // The private-static-through-host rule: `ObjectQL.x` in a moved body reads - // the forwarder object; the host interface names the class by an alias. - fromHost.delete(CLASS_NAME); - fromHost.set(`${STATICS_NAME} as ${CLASS_NAME}`, { value: true }); - if (needsHost) fromHost.set(`${CLASS_NAME} as ${CLASS_TYPE_ALIAS}`, { value: false }); - } else if (needsHost && !fromHost.has(className)) fromHost.set(className, { value: false }); - out.push(...importPair(leafSpecifier(), fromLeaf)); - out.push(...importPair('./engine.js', fromHost)); - return out; -} - -/** - * The import lines of one package specifier in a facet module, from its - * bindings (local -> { form, imported, value }): the value statement, then a - * type-only default, a namespace, then the type-only names, each list sorted. - */ -function specifierImportLines(specifier, bindings) { - const out = []; - const entries = [...bindings.entries()].sort(byName); - const named = (value) => entries - .filter(([, e]) => e.form === 'named' && e.value === value) - .map(([local, e]) => (e.imported === local ? local : `${e.imported} as ${local}`)); - const def = entries.find(([, e]) => e.form === 'default'); - const ns = entries.find(([, e]) => e.form === 'namespace'); - const valueNamed = named(true); - const defValue = def && def[1].value ? def[0] : null; - if (defValue || valueNamed.length > 0) { - const parts = [defValue, valueNamed.length > 0 ? `{ ${valueNamed.join(', ')} }` : null].filter(Boolean); - out.push(`import ${parts.join(', ')} from '${specifier}';`); - } - if (def && !def[1].value) out.push(`import type ${def[0]} from '${specifier}';`); - if (ns) out.push(`import ${ns[1].value ? '' : 'type '}* as ${ns[0]} from '${specifier}';`); - const typeNamed = named(false); - if (typeNamed.length > 0) out.push(`import type { ${typeNamed.join(', ')} } from '${specifier}';`); - return out; -} - -/** `text` wrapped into ` * ` comment lines no wider than `width`. */ -function wrapComment(words, width = 80) { - const lines = []; - let line = ' *'; - for (const w of words) { - if (line.length + 1 + w.length > width && line !== ' *') { lines.push(line); line = ' *'; } - line += ` ${w}`; - } - if (line !== ' *') lines.push(line); - return lines; -} - -function paramsText(m) { - return m.getParameters().map((p) => p.getText()); -} - -function forwardList(m) { - return m.getParameters().map((p) => (p.isRestParameter() ? `...${p.getName()}` : p.getName())); -} - -/** A facet module header's import paragraph: values imported from `engine.ts` (lever (a)), or types only. */ -const VALUES_CYCLE_PARA = [ - ' * Values that stayed in `engine.ts` are imported from it (lever (a) of', - ' * ruling 6591753301); every use is inside a function body, so the import', - ' * cycle is never read at evaluation time. `index.ts` re-exports nothing from', - ' * this module.', -].join('\n'); -const TYPES_CYCLE_PARA = [ - ' * The module imports `engine.ts` for types only, so the two modules form no', - ' * evaluation cycle. `index.ts` re-exports nothing from this module.', -].join('\n'); - -/** - * A routed facet module's header paragraph on the statics route: what - * `ObjectQL` names there. The first pass writes it for a module it routes, and - * the fourth pass's R10 (#30020) for one it reroutes. - */ -const STATICS_PARA = [ - ` * \`${CLASS_NAME}\` here is \`${STATICS_NAME}\` (imported AS \`${CLASS_NAME}\`): forwarders to the`, - ' * statics the bodies read, private ones included, which the class fills in a', - ` * static block; the class as a type is \`${CLASS_TYPE_ALIAS}\`.`, -].join('\n'); - -/** Does a facet module import a VALUE from `./engine.js`? */ -const importsEngineValues = (text) => /^import \{[^}]*\} from '\.\/engine\.js';$/m.test(text); - -/** - * A facet module's header paragraph made to say what its `./engine.js` lines - * import (R4 of #30020: a move that brings the first value import switches - * it, and the undo switches it back). Refuses a header carrying neither form. - */ -function withCyclePara(text, file) { - const values = importsEngineValues(text); - const [from, to] = values ? [TYPES_CYCLE_PARA, VALUES_CYCLE_PARA] : [VALUES_CYCLE_PARA, TYPES_CYCLE_PARA]; - if (text.includes(to)) return text; - const at = text.indexOf(from); - if (at < 0 || text.indexOf(from, at + 1) >= 0) refuse(`${file}: its header carries no single import paragraph as the first pass writes one`); - return text.slice(0, at) + to + text.slice(at + from.length); -} - -function moduleText(moduleFile, title, movers, scope, leafNames, routed = false) { - const hostName = hostNameOf(moduleFile); - const facet = facetNameOf(moduleFile); - const classType = routed ? CLASS_TYPE_ALIAS : CLASS_NAME; - const hostMembers = new Map(); - const written = new Set(); - for (const r of movers) for (const [member, kind] of r.host) hostMembers.set(member, kind); - for (const r of movers) for (const member of r.writes) written.add(member); - const needsHost = hostMembers.size > 0; - const moduleRefs = new Map(); - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - const prev = moduleRefs.get(n); - moduleRefs.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - const readsHostValues = [...moduleRefs].some(([n, use]) => use.value && !leafNames.has(n)); - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push('/**'); - out.push(...moduleHeaderLines(title, movers.map((r) => r.name))); - out.push(' *'); - out.push(` * A MOVE, not a redesign. {@link ${facet}} is a stateless facet of \`ObjectQL\``); - out.push(' * (ruling 6624345766): each static method of it is the body of the `ObjectQL`'); - out.push(' * method of the same name exactly as it stood: not re-indented, not'); - out.push(' * formatted, not edited. The method stays on the class as a one-call stub with'); - out.push(' * its signature, so the published surface, an instance spy and a subclass'); - out.push(' * override are what they were. A public or protected method keeps its'); - out.push(' * docblock on the class, the contract; a private method\'s docblock moved here'); - out.push(' * with its body. The state stays on `ObjectQL`.'); - out.push(' *'); - if (needsHost) { - out.push(...wrapComment((`The bodies reach the class through {@link ${hostName}}: exactly the \`ObjectQL\` ` + - 'members they read, private ones included. Every stub hands its body, by a `.call`, the same host: ' + - `\`${hostVarOf(moduleFile)}\` in \`${HOSTS_MODULE}\`, built once per engine by the class's static block. ` + - 'Methods go as closures that call them on the engine at call time, so a subclass override or an ' + - 'instance spy is still the one reached; fields and accessors go as GETTERS, read when the body reads ' + - 'them, as they were on the class, and a field a body assigns goes with a SETTER that assigns it on ' + - 'the engine.').split(' '))); - } else { - out.push(' * No body reads an `ObjectQL` member, so each stub calls its body directly.'); - } - if (routed) { - out.push(' *'); - out.push(STATICS_PARA); - } - out.push(' *'); - out.push(readsHostValues ? VALUES_CYCLE_PARA : TYPES_CYCLE_PARA); - out.push(' */'); - out.push(''); - out.push(...importLines(scope, movers, { needsHost, moduleRefs, leafNames, routed })); - if (needsHost) { - out.push(''); - out.push('/**'); - out.push(` * The \`ObjectQL\` members the bodies of {@link ${facet}} read — every one of`); - out.push(' * them, and no other. Each is typed AS the class member (an indexed access on'); - out.push(' * the class), so a change to a member\'s signature on the class is a change'); - out.push(' * here too. `readonly` members are the getters; the others are fields a body'); - out.push(' * assigns.'); - out.push(' */'); - out.push(`export interface ${hostName} {`); - for (const member of [...hostMembers.keys()].sort()) { - // R1's identity port: only a fourth-pass mover reads it (R11 starts its facet with this text). - if (hostMembers.get(member) === 'facade') { out.push(facadeIfaceLine(classType)); continue; } - const ro = hostMembers.get(member) === 'getter' && !written.has(member); - out.push(` ${ro ? 'readonly ' : ''}${member}: ${classType}['${member}'];`); - } - out.push('}'); - } - out.push(''); - out.push(`/** The bodies of the "${title}" section of \`ObjectQL\`: a stateless facet, called by the class's stubs. */`); - out.push(`export class ${facet} {`); - movers.forEach((r, i) => { - if (i > 0) out.push(''); - out.push(facetMethodText(r, hostName)); - }); - out.push('}'); - out.push(''); - return out.join('\n'); -} - -/** The opening lines of a facet module's header docblock: its section's title and the names of its bodies. */ -/** - * A facet module's header sentence, wrapped. `tail` is the words a hand edit - * wrote after that sentence in the same paragraph (the fourth pass reads them - * back with `headerNamesOf` and carries them over unedited); the first pass - * writes none. - */ -function moduleHeaderLines(title, names, tail = []) { - const listed = names.map((n, i) => `\`${n}\`${i === names.length - 1 ? '' : ','}`); - return wrapComment([MARK, 'The', `"${title}"`, 'section', 'of', '`ObjectQL`:', 'the', 'bodies', 'of', - ...listed, ...HEADER_SENTENCE_END.trim().split(' '), ...tail]); -} - -/** The words that close a facet module's header sentence, after its list of names. */ -const HEADER_SENTENCE_END = ` moved out of \`engine.ts\` whole by \`${SCRIPT}\`.`; - -/** - * One facet member, as its module holds it: the method's docblock (a private - * one) or the placeholder, `static`, and the method's own parameters, return - * type and body text, with `this` a `Pick` of the host when the body reads it. - */ -function facetMethodText(r, hostName, className = CLASS_NAME) { - const m = r.node; - const picks = [...r.host.keys()].sort().map((k) => `'${k}'`).join(' | '); - const params = [...(r.host.size > 0 ? [`this: Pick<${hostName}, ${picks}>`] : []), ...paramsText(m)]; - const ret = m.getReturnTypeNode() ? `: ${m.getReturnTypeNode().getText()}` : ''; - const typeParams = m.getTypeParameters().length > 0 ? `<${m.getTypeParameters().map((t) => t.getText()).join(', ')}>` : ''; - return ` ${r.doc ?? `${placeholderDoc(r.name, className)}\n `}static ${m.isAsync() ? 'async ' : ''}${r.facetName ?? r.name}${typeParams}(${params.join(', ')})${ret} ${identityBodyText(m.getBody(), r.identity)}`; -} - -/** - * A method's body text with R1 applied (#30020): each bare `this` at the - * starts `identity` lists reads `this.facade`. No other byte changes, so the - * undo (`identityUndoText`) is the one inverse rewrite. - */ -function identityBodyText(body, identity = []) { - const start = body.getStart(); - let text = body.getText(); - for (const at of [...identity].sort((a, b) => b - a)) { - if (text.slice(at - start, at - start + 4) !== 'this') refuse(`identity port: no \`this\` at offset ${at}`); - text = `${text.slice(0, at - start)}this.${FACADE_MEMBER}${text.slice(at - start + 4)}`; - } - return text; -} - -/** - * R1's inverse, read off a facet member at head: its body text with each - * `this.facade` its own `this` reads back to a bare `this`. - */ -function identityUndoText(tm, fm) { - const { Node, SyntaxKind } = tm; - const body = fm.getBody(); - const start = body.getStart(); - let text = body.getText(); - const sites = body.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).filter((pa) => - pa.getExpression().getKind() === SyntaxKind.ThisKeyword && Node.isIdentifier(pa.getNameNode()) && - pa.getName() === FACADE_MEMBER && thisContainer(tm, pa.getExpression()) === fm); - for (const pa of sites.sort((a, b) => b.getStart() - a.getStart())) { - text = `${text.slice(0, pa.getStart() - start)}this${text.slice(pa.getEnd() - start)}`; - } - return text; -} - -/** - * The leaf: the moved top-level statements, each its base text exactly (its - * leading comments and blank lines included), in base order, after the - * imports they use; then one `export { … }` of the moved names base did not - * export and something outside the leaf now imports. - */ -function leafText(scope, top, leafExports) { - // The header is `//` lines, not a `/** */` docblock: the bundled `.d.ts` - // keeps a JSDoc block that leads a module's first statement, and a leaf - // bundled first would publish text the base did not carry (the pilot's - // measurement: 14 added lines in dist/index.d.ts). - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push(...wrapComment([MARK, 'The', 'top-level', 'declarations', 'ahead', 'of', '`ObjectQL`', 'in', '`engine.ts`', - 'that', 'moved', 'out', 'whole', 'by', `\`${SCRIPT}\``, '(lever', '(b)', 'of', 'ruling', - '6591753301).']).map((l) => l.replace(/^ \*/, '//'))); - out.push('//'); - out.push('// A MOVE, not a redesign: each declaration below is its `engine.ts` text'); - out.push('// exactly, with the comments above it, in the order it stood there. A LEAF:'); - out.push('// it imports neither `engine.ts` nor any `engine-*` module, so it is'); - out.push('// evaluated before the class and forms no cycle with it. `engine.ts`'); - out.push('// re-exports, by name, every declaration here it exported before, so every'); - out.push('// importer of `./engine.js` reads what it read.'); - out.push(''); - out.push(...importLines(scope, top.movers)); - let text = out.join('\n'); - for (const r of top.movers) text += r.node.getFullText(); - if (leafExports.length > 0) { - text += `\n\n// ${MARK} Declared above without \`export\`, and read by \`engine.ts\` or a section module.\n`; - text += `${namedStatement('export', [...leafExports].sort(), ';')}`; - } - return `${text}\n`; -} - -const DOC_MOVED = 'its docblock with it'; - -/** - * A stub's body: the marker line, then ONE call of the facet member of the - * same name. A body that reads the class is called with its facet's host, the - * one object per engine `HOSTS_MODULE` keeps (#30051), not a literal built per - * call. `node` is the method (base or head: the stub keeps its signature). - * Pure: `verify` rebuilds every stub with it and compares. - */ -function stubBody({ node, name, usesHost, docMoved }, moduleFile, closeIndent, mark = MARK) { - const ind = `${closeIndent} `; - const hostName = hostNameOf(moduleFile); - // A generic method calls its body INSTANTIATED with its own type - // parameters (`Function#call` alone would erase them). - const typeArgs = node.getTypeParameters().map((t) => t.getName()); - const fn = typeArgs.length > 0 ? `(${facetNameOf(moduleFile)}.${name}<${typeArgs.join(', ')}>)` : `${facetNameOf(moduleFile)}.${name}`; - const out = ['{']; - const args = forwardList(node).join(', '); - const doc = docMoved ? `, ${DOC_MOVED}` : ''; - if (!usesHost) { - out.push(`${ind}// ${mark} The body moved to \`${moduleFile}\`${doc}.`); - out.push(`${ind}return ${fn}(${args});`); - } else { - out.push(`${ind}// ${mark} The body moved to \`${moduleFile}\`${doc} (see \`${hostName}\`).`); - out.push(`${ind}return ${fn}.call(${hostVarOf(moduleFile)}.of(this)${args ? `, ${args}` : ''});`); - } - out.push(`${closeIndent}}`); - return out.join('\n'); -} - -/** The constructor's forwarded arguments: the parameters a moved part reads, in declaration order. */ -const ctorArgs = (node, read) => forwardList(node).filter((_, i) => read.has(node.getParameters()[i].getName())); - -/** - * A moved constructor's body (#30020 R8): the marker line, each statement R8 - * keeps (`this.F = Facet.constructF(…)`), then ONE call of the facet's - * `construct`. Gate wiring only: `this.x = ` and a - * forwarding call. Pure: `verify` rebuilds it and compares. - */ -function ctorStubBody({ node, usesHost, r8, paramsRead }, moduleFile, closeIndent, mark = MARK) { - const ind = `${closeIndent} `; - const facet = facetNameOf(moduleFile); - const out = ['{']; - out.push(usesHost - ? `${ind}// ${mark} The body moved to \`${moduleFile}\` (see \`${hostNameOf(moduleFile)}\`).` - : `${ind}// ${mark} The body moved to \`${moduleFile}\`.`); - for (const a of r8) out.push(`${ind}this.${a.field} = ${facet}.${a.fn}(${ctorArgs(node, a.params).join(', ')});`); - const args = ctorArgs(node, paramsRead).join(', '); - out.push(usesHost - ? `${ind}${facet}.${CTOR_FACET_MEMBER}.call(${hostVarOf(moduleFile)}.of(this)${args ? `, ${args}` : ''});` - : `${ind}${facet}.${CTOR_FACET_MEMBER}(${args});`); - out.push(`${closeIndent}}`); - return out.join('\n'); -} - -/** R8's facet member: the value the constructor statement R8 keeps on the class assigns. */ -function r8FnText(node, a, classType) { - const params = node.getParameters().filter((p) => a.params.has(p.getName())).map((p) => p.getText()); - return ` /** R8 (#30020): the value \`${CLASS_NAME}\`'s constructor assigns to \`${a.field}\`, a field only a constructor may assign. */\n` + - ` static ${a.fn}(${params.join(', ')}): ${classType}['${a.field}'] {\n return ${a.exprText};\n }`; -} - -/** - * The constructor's facet member: its parameters the body reads, `this` a - * `Pick` of the host when it reads the class, and its body with R1 applied and - * each statement R8 kept on the class replaced by a marker line. - */ -function ctorFacetText(r, hostName) { - const m = r.node; - const picks = [...r.host.keys()].sort().map((k) => `'${k}'`).join(' | '); - const params = [...(r.host.size > 0 ? [`this: Pick<${hostName}, ${picks}>`] : []), - ...m.getParameters().filter((p) => r.paramsRead.has(p.getName())).map((p) => p.getText())]; - const body = m.getBody(); - const start = body.getStart(); - const text = body.getText(); - const edits = []; - for (const at of r.identity) { - if (text.slice(at - start, at - start + 4) !== 'this') refuse(`identity port: no \`this\` at offset ${at}`); - edits.push({ start: at - start, end: at - start + 4, text: `this.${FACADE_MEMBER}` }); - } - for (const a of r.r8) edits.push({ start: a.start - start, end: a.end - start, text: r8MarkerText(a.field, a.fn) }); - return ` /** The body of \`${CLASS_NAME}\`'s constructor; the constructor there keeps its signature and docblock. */\n` + - ` static ${CTOR_FACET_MEMBER}(${params.join(', ')}): void ${applyOrderedEdits(text, edits)}`; -} - -/** The facet member texts a moved constructor becomes, in module order: R8's, then `construct`. */ -function ctorFacetTexts(r, hostName, classType) { - return [...r.r8.map((a) => r8FnText(r.node, a, classType)), ctorFacetText(r, hostName)]; -} - -/** The facets whose bodies read the class, as `hostsTexts` takes them, from the movers of each module. */ -function facetsOf(modules) { - const facets = []; - for (const [moduleFile, movers] of modules) { - const members = new Map(); - const written = new Set(); - for (const r of movers) for (const [member, kind] of r.host) members.set(member, kind); - for (const r of movers) for (const member of r.writes) written.add(member); - if (members.size > 0) facets.push({ moduleFile, members, written }); - } - return facets; -} - -/** - * Apply a plan to `text`. Returns `{ host, modules, pruned }`: the new - * `engine.ts`, a Map of module basename -> text (the leaf among them), and the - * import bindings the prune dropped. Pure. - */ -function generate(tm, text, planned) { - const { sf, ctx, modules, top, hostUses, leafExports, hostExportsForSections, routedModules, routedStatics } = planned; - const edits = []; - const importBlock = []; - if (top.movers.length > 0) { - const leafUses = new Map([...hostUses].filter(([n]) => top.moverNames.has(n))); - const lines = importPair(leafSpecifier(), leafUses); - if (lines.length > 0) { - importBlock.push(`\n// ${MARK} The top-level declarations that moved whole to \`${LEAF_MODULE}\`, as this file still reads them.`); - for (const l of lines) importBlock.push(`\n${l}`); - } - const reexports = top.movers.filter((r) => r.exported) - .flatMap((r) => r.names.map((n) => [n, r.typeOnly ? `type ${n}` : n])) - .sort(byName).map(([, spelled]) => spelled); - if (reexports.length > 0) { - importBlock.push(`\n// ${MARK} Re-exported by name, so every importer of \`./engine.js\` reads what it read.`); - importBlock.push(`\n${namedStatement('export', reexports, ` from '${leafSpecifier()}';`)}`); - } - for (const r of top.movers) edits.push({ start: r.node.getFullStart(), end: r.node.getEnd(), text: '' }); - } - for (const [moduleFile, movers] of modules) { - const title = movers[0].section; - const hostName = hostNameOf(moduleFile); - const anyHost = movers.some((r) => r.host.size > 0); - importBlock.push(`\n// ${MARK} ${title}: the methods of the same names below hand the bodies` + - `${anyHost ? ` what they read (\`${hostName}\`)` : ' their arguments'}.`); - importBlock.push(`\nimport { ${facetNameOf(moduleFile)} } from './${moduleFile.replace(/\.ts$/, '.js')}';`); - for (const r of movers) { - const body = r.node.getBody(); - const lineStart = text.lastIndexOf('\n', body.getEnd() - 1) + 1; - const closeIndent = text.slice(lineStart, body.getEnd() - 1); - if (!/^ *$/.test(closeIndent)) refuse(`${r.name}: the body's closing brace does not open its own line`); - if (r.host.size > 0 && r.node.getParameters().some((p) => p.getName() === hostVarOf(moduleFile))) { - refuse(`${r.name}: a parameter is named ${hostVarOf(moduleFile)}, which its stub reads as the facet's host`); - } - const stub = stubBody({ node: r.node, name: r.name, usesHost: r.host.size > 0, docMoved: Boolean(r.doc) }, moduleFile, closeIndent); - edits.push({ start: body.getStart(), end: body.getEnd(), text: stub }); - const asyncKw = r.node.getModifiers().find((x) => x.getKind() === tm.SyntaxKind.AsyncKeyword); - if (asyncKw) edits.push({ start: asyncKw.getStart(), end: r.node.getNameNode().getStart(), text: '' }); - if (r.doc) edits.push({ start: r.node.getStart(true), end: r.node.getStart(), text: '' }); - } - } - // After the class's last member: the static block that fills the statics - // forwarders, then the one that installs the facet hosts (one edit, so the - // two keep this order). - const tail = []; - if (routedStatics.size > 0) { - // The private-static-through-host rule: the forwarder object ahead of the - // class (ahead of its leading comments), the static block that fills it - // after the class's last member. - const { ahead, block } = staticsTexts(routedStatics); - edits.push({ start: ctx.cls.getFullStart(), end: ctx.cls.getFullStart(), text: `\n\n${ahead}` }); - tail.push(`\n\n${block}`); - } - const facets = facetsOf(modules); - const hosts = facets.length > 0 ? hostsTexts(facets) : null; - if (hosts) { - for (const f of facets) { - if (ctx.scope.bindings.has(hostVarOf(f.moduleFile))) refuse(`engine.ts already binds ${hostVarOf(f.moduleFile)}, the name of ${f.moduleFile}'s host`); - } - tail.push(`\n\n${hosts.block}`); - importBlock.push(`\n// ${MARK} The facets' hosts, one per engine, which the static block at the end of the class builds.`); - importBlock.push(`\n${namedStatement('import', facets.map((f) => hostVarOf(f.moduleFile)).sort(), ` from './${HOSTS_MODULE.replace(/\.ts$/, '.js')}';`)}`); - } - if (tail.length > 0) { - const last = ctx.cls.getMembers().at(-1); - edits.push({ start: last.getEnd(), end: last.getEnd(), text: tail.join('') }); - } - if (hostExportsForSections.size > 0) { - const spelled = [...hostExportsForSections.keys()].sort().map((n) => { - const st = ctx.sf.getStatements().find((s) => (declaredNames(tm, s) ?? []).includes(n)); - return st && (tm.Node.isInterfaceDeclaration(st) || tm.Node.isTypeAliasDeclaration(st)) ? `type ${n}` : n; - }); - importBlock.push(`\n// ${MARK} Exported for the section modules above, which import them (lever (a)); \`index.ts\` re-exports by name, so none reaches the package.`); - importBlock.push(`\n${namedStatement('export', spelled, ';')}`); - } - const lastImport = sf.getImportDeclarations().at(-1); - if (!lastImport) refuse('engine.ts has no import declaration to place the generated imports after'); - if (importBlock.length > 0) edits.push({ start: lastImport.getEnd(), end: lastImport.getEnd(), text: importBlock.join('') }); - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let out = text; - let floor = Infinity; - for (const e of edits) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - // The imports only moved text read are dropped (the package compiles with - // `noUnusedLocals`); `verify` recomputes the same prune from the head. - const pruned = pruneImports(tm, out, usedImportNames(tm, out)); - const moduleTexts = new Map(); - const leafNames = top.moverNames; - if (top.movers.length > 0) moduleTexts.set(LEAF_MODULE, leafText(ctx.scope, top, leafExports)); - for (const [moduleFile, movers] of modules) { - moduleTexts.set(moduleFile, moduleText(moduleFile, movers[0].section, movers, ctx.scope, leafNames, routedModules.has(moduleFile))); - } - if (hosts) moduleTexts.set(HOSTS_MODULE, hosts.module); - return { host: pruned.text, modules: moduleTexts, pruned: pruned.removed }; -} - -// ── The import prune ───────────────────────────────────────────────────────── - -/** Is `node` (a compiler node) inside a JSDoc comment? */ -function inJsDocNode(ts, node) { - for (let n = node; n; n = n.parent) { - if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode) return true; - } - return false; -} - -/** Is the identifier a property NAME (`a.NAME`, `{ NAME: … }`, a member name), not a reference? */ -function isPropertyNameIdentifier(ts, node) { - const p = node.parent; - if (!p) return false; - if (ts.isPropertyAccessExpression(p) && p.name === node) return true; - if ((ts.isPropertyAssignment(p) || ts.isPropertyDeclaration(p) || ts.isPropertySignature(p) || - ts.isMethodDeclaration(p) || ts.isMethodSignature(p) || ts.isGetAccessorDeclaration(p) || - ts.isSetAccessorDeclaration(p) || ts.isEnumMember(p)) && p.name === node) return true; - if (ts.isQualifiedName(p) && p.right === node) return true; - return false; -} - -/** - * The import bindings of an `engine.ts` that something outside its import - * declarations reads: a reference in code or a type, a local `export { … }`, - * or a JSDoc `{@link X}` / `@see X` name. Those JSDoc names count because the - * compiler's `noUnusedLocals` counts them; other JSDoc text and `//` comments - * do not. - */ -function usedImportNames(tm, text) { - const ts = tm.ts; - const sfm = parse(tm, HOST_PATH, text); - const sf = sfm.compilerNode; - const checker = sfm.getProject().getTypeChecker().compilerObject; - const used = new Set(); - const isImportDecl = (d) => d.getSourceFile() === sf && (ts.isImportSpecifier(d) || ts.isImportClause(d) || ts.isNamespaceImport(d)); - const leftmost = (name) => { - let n = name; - while (n && (ts.isQualifiedName(n) || ts.isPropertyAccessExpression(n) || n.kind === ts.SyntaxKind.JSDocMemberName)) { - n = ts.isQualifiedName(n) || n.kind === ts.SyntaxKind.JSDocMemberName ? n.left : n.expression; - } - return n && ts.isIdentifier(n) ? n : undefined; - }; - const visitDoc = (node) => { - const linkish = node.kind === ts.SyntaxKind.JSDocLink || node.kind === ts.SyntaxKind.JSDocLinkCode || - node.kind === ts.SyntaxKind.JSDocLinkPlain || node.kind === ts.SyntaxKind.JSDocNameReference; - if (linkish && node.name) { - const id = leftmost(node.name); - const symbol = id && checker.getSymbolAtLocation(id); - if (id && (symbol?.declarations ?? []).some(isImportDecl)) used.add(id.text); - } - if (Array.isArray(node.comment)) node.comment.forEach(visitDoc); - ts.forEachChild(node, visitDoc); - }; - const visit = (node) => { - if (ts.isImportDeclaration(node)) return; - for (const doc of node.jsDoc ?? []) visitDoc(doc); - if (ts.isExportDeclaration(node) && node.moduleSpecifier) return; - if (ts.isIdentifier(node) && !inJsDocNode(ts, node)) { - const parent = node.parent; - let symbol; - if (ts.isExportSpecifier(parent)) symbol = checker.getExportSpecifierLocalTargetSymbol(parent); - else if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) symbol = checker.getShorthandAssignmentValueSymbol(parent); - else if (!isPropertyNameIdentifier(ts, node)) symbol = checker.getSymbolAtLocation(node); - if ((symbol?.declarations ?? []).some(isImportDecl)) used.add(node.text); - } - ts.forEachChild(node, visit); - }; - visit(sf); - return used; -} - -/** - * Drop every import binding `used` lacks. A declaration left with no binding - * goes whole (its own text and the line break after it; the comments above it - * stay, unless `dropAttachedComments`: then the `//` lines directly above it, - * with no blank line between, go with it); one left with some keeps them, a - * one-line `{ … }` on one line, a multi-line one as one binding per line. - * Pure. Returns `{ text, removed }`. - */ -function pruneImports(tm, text, used, { dropAttachedComments = false } = {}) { - const ts = tm.ts; - const sf = parseSourceFile(HOST_PATH, text); - const edits = []; - const removed = []; - for (const st of sf.statements) { - if (!ts.isImportDeclaration(st) || !st.importClause) continue; - const clause = st.importClause; - const nb = clause.namedBindings; - const named = nb && ts.isNamedImports(nb) ? [...nb.elements] : []; - const dropDefault = Boolean(clause.name && !used.has(clause.name.text)); - const dropNs = Boolean(nb && ts.isNamespaceImport(nb) && !used.has(nb.name.text)); - const dropNamed = named.filter((e) => !used.has(e.name.text)); - if (!dropDefault && !dropNs && dropNamed.length === 0) continue; - if (dropDefault) removed.push(clause.name.text); - if (dropNs) removed.push(nb.name.text); - for (const e of dropNamed) removed.push(e.name.text); - const keepDefault = Boolean(clause.name && !dropDefault); - const keepNs = Boolean(nb && ts.isNamespaceImport(nb) && !dropNs); - const keepNamed = named.filter((e) => used.has(e.name.text)); - if (!keepDefault && !keepNs && keepNamed.length === 0) { - const end = text[st.getEnd()] === '\n' ? st.getEnd() + 1 : st.getEnd(); - let start = st.getStart(sf); - if (dropAttachedComments) { - // Walk up the `//` lines that touch the declaration (no blank line between). - for (;;) { - const prevEnd = start - 1; - if (prevEnd <= 0 || text[prevEnd] !== '\n') break; - const lineStart = text.lastIndexOf('\n', prevEnd - 1) + 1; - if (!/^\s*\/\/.*$/.test(text.slice(lineStart, prevEnd))) break; - start = lineStart; - } - } - edits.push({ start, end, text: '' }); - continue; - } - if (nb && ts.isNamedImports(nb) && dropNamed.length > 0) { - if (keepNamed.length === 0) { - edits.push({ start: clause.name.getEnd(), end: nb.getEnd(), text: '' }); - } else { - const one = !nb.getText(sf).includes('\n'); - const parts = keepNamed.map((e) => e.getText(sf)); - edits.push({ start: nb.getStart(sf), end: nb.getEnd(), text: one ? `{ ${parts.join(', ')} }` : `{\n${parts.map((x) => ` ${x},`).join('\n')}\n}` }); - } - } - if (dropNs) edits.push({ start: clause.name.getEnd(), end: nb.getEnd(), text: '' }); - if (dropDefault) edits.push({ start: clause.name.getStart(sf), end: nb.getStart(sf), text: '' }); - } - edits.sort((a, b) => b.start - a.start); - let out = text; - for (const e of edits) out = out.slice(0, e.start) + e.text + out.slice(e.end); - return { text: out, removed: removed.sort() }; -} - -// ── Proof 1: byte-identity ─────────────────────────────────────────────────── - -const sha256 = (text) => createHash('sha256').update(text).digest('hex'); - -/** - * Prove a split against its base, from the texts alone (it shares no state with - * `generate`): every generated function is its base method's text, every leaf - * declaration is its base statement's text, and undoing the split rebuilds the - * base `engine.ts` byte-for-byte, once the base's import bindings the head no - * longer reads are pruned from it. - * - * Undoing is: put each body back on its stub (and `async` back), drop the - * generated import / export statements, then splice the leaf's statements back - * between the statements that stayed — the interleaving read off the base by - * NAME only, so every byte of the result comes from the head or the leaf. - * - * The one edit the undo does not reverse by reading the head is the import - * prune: it is recomputed from the head (which import bindings does the head - * still read?) and applied to the base, and every binding it drops must occur - * in a moved body or a moved declaration, so a binding the head lost for any - * other reason fails. - * - * Returns `{ failures, moved, movedTop, pruned, linesBefore, linesAfter }`; no failure = proved. - */ -function verify(tm, baseText, headText, moduleTexts, { readSibling = null } = {}) { - const { Node } = tm; - const failures = []; - const moved = []; - const movedTop = []; - const baseSf = parse(tm, HOST_PATH, baseText); - const baseCls = baseSf.getClass(CLASS_NAME); - const headSf = parse(tm, HOST_PATH, headText); - const headCls = headSf.getClass(CLASS_NAME); - const none = { failures: [`no class ${CLASS_NAME} at base or head`], moved, movedTop, pruned: [], linesBefore: 0, linesAfter: 0 }; - if (!baseCls || !headCls) return none; - const prune = pruneImports(tm, baseText, usedImportNames(tm, headText)); - const target = prune.text; - - const modules = new Map(); - let leaf = null; - let hostsOnDisk = null; - for (const [file, text] of moduleTexts) { - if (!text.includes(MARK)) continue; - if (file === HOSTS_MODULE) { hostsOnDisk = text; continue; } - const sf = parse(tm, join(SRC_DIR, file), text); - if (file === LEAF_MODULE) { - const statements = []; - const stmts = sf.getStatements(); - // The generated header is leading trivia of the first statement when no - // import precedes it; a moved statement's text starts after it. - const headerEnd = text.indexOf('\n\n', text.indexOf(MARK)) + 1; - stmts.forEach((st, i) => { - if (Node.isImportDeclaration(st)) { - if (st.getModuleSpecifierValue() === './engine.js' || SEAM_SPECIFIER.test(st.getModuleSpecifierValue())) { - failures.push(`${file}: imports ${st.getModuleSpecifierValue()} — a leaf never imports engine.ts or an engine-* module`); - } - return; - } - if (i === stmts.length - 1 && Node.isExportDeclaration(st) && !st.getModuleSpecifier() && st.getFullText().includes(MARK)) return; - const names = declaredNames(tm, st); - if (!names) { failures.push(`${file}: a statement that is not a moved declaration: ${st.getText().slice(0, 60)}`); return; } - statements.push({ names, text: text.slice(Math.max(st.getFullStart(), headerEnd), st.getEnd()), node: st }); - }); - leaf = { file, sf, statements }; - if (readSibling) { - // The leaf's relative VALUE imports, followed on disk: none may reach - // engine.ts or an engine-* module. A type-only import is erased, so it - // forms no evaluation cycle and is not followed. - const seen = new Set(); - const queue = valueSpecifiers(text).map((spec) => [file, spec]); - while (queue.length > 0) { - const [from, spec] = queue.shift(); - let rel = relative(SRC_DIR, resolve(dirname(join(SRC_DIR, from)), spec.replace(/\.js$/, '.ts'))); - if (seen.has(rel)) continue; - seen.add(rel); - if (rel === HOST_BASENAME || /^engine-[a-z0-9-]+\.ts$/.test(rel)) { - failures.push(`${file}: reaches ${rel} through its value imports (from ${from}) — not a leaf`); - continue; - } - let sibling = readSibling(rel); - if (sibling === null) { - const index = rel.replace(/\.ts$/, '/index.ts'); - sibling = readSibling(index); - if (sibling !== null) rel = index; - } - if (sibling === null) continue; - for (const next of valueSpecifiers(sibling)) queue.push([rel, next]); - } - } - continue; - } - // A facet module: imports, the host interface, and ONE class, the facet, - // whose every member is a static method that is a moved body. - const fns = new Map(); - const facet = facetNameOf(file); - for (const st of sf.getStatements()) { - if (Node.isImportDeclaration(st)) continue; - if (Node.isInterfaceDeclaration(st) && st.getName() === hostNameOf(file)) continue; - if (Node.isClassDeclaration(st) && st.getName() === facet && !fns.size) { - for (const member of st.getMembers()) { - if (Node.isMethodDeclaration(member) && member.isStatic() && member.getBody() && !fns.has(member.getName())) fns.set(member.getName(), member); - else failures.push(`${file}: ${facet} has a member that is not a moved body: ${member.getText().slice(0, 60)}`); - } - continue; - } - failures.push(`${file}: a top-level statement that is neither an import, the host interface nor the facet class ${facet}: ${st.getText().slice(0, 60)}`); - } - modules.set(file, { sf, text, fns, claimed: new Set() }); - } - - const marker = new RegExp(`^\\{\\s*// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(engine-[a-z0-9-]+\\.ts)\`(, ${DOC_MOVED})?`); - const movedDocs = []; - const edits = []; - for (const m of headCls.getMethods()) { - const body = m.getBody(); - if (!body) continue; - const hit = marker.exec(body.getText()); - if (!hit) continue; - const name = m.getName(); - const mod = modules.get(hit[1]); - const fn = mod && mod.fns.get(name); - if (!fn) { failures.push(`${name}: its stub names ${hit[1]}, which has no function ${name}`); continue; } - mod.claimed.add(name); - // The stub itself is exactly what `stubBody` writes for this method: one - // call of the facet member of the same name, with the facet's own host - // when the body reads the class (#30051). - { - const lineStart = headText.lastIndexOf('\n', body.getEnd() - 1) + 1; - const closeIndent = headText.slice(lineStart, body.getEnd() - 1); - const usesHost = fn.getParameters().some((p) => p.getName() === 'this'); - const want = stubBody({ node: m, name, usesHost, docMoved: Boolean(hit[2]) }, hit[1], closeIndent); - if (body.getText() !== want) failures.push(`${name}: its stub is not the generated one-call stub (want ${JSON.stringify(want.split('\n').at(-2).trim())})`); - } - const base = baseCls.getMethods().find((x) => x.getName() === name && x.isStatic() === m.isStatic()); - if (!base || !base.getBody()) { failures.push(`${name}: no method of that name with a body at base`); continue; } - const fnParams = fn.getParameters().filter((p) => p.getName() !== 'this').map((p) => p.getText()); - const baseParams = base.getParameters().map((p) => p.getText()); - const same = { - body: fn.getBody().getText() === base.getBody().getText(), - params: JSON.stringify(fnParams) === JSON.stringify(baseParams), - returnType: (fn.getReturnTypeNode()?.getText() ?? null) === (base.getReturnTypeNode()?.getText() ?? null), - async: fn.isAsync() === base.isAsync(), - typeParameters: JSON.stringify(fn.getTypeParameters().map((t) => t.getText())) === JSON.stringify(base.getTypeParameters().map((t) => t.getText())), - static: m.isStatic() === base.isStatic(), - }; - // Docblock ownership: the facet member's leading text is the base - // method's docblock (the stub says so, and only a private method's), else - // exactly the placeholder; the undo puts a moved docblock back. - const lead = mod.text.slice(fn.getStart(true), fn.getStart()); - const docMoved = Boolean(hit[2]); - if (docMoved) { - if (m.getStart(true) !== m.getStart()) failures.push(`${name}: its stub says the docblock moved, but the class still carries one`); - if (m.getScope() !== 'private') failures.push(`${name}: a ${m.getScope()} method's docblock moved off the class (only a private one may)`); - edits.push({ start: m.getStart(), end: m.getStart(), text: lead }); - movedDocs.push(lead); - } else if (lead !== `${placeholderDoc(name)}\n `) { - failures.push(`${name}: the facet member's leading text is neither its moved docblock nor the placeholder`); - } - for (const [what, ok] of Object.entries(same)) if (!ok) failures.push(`${name}: the generated function's ${what} is not the base method's`); - moved.push({ - name, module: hit[1], bodySha: sha256(fn.getBody().getText()), baseBodySha: sha256(base.getBody().getText()), - lines: base.getBody().getEndLineNumber() - base.getBody().getStartLineNumber() + 1, text: fn.getText(), docMoved, ...same, - }); - edits.push({ start: body.getStart(), end: body.getEnd(), text: fn.getBody().getText() }); - if (fn.isAsync()) edits.push({ start: m.getNameNode().getStart(), end: m.getNameNode().getStart(), text: 'async ' }); - } - - // The statics route: the forwarder type and object ahead of the class and - // the static block that fills them must be exactly what `staticsTexts` - // writes for the statics the type names, each forwarded as the BASE class - // declares it (a method called, anything else read). Then the undo drops - // them. - const staticsHost = headSf.getInterface(STATICS_HOST_NAME); - const staticsVar = headSf.getVariableStatement(STATICS_NAME); - const markedBlocks = headCls.getMembers().filter((x) => Node.isClassStaticBlockDeclaration(x) && x.getFullText().includes(MARK)); - const hostsBlocks = markedBlocks.filter((x) => x.getFullText().includes(`// ${MARK} Installs`)); - const staticBlocks = markedBlocks.filter((x) => !hostsBlocks.includes(x)); - if (staticsHost || staticsVar || staticBlocks.length > 0) { - const kinds = new Map(); - for (const member of staticsHost ? staticsHost.getProperties() : []) { - const n = member.getName(); - const declared = baseCls.getMembers().filter((x) => typeof x.isStatic === 'function' && x.isStatic() && typeof x.getName === 'function' && x.getName() === n); - if (declared.length === 0) failures.push(`${STATICS_HOST_NAME}.${n}: the base class declares no static of that name`); - kinds.set(n, declared.some((x) => Node.isMethodDeclaration(x)) ? 'method' : 'getter'); - } - const { ahead, block } = staticsTexts(kinds); - const aheadAt = staticsHost ? headText.lastIndexOf(`// ${MARK} The statics of`, staticsHost.getStart()) : -1; - const aheadEnd = staticsVar ? staticsVar.getEnd() : -1; - if (!staticsHost || !staticsVar || aheadAt < 0 || headText.slice(aheadAt, aheadEnd) !== ahead) { - failures.push(`${STATICS_HOST_NAME} / ${STATICS_NAME} are not the generated forwarder declarations for the statics they name`); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', aheadAt), end: aheadEnd, text: '' }); - } - const blockAt = staticBlocks.length === 1 ? headText.lastIndexOf(` // ${MARK} Fills`, staticBlocks[0].getStart()) : -1; - if (staticBlocks.length !== 1 || blockAt < 0 || headText.slice(blockAt, staticBlocks[0].getEnd()) !== block) { - failures.push(`the class's static block is not the generated filler of ${STATICS_NAME} for the statics it names`); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', blockAt), end: staticBlocks[0].getEnd(), text: '' }); - } - } - for (const [file, mod] of modules) { - for (const name of mod.fns.keys()) if (!mod.claimed.has(name)) failures.push(`${file}: function ${name} has no stub on the class`); - } - - // The facet hosts (#30051): `HOSTS_MODULE` and the static block that - // installs the factories must be exactly what `hostsTexts` writes for the - // facets on disk, each member forwarded as the BASE class declares it (a - // method as a closure, anything else as a getter, a member the interface - // does not mark `readonly` with a setter too). Then the undo drops both. - const baseMembers = instanceMembers(tm, baseCls); - const facets = []; - for (const [file, mod] of modules) { - const iface = mod.sf.getInterface(hostNameOf(file)); - if (!iface) continue; - const members = new Map(); - const written = new Set(); - for (const p of iface.getProperties()) { - const n = p.getName(); - const info = baseMembers.get(n); - if (!info) { failures.push(`${file}: ${hostNameOf(file)}.${n} names no instance member of the base class`); continue; } - members.set(n, info.kind === 'method' ? 'method' : 'getter'); - if (info.kind !== 'method' && !p.isReadonly()) written.add(n); - } - facets.push({ moduleFile: file, members, written }); - } - if (facets.length > 0 || hostsOnDisk !== null || hostsBlocks.length > 0) { - const want = hostsTexts(facets); - if (hostsOnDisk !== want.module) failures.push(`${HOSTS_MODULE} is not the generated host module for the facets on disk`); - const blockAt = hostsBlocks.length === 1 ? headText.lastIndexOf(` // ${MARK} Installs`, hostsBlocks[0].getStart()) : -1; - if (hostsBlocks.length !== 1 || blockAt < 0 || headText.slice(blockAt, hostsBlocks[0].getEnd()) !== want.block) { - failures.push('the class\'s host static block is not the generated installer of the facet hosts'); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', blockAt), end: hostsBlocks[0].getEnd(), text: '' }); - } - } - const generatedSpecifier = (spec) => { - const hit = /^\.\/(engine-[a-z0-9-]+)\.js$/.exec(spec ?? ''); - return Boolean(hit && (modules.has(`${hit[1]}.ts`) || `${hit[1]}.ts` === HOSTS_MODULE || (leaf && `${hit[1]}.ts` === leaf.file))); - }; - for (const st of headSf.getStatements()) { - const drop = (Node.isImportDeclaration(st) && generatedSpecifier(st.getModuleSpecifierValue())) || - (Node.isExportDeclaration(st) && (st.getModuleSpecifier() - ? generatedSpecifier(st.getModuleSpecifierValue()) - : st.getFullText().includes(MARK))); - if (drop) edits.push({ start: st.getFullStart(), end: st.getEnd(), text: '' }); - } - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let rebuilt = headText; - for (const e of edits) rebuilt = rebuilt.slice(0, e.start) + e.text + rebuilt.slice(e.end); - - if (leaf) { - // Splice the leaf back, in the order the base interleaves it by NAME. - const restSf = parse(tm, HOST_PATH, rebuilt); - const rest = restSf.getStatements(); - const queue = [...leaf.statements]; - const baseStmts = parse(tm, HOST_PATH, target).getStatements(); - let j = 0; - let assembled = rest.length > 0 ? rebuilt.slice(0, rest[0].getFullStart()) : ''; - for (const b of baseStmts) { - const names = declaredNames(tm, b); - const key = names ? names.join(',') : null; - if (queue.length > 0 && key !== null && queue[0].names.join(',') === key) { - const l = queue.shift(); - assembled += l.text; - const same = l.text === b.getFullText(); - if (!same) failures.push(`${leaf.file}: ${key} is not its base text (leading comments included)`); - movedTop.push({ - name: key, lines: b.getEndLineNumber() - b.getStartLineNumber(true) + 1, - sha: sha256(l.text), baseSha: sha256(b.getFullText()), same, exported: Node.isExportable(b) && b.isExported(), - }); - continue; - } - if (j >= rest.length) { failures.push(`undoing the split runs out of head statements at base ${key ?? b.getKindName()}`); break; } - assembled += rest[j].getFullText(); - j += 1; - } - if (queue.length > 0) failures.push(`${leaf.file}: ${queue.map((q) => q.names.join(',')).join('; ')} not placed — out of base order or not in the base`); - if (rest.length > 0) assembled += rebuilt.slice(rest[rest.length - 1].getEnd()); - rebuilt = assembled; - } - - const movedText = [...moved.map((m) => m.text), ...movedDocs, ...(leaf ? leaf.statements.map((s) => s.text) : [])].join('\n'); - for (const n of prune.removed) { - if (!new RegExp(`(^|[^\\w$])${n.replace(/\$/g, '\\$')}($|[^\\w$])`).test(movedText)) { - failures.push(`the head dropped the import \`${n}\`, which no moved body or declaration reads`); - } - } - if (rebuilt !== target) { - const a = rebuilt.split('\n'); - const b = target.split('\n'); - let i = 0; - while (i < Math.max(a.length, b.length) && a[i] === b[i]) i += 1; - failures.push(`undoing the split does not rebuild the base engine.ts (its unread imports pruned): first difference at line ${i + 1}` + - `\n rebuilt: ${JSON.stringify(a[i] ?? '')}\n base: ${JSON.stringify(b[i] ?? '')}`); - } - if (moved.length === 0 && movedTop.length === 0) failures.push('no moved method or declaration found: a proof over nothing is not a proof'); - return { failures, moved, movedTop, pruned: prune.removed, linesBefore: lineCount(baseText), linesAfter: lineCount(headText), - routedStatics: staticsHost ? staticsHost.getProperties().length : 0 }; -} - -/** Lines as `wc -l` counts them: newline characters. */ -function lineCount(text) { - return text.split('\n').length - 1; -} - -// ── Reports ────────────────────────────────────────────────────────────────── - -function planReport(planned) { - const out = []; - const bySection = new Map(); - for (const r of planned.records) { - const key = r.section ?? '(above the first anchor)'; - if (!bySection.has(key)) bySection.set(key, []); - bySection.get(key).push(r); - } - let movedMethods = 0; - let movedLines = 0; - let movedSaved = 0; - const reasonCounts = new Map(); - for (const [section, rs] of bySection) { - const movers = rs.filter((r) => r.reasons.length === 0); - const lines = movers.reduce((n, r) => n + r.bodyLines, 0); - const saved = movers.reduce((n, r) => n + r.bodyLines - r.stubLines, 0); - movedMethods += movers.length; - movedLines += lines; - movedSaved += saved; - out.push(`§ ${section} -> ${rs[0].module ?? '(stays)'}: ${movers.length}/${rs.length} methods move ` + - `(${lines} body lines out, ${lines - saved} stub lines in)`); - for (const r of rs) { - if (r.reasons.length === 0) out.push(` move ${r.name} (body ${r.bodyLines} -> stub ${r.stubLines})`); - else out.push(` stay ${r.name} (${r.lineCount}) — ${r.reasons.join('; ')}`); - for (const reason of r.reasons) { - const code = reason.split(':')[0]; - reasonCounts.set(code, (reasonCounts.get(code) ?? 0) + 1); - } - } - } - out.push(''); - out.push(`total: ${movedMethods}/${planned.records.length} methods move into ${planned.modules.size} module(s): ` + - `${movedLines} body lines out, ${movedLines - movedSaved} stub lines in, plus ${2 * planned.modules.size} import lines`); - out.push(`stay reasons (a method may carry several): ${[...reasonCounts].sort((a, b) => b[1] - a[1]).map(([c, n]) => `${c} ${n}`).join(', ')}`); - const top = planned.top; - out.push(''); - out.push(`§ top-level declarations ahead of the class -> ${LEAF_MODULE}: ${top.movers.length}/${top.records.length} move`); - const topReasons = new Map(); - for (const r of top.records) { - if (r.reasons.length === 0) out.push(` move ${r.label} (${r.lines})${r.exported ? ' [exported, re-exported]' : ''}`); - else out.push(` stay ${r.label} (${r.lines}) — ${r.reasons.join('; ')}`); - for (const reason of r.reasons) { - const code = reason.split(':')[0]; - topReasons.set(code, (topReasons.get(code) ?? 0) + 1); - } - } - const topLines = top.movers.reduce((n, r) => n + r.lines, 0); - out.push(`top-level total: ${top.movers.length}/${top.records.length} declarations move (${topLines} lines with their docblocks); ` + - `stay reasons: ${[...topReasons].sort((a, b) => b[1] - a[1]).map(([c, n]) => `${c} ${n}`).join(', ') || 'none'}`); - out.push(`lever (a): ${planned.hostExportsForSections.size} staying name(s) exported for the section modules` + - `${planned.hostExportsForSections.size ? ` (${[...planned.hostExportsForSections.keys()].sort().join(', ')})` : ''}; ` + - `${planned.leafExports.length} leaf name(s) exported beside the base exports`); - return out.join('\n'); -} - -function treeHash(files) { - const h = createHash('sha256'); - for (const [name, text] of [...files].sort(([a], [b]) => (a < b ? -1 : 1))) h.update(`${name}\0${sha256(text)}\n`); - return h.digest('hex'); -} - -function printVerify(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - const identical = v.moved.filter((m) => m.body && m.params && m.returnType && m.async).length; - const identicalTop = v.movedTop.filter((m) => m.same).length; - console.log(`byte-identity: ${identical}/${v.moved.length} moved bodies identical to base (body, parameters, return type, async); ` + - `${identicalTop}/${v.movedTop.length} moved top-level declarations identical to base (leading comments included); ` + - `engine.ts ${v.linesBefore} -> ${v.linesAfter} lines; undoing the split ${v.failures.some((f) => f.startsWith('undoing')) ? 'does NOT' : 'does'} rebuild the base byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved text reads are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -function gitShow(ref, path) { - return execFileSync('git', ['show', `${ref}:${path}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28 }); -} - -/** A file under `engine.ts`'s directory by its relative path, or null when there is none. */ -function readSibling(rel) { - const p = join(SRC_DIR, rel); - return existsSync(p) ? readFileSync(p, 'utf8') : null; -} - -function generatedModulesOnDisk() { - const out = new Map(); - for (const file of [LEAF_MODULE, HOSTS_MODULE, ...SECTION_ANCHORS.map((row) => row[2])]) { - if (!file) continue; - const p = join(SRC_DIR, file); - if (existsSync(p)) out.set(file, readFileSync(p, 'utf8')); - } - return out; -} - -// ── The scoped classes (#30052) ────────────────────────────────────────────── -// -// The second pass. `engine.ts` declares two more classes after `ObjectQL`: -// `ObjectRepository` (what `ctx.api.object(name)` returns) and `ScopedContext` -// (what a hook reaches as `ctx.api`). This pass facades them with the same cut -// pattern, the same stay rules and the same byte-identity proof as the first, -// and touches nothing else: its input is the `engine.ts` the first pass left -// (any `main` after #29986), it is proved against that file, and so it is -// re-run on the latest `main` at landing, never rebased. -// -// - ONE section per class, so one facet module per class (`SCOPED_CLASSES`). -// Each `engine-.ts` holds one stateless facet class whose static -// methods are the moved bodies, unedited, with `this` typed as a `Pick` of -// the class's host interface, the members typed AS the class members. -// - One host per INSTANCE (`SCOPED_HOSTS_MODULE`), built on the first call that -// needs it by the factory the class's own static block installs, and kept -// for the instance's life: `#30051`'s shape, keyed by the instance instead -// of the engine. The module imports types only, for the same reason the -// first pass's host module does. -// - Neither class declares a static or a top-level declaration ahead of it, -// so no statics route and no leaf: a body that reads a non-public static -// stays (`private-static`). A body that reads a private member off another -// instance stays too (`foreign-private`): the class body may, a module -// function may not. - -const SCOPED_CARD = '#30052'; - -/** The marker every file and stub the second pass writes carries; its proof keys on it. */ -const SCOPED_MARK = `[${SCOPED_CARD} codemod]`; - -/** The scoped classes, in file order: the class, its facet module, its section title. */ -const SCOPED_CLASSES = Object.freeze([ - ['ObjectRepository', 'engine-object-repository.ts', 'Repository bound to one object and one execution context'], - ['ScopedContext', 'engine-scoped-context.ts', 'Scoped execution context: repositories, elevation, transactions'], -]); - -/** The module that holds each scoped facet's per-instance host. Types-only imports, like `HOSTS_MODULE`. */ -const SCOPED_HOSTS_MODULE = 'engine-scoped-hosts.ts'; -const SCOPED_HOSTS_CLASS = 'InstanceHost'; - -/** The marker line of a scoped stub: the module it names, and whether the docblock moved. */ -const scopedStubMarker = () => new RegExp( - `^\\{\\s*// ${SCOPED_MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(engine-[a-z0-9-]+\\.ts)\`(, ${DOC_MOVED})?`); - -/** - * Read `text` (an `engine.ts` whose scoped classes are not split yet) and - * decide, per method of each scoped class, whether its body moves. Pure. - */ -function planScoped(tm, text, { classes = SCOPED_CLASSES } = {}) { - const sf = parse(tm, HOST_PATH, text); - const scope = moduleScope(tm, sf); - const targets = []; - for (const [className, moduleFile, title] of classes) { - const cls = sf.getClass(className); - if (!cls) refuse(`no class ${className} in ${HOST_BASENAME}`); - for (const n of [facetNameOf(moduleFile), hostNameOf(moduleFile), hostVarOf(moduleFile), SCOPED_HOSTS_CLASS]) { - if (scope.bindings.has(n)) refuse(`${HOST_BASENAME} already binds ${n}, a name this script generates`); - } - const ctx = { text, sf, cls, className, members: instanceMembers(tm, cls), scope, statics: scopedStaticsOf(tm, cls), pins: {}, needles: {}, classNeedles: {} }; - const records = []; - for (const m of cls.getMethods()) { - const read = readMethod(tm, ctx, m); - if (read.readsNonPublicStatic) read.reasons.push('private-static'); - const name = m.getName(); - for (const p of m.getParameters()) { - if (p.getName() === facetNameOf(moduleFile) || p.getName() === hostVarOf(moduleFile)) read.reasons.push(`parameter-shadows: ${p.getName()}`); - } - const startLine = m.getStartLineNumber(true); - const body = m.getBody(); - const docStart = m.getStart(true); - const doc = m.getScope() === 'private' && docStart < m.getStart() ? text.slice(docStart, m.getStart()) : null; - const record = { - name, node: m, className, section: title, module: moduleFile, startLine, - lineCount: m.getEndLineNumber() - startLine + 1, - bodyLines: body ? body.getEndLineNumber() - body.getStartLineNumber() + 1 : 0, - doc, docLines: doc ? doc.split('\n').length - 1 : 0, ...read, - }; - if (record.reasons.length === 0) { - record.stubLines = stubBody({ node: m, name, usesHost: read.host.size > 0, docMoved: Boolean(doc) }, moduleFile, ' ', SCOPED_MARK).split('\n').length; - } - records.push(record); - } - const movers = records.filter((r) => r.reasons.length === 0); - for (const r of movers) { - for (const local of [...r.imports.keys(), ...r.moduleRefs.keys()]) { - if (local === facetNameOf(moduleFile) || local === hostNameOf(moduleFile)) { - refuse(`${moduleFile}: ${r.name} reads ${local}, a name this script generates in that module`); - } - } - } - targets.push({ className, moduleFile, title, cls, records, movers }); - } - // Lever (a): a staying top-level name of engine.ts a moved body reads, which - // engine.ts does not export yet, is exported for the facet modules. - const hostExports = new Map(); - for (const t of targets) { - for (const r of t.movers) { - for (const [n, use] of r.moduleRefs) { - if (scope.exported.has(n)) continue; - const prev = hostExports.get(n); - hostExports.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - } - return { sf, scope, targets, hostExports }; -} - -/** A scoped facet's host members (member -> `method` | `getter`) and the fields its bodies assign. */ -function scopedFacetOf(t) { - const members = new Map(); - const written = new Set(); - for (const r of t.movers) for (const [member, kind] of r.host) members.set(member, kind); - for (const r of t.movers) for (const member of r.writes) written.add(member); - return { className: t.className, moduleFile: t.moduleFile, members, written }; -} - -/** A scoped class's statics (the second pass routes none; a body reading a non-public one stays). */ -function scopedStaticsOf(tm, cls) { - const statics = new Map(); - for (const m of cls.getMembers()) { - if (typeof m.isStatic === 'function' && m.isStatic() && typeof m.getName === 'function') { - statics.set(m.getName(), { scope: typeof m.getScope === 'function' ? m.getScope() : 'public', - kind: tm.Node.isMethodDeclaration(m) ? 'method' : 'field', overloaded: false }); - } - } - return statics; -} - -/** - * A scoped class's host factory lines, one member each in name order: a - * method as a closure called on the instance, a field or accessor as a getter - * (and a setter when a body assigns it), the identity port (#30020) as the - * instance itself. - */ -function scopedInstallLines(members, written) { - return [...members.keys()].sort().flatMap((member) => { - const kind = members.get(member); - if (kind === 'facade') return [SCOPED_FACADE_INSTALL_LINE]; - if (kind === 'getter') { - return [` get ${member}() { return instance.${member}; },`, - ...(written.has(member) ? [` set ${member}(v) { instance.${member} = v; },`] : [])]; - } - return [` ${member}: (...a) => instance.${member}(...a),`]; - }); -} - -/** The opening sentence of a scoped facet module's header: what moved, by the second pass. */ -function scopedHeaderSentence(className, title, names) { - return wrapComment([SCOPED_MARK, 'The', ...`"${title}"`.split(' '), 'section:', 'the', 'bodies', 'of', `\`${className}\`'s`, 'methods', - ...names.map((n, i) => `\`${n}\`${i === names.length - 1 ? '' : ','}`), 'moved', 'out', 'of', '`engine.ts`', 'whole', 'by', `\`${SCRIPT}\``, - '(its', 'second', 'pass).']); -} - -/** - * The per-instance hosts: `SCOPED_HOSTS_MODULE`'s text, and, per class, the - * static block at the end of the class that installs its facet's factory. - * Each member forwards as the first pass's hosts do: a method as a closure - * called on the instance at call time, a field or accessor as a getter, and a - * field a body assigns with a setter too. Pure: the proof rebuilds both from - * the head's host interfaces and the base classes, and compares. - */ -function scopedHostsTexts(facets) { - const sorted = [...facets].sort((a, b) => (a.moduleFile < b.moduleFile ? -1 : a.moduleFile > b.moduleFile ? 1 : 0)); - const classNames = [...new Set(sorted.map((f) => f.className))].sort(); - const module = [ - '// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.', - '', - '/**', - ` * ${SCOPED_MARK} The host of each facet of ${classNames.map((c) => `\`${c}\``).join(' and ')},`, - ' * built ONCE per instance: what every stub of a facet hands that facet\'s', - ' * bodies as `this`. Each host below is filled by the factory its class\'s', - ' * static block installs, the one place that can read the class\'s private', - ' * members; the host is built on the first call that needs it and kept for', - ' * the instance\'s life. A method goes as a closure that calls it on the', - ' * instance at call time, a field or accessor as a getter (and a setter when', - ' * a body assigns it), so a body reads and writes the instance exactly as', - ' * the method did.', - ' *', - ` * Written by \`${SCRIPT}\` (its second pass). It imports`, - ' * types only, so it forms no evaluation cycle and is evaluated before the', - ' * classes whichever module loads first. `index.ts` re-exports nothing from', - ' * this module.', - ' */', - '', - `import type { ${classNames.join(', ')} } from './engine.js';`, - ...sorted.map((f) => `import type { ${hostNameOf(f.moduleFile)} } from './${f.moduleFile.replace(/\.ts$/, '.js')}';`), - '', - '/** One facet\'s host for each instance of its class: built on first use, kept for the instance\'s life. */', - `export class ${SCOPED_HOSTS_CLASS} {`, - ' private readonly hosts = new WeakMap();', - ' private build: ((instance: E) => H) | undefined;', - '', - ' constructor(private readonly facet: string, private readonly owner: string) {}', - '', - ' /** Called once, from the owning class\'s static block. */', - ' install(build: (instance: E) => H): void {', - ' this.build = build;', - ' }', - '', - ' /** The host of `instance`, built on first use. */', - ' of(instance: E): H {', - ' let host = this.hosts.get(instance);', - ' if (host === undefined) {', - ' if (this.build === undefined) {', - ' throw new Error(`${this.facet}: ${this.owner} has not installed its host factory`);', - ' }', - ' host = this.build(instance);', - ' this.hosts.set(instance, host);', - ' }', - ' return host;', - ' }', - '}', - '', - ...sorted.map((f) => `export const ${hostVarOf(f.moduleFile)} = new ${SCOPED_HOSTS_CLASS}<${f.className}, ${hostNameOf(f.moduleFile)}>` + - `('${facetNameOf(f.moduleFile)}', '${f.className}');`), - '', - ].join('\n'); - const blocks = new Map(); - for (const f of sorted) { - blocks.set(f.className, [ - ` // ${SCOPED_MARK} Installs the host of \`${facetNameOf(f.moduleFile)}\` (\`${SCOPED_HOSTS_MODULE}\`): a static`, - ' // block adds no member to the class, so the published `.d.ts` does not move.', - ' static {', - ` ${hostVarOf(f.moduleFile)}.install((instance) => ({`, - ...scopedInstallLines(f.members, f.written), - ' }));', - ' }', - ].join('\n')); - } - return { module, blocks }; -} - -/** A scoped facet module: the header, the imports, the host interface, the facet class. Pure. */ -function scopedModuleText(t, scope) { - const { className, moduleFile, title, movers } = t; - const hostName = hostNameOf(moduleFile); - const facet = facetNameOf(moduleFile); - const { members: hostMembers, written } = scopedFacetOf(t); - const needsHost = hostMembers.size > 0; - const moduleRefs = new Map(); - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - const prev = moduleRefs.get(n); - moduleRefs.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - const readsHostValues = [...moduleRefs.values()].some((use) => use.value); - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push('/**'); - out.push(...scopedHeaderSentence(className, title, movers.map((r) => r.name))); - out.push(' *'); - out.push(...wrapComment((`A MOVE, not a redesign. {@link ${facet}} is a stateless facet of \`${className}\`: each static ` + - `method of it is the body of the \`${className}\` method of the same name exactly as it stood: not re-indented, not ` + - 'formatted, not edited. The method stays on the class as a one-call stub with its signature, so the published ' + - 'surface, an instance spy and a subclass override are what they were. A public method keeps its docblock on the ' + - `class, the contract; a private method's docblock moved here with its body. The state stays on \`${className}\`.`).split(' '))); - out.push(' *'); - if (needsHost) { - out.push(...wrapComment((`The bodies reach the instance through {@link ${hostName}}: exactly the \`${className}\` ` + - 'members they read, private ones included. Every stub hands its body, by a `.call`, the same host: ' + - `\`${hostVarOf(moduleFile)}\` in \`${SCOPED_HOSTS_MODULE}\`, built once per instance by the class's static block. ` + - 'Methods go as closures that call them on the instance at call time; fields and accessors go as GETTERS, read when ' + - 'the body reads them, and a field a body assigns goes with a SETTER that assigns it on the instance.').split(' '))); - } else { - out.push(` * No body reads a \`${className}\` member, so each stub calls its body directly.`); - } - out.push(' *'); - if (readsHostValues) { - out.push(' * Values declared in `engine.ts` are imported from it (lever (a) of'); - out.push(' * ruling 6591753301); every use is inside a function body, so the import'); - out.push(' * cycle is never read at evaluation time. `index.ts` re-exports nothing from'); - out.push(' * this module.'); - } else { - out.push(' * The module imports `engine.ts` for types only, so the two modules form no'); - out.push(' * evaluation cycle. `index.ts` re-exports nothing from this module.'); - } - out.push(' */'); - out.push(''); - out.push(...importLines(scope, movers, { needsHost, moduleRefs, leafNames: new Map(), className })); - if (needsHost) { - out.push(''); - out.push('/**'); - out.push(...wrapComment((`The \`${className}\` members the bodies of {@link ${facet}} read — every one of them, and ` + - 'no other. Each is typed AS the class member (an indexed access on the class), so a change to a member\'s ' + - 'signature on the class is a change here too. `readonly` members are the getters; the others are fields a body ' + - 'assigns.').split(' '))); - out.push(' */'); - out.push(`export interface ${hostName} {`); - for (const member of [...hostMembers.keys()].sort()) { - const ro = hostMembers.get(member) === 'getter' && !written.has(member); - out.push(` ${ro ? 'readonly ' : ''}${member}: ${className}['${member}'];`); - } - out.push('}'); - } - out.push(''); - out.push(`/** The bodies of \`${className}\`'s methods: a stateless facet, called by the class's stubs. */`); - out.push(`export class ${facet} {`); - movers.forEach((r, i) => { - const m = r.node; - const picks = [...r.host.keys()].sort().map((k) => `'${k}'`).join(' | '); - const params = [...(r.host.size > 0 ? [`this: Pick<${hostName}, ${picks}>`] : []), ...paramsText(m)]; - const ret = m.getReturnTypeNode() ? `: ${m.getReturnTypeNode().getText()}` : ''; - if (i > 0) out.push(''); - const typeParams = m.getTypeParameters().length > 0 ? `<${m.getTypeParameters().map((tp) => tp.getText()).join(', ')}>` : ''; - out.push(` ${r.doc ?? `${placeholderDoc(r.name, className)}\n `}static ${m.isAsync() ? 'async ' : ''}${r.name}${typeParams}(${params.join(', ')})${ret} ${m.getBody().getText()}`); - }); - out.push('}'); - out.push(''); - return out.join('\n'); -} - -/** - * Apply a scoped plan to `text`. Returns `{ host, modules, pruned }` as - * `generate` does. Pure. - */ -function generateScoped(tm, text, planned) { - const { sf, scope, targets, hostExports } = planned; - const edits = []; - const importBlock = []; - const facets = []; - for (const t of targets) { - if (t.movers.length === 0) continue; - const hostName = hostNameOf(t.moduleFile); - const anyHost = t.movers.some((r) => r.host.size > 0); - importBlock.push(`\n// ${SCOPED_MARK} ${t.title}: the methods of the same names on \`${t.className}\` hand the bodies` + - `${anyHost ? ` what they read (\`${hostName}\`)` : ' their arguments'}.`); - importBlock.push(`\nimport { ${facetNameOf(t.moduleFile)} } from './${t.moduleFile.replace(/\.ts$/, '.js')}';`); - for (const r of t.movers) { - const body = r.node.getBody(); - const lineStart = text.lastIndexOf('\n', body.getEnd() - 1) + 1; - const closeIndent = text.slice(lineStart, body.getEnd() - 1); - if (!/^ *$/.test(closeIndent)) refuse(`${t.className}#${r.name}: the body's closing brace does not open its own line`); - const stub = stubBody({ node: r.node, name: r.name, usesHost: r.host.size > 0, docMoved: Boolean(r.doc) }, t.moduleFile, closeIndent, SCOPED_MARK); - edits.push({ start: body.getStart(), end: body.getEnd(), text: stub }); - const asyncKw = r.node.getModifiers().find((x) => x.getKind() === tm.SyntaxKind.AsyncKeyword); - if (asyncKw) edits.push({ start: asyncKw.getStart(), end: r.node.getNameNode().getStart(), text: '' }); - if (r.doc) edits.push({ start: r.node.getStart(true), end: r.node.getStart(), text: '' }); - } - const facet = scopedFacetOf(t); - if (facet.members.size > 0) facets.push(facet); - } - const hosts = facets.length > 0 ? scopedHostsTexts(facets) : null; - if (hosts) { - for (const f of facets) { - const t = targets.find((x) => x.className === f.className); - const last = t.cls.getMembers().at(-1); - edits.push({ start: last.getEnd(), end: last.getEnd(), text: `\n\n${hosts.blocks.get(f.className)}` }); - } - importBlock.push(`\n// ${SCOPED_MARK} The scoped facets' hosts, one per instance, which each class's static block builds.`); - importBlock.push(`\n${namedStatement('import', facets.map((f) => hostVarOf(f.moduleFile)).sort(), ` from './${SCOPED_HOSTS_MODULE.replace(/\.ts$/, '.js')}';`)}`); - } - if (hostExports.size > 0) { - const spelled = [...hostExports.keys()].sort().map((n) => { - const st = sf.getStatements().find((s) => (declaredNames(tm, s) ?? []).includes(n)); - return st && (tm.Node.isInterfaceDeclaration(st) || tm.Node.isTypeAliasDeclaration(st)) ? `type ${n}` : n; - }); - importBlock.push(`\n// ${SCOPED_MARK} Exported for the scoped facet modules above (lever (a)); \`index.ts\` re-exports by name, so none reaches the package.`); - importBlock.push(`\n${namedStatement('export', spelled, ';')}`); - } - const lastImport = sf.getImportDeclarations().at(-1); - if (!lastImport) refuse('engine.ts has no import declaration to place the generated imports after'); - if (importBlock.length > 0) edits.push({ start: lastImport.getEnd(), end: lastImport.getEnd(), text: importBlock.join('') }); - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let out = text; - let floor = Infinity; - for (const e of edits) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - const pruned = pruneImports(tm, out, usedImportNames(tm, out)); - const moduleTexts = new Map(); - for (const t of targets) if (t.movers.length > 0) moduleTexts.set(t.moduleFile, scopedModuleText(t, scope)); - if (hosts) moduleTexts.set(SCOPED_HOSTS_MODULE, hosts.module); - return { host: pruned.text, modules: moduleTexts, pruned: pruned.removed }; -} - -/** - * Prove a scoped split against its base, from the texts alone, as `verify` - * proves the first pass: every generated function is its base method's text, - * every stub is the generated one-call stub, the host module and each install - * block are the generated ones, and undoing the split rebuilds the base - * `engine.ts` byte-for-byte once the base's import bindings the head no longer - * reads are pruned from it (each pruned binding must occur in moved text). - * The first pass's text, `ObjectQL` among it, is compared like every other - * byte: it must not move. - */ -function verifyScoped(tm, baseText, headText, moduleTexts, { classes = SCOPED_CLASSES } = {}) { - const { Node } = tm; - const failures = []; - const moved = []; - const baseSf = parse(tm, HOST_PATH, baseText); - const headSf = parse(tm, HOST_PATH, headText); - const prune = pruneImports(tm, baseText, usedImportNames(tm, headText)); - const target = prune.text; - const ownModule = new Map(classes.map(([className, moduleFile]) => [moduleFile, className])); - - const modules = new Map(); - let hostsOnDisk = null; - for (const [file, text] of moduleTexts) { - if (!text.includes(SCOPED_MARK)) continue; - if (file === SCOPED_HOSTS_MODULE) { hostsOnDisk = text; continue; } - if (!ownModule.has(file)) { failures.push(`${file}: carries ${SCOPED_MARK} but is the module of no scoped class`); continue; } - const sf = parse(tm, join(SRC_DIR, file), text); - const fns = new Map(); - const facet = facetNameOf(file); - for (const st of sf.getStatements()) { - if (Node.isImportDeclaration(st)) continue; - if (Node.isInterfaceDeclaration(st) && st.getName() === hostNameOf(file)) continue; - if (Node.isClassDeclaration(st) && st.getName() === facet && !fns.size) { - for (const member of st.getMembers()) { - if (Node.isMethodDeclaration(member) && member.isStatic() && member.getBody() && !fns.has(member.getName())) fns.set(member.getName(), member); - else failures.push(`${file}: ${facet} has a member that is not a moved body: ${member.getText().slice(0, 60)}`); - } - continue; - } - failures.push(`${file}: a top-level statement that is neither an import, the host interface nor the facet class ${facet}: ${st.getText().slice(0, 60)}`); - } - modules.set(file, { sf, text, fns, claimed: new Set() }); - } - - const marker = scopedStubMarker(); - const movedDocs = []; - const edits = []; - const facets = []; - for (const [className, moduleFile] of classes) { - const headCls = headSf.getClass(className); - const baseCls = baseSf.getClass(className); - if (!headCls || !baseCls) { failures.push(`no class ${className} at base or head`); continue; } - const mod = modules.get(moduleFile); - for (const m of headCls.getMethods()) { - const body = m.getBody(); - if (!body) continue; - const hit = marker.exec(body.getText()); - if (!hit) continue; - const name = m.getName(); - if (hit[1] !== moduleFile) { failures.push(`${className}#${name}: its stub names ${hit[1]}, not its class's module ${moduleFile}`); continue; } - const fn = mod && mod.fns.get(name); - if (!fn) { failures.push(`${className}#${name}: its stub names ${moduleFile}, which has no function ${name}`); continue; } - mod.claimed.add(name); - const lineStart = headText.lastIndexOf('\n', body.getEnd() - 1) + 1; - const closeIndent = headText.slice(lineStart, body.getEnd() - 1); - const usesHost = fn.getParameters().some((p) => p.getName() === 'this'); - const want = stubBody({ node: m, name, usesHost, docMoved: Boolean(hit[2]) }, moduleFile, closeIndent, SCOPED_MARK); - if (body.getText() !== want) failures.push(`${className}#${name}: its stub is not the generated one-call stub (want ${JSON.stringify(want.split('\n').at(-2).trim())})`); - const base = baseCls.getMethods().find((x) => x.getName() === name && x.isStatic() === m.isStatic()); - if (!base || !base.getBody()) { failures.push(`${className}#${name}: no method of that name with a body at base`); continue; } - const same = { - body: fn.getBody().getText() === base.getBody().getText(), - params: JSON.stringify(fn.getParameters().filter((p) => p.getName() !== 'this').map((p) => p.getText())) === - JSON.stringify(base.getParameters().map((p) => p.getText())), - returnType: (fn.getReturnTypeNode()?.getText() ?? null) === (base.getReturnTypeNode()?.getText() ?? null), - async: fn.isAsync() === base.isAsync(), - typeParameters: JSON.stringify(fn.getTypeParameters().map((x) => x.getText())) === JSON.stringify(base.getTypeParameters().map((x) => x.getText())), - static: m.isStatic() === base.isStatic(), - }; - const lead = mod.text.slice(fn.getStart(true), fn.getStart()); - const docMoved = Boolean(hit[2]); - if (docMoved) { - if (m.getStart(true) !== m.getStart()) failures.push(`${className}#${name}: its stub says the docblock moved, but the class still carries one`); - if (m.getScope() !== 'private') failures.push(`${className}#${name}: a ${m.getScope()} method's docblock moved off the class (only a private one may)`); - edits.push({ start: m.getStart(), end: m.getStart(), text: lead }); - movedDocs.push(lead); - } else if (lead !== `${placeholderDoc(name, className)}\n `) { - failures.push(`${className}#${name}: the facet member's leading text is neither its moved docblock nor the placeholder`); - } - for (const [what, ok] of Object.entries(same)) if (!ok) failures.push(`${className}#${name}: the generated function's ${what} is not the base method's`); - moved.push({ - name: `${className}#${name}`, module: moduleFile, lines: base.getBody().getEndLineNumber() - base.getBody().getStartLineNumber() + 1, - text: fn.getText(), docMoved, ...same, - }); - edits.push({ start: body.getStart(), end: body.getEnd(), text: fn.getBody().getText() }); - if (fn.isAsync()) edits.push({ start: m.getNameNode().getStart(), end: m.getNameNode().getStart(), text: 'async ' }); - } - // The class's install block: exactly what `scopedHostsTexts` writes for - // the host interface on disk, each member forwarded as the BASE class - // declares it. Then the undo drops it. - const blocks = headCls.getMembers().filter((x) => Node.isClassStaticBlockDeclaration(x) && x.getFullText().includes(SCOPED_MARK)); - const iface = mod ? mod.sf.getInterface(hostNameOf(moduleFile)) : undefined; - if (iface || blocks.length > 0) { - const baseMembers = instanceMembers(tm, baseCls); - const members = new Map(); - const written = new Set(); - for (const p of iface ? iface.getProperties() : []) { - const n = p.getName(); - const info = baseMembers.get(n); - if (!info) { failures.push(`${moduleFile}: ${hostNameOf(moduleFile)}.${n} names no instance member of the base class ${className}`); continue; } - members.set(n, info.kind === 'method' ? 'method' : 'getter'); - if (info.kind !== 'method' && !p.isReadonly()) written.add(n); - } - const facet = { className, moduleFile, members, written }; - if (iface) facets.push(facet); - const want = scopedHostsTexts([facet]).blocks.get(className); - const blockAt = blocks.length === 1 ? headText.lastIndexOf(` // ${SCOPED_MARK} Installs`, blocks[0].getStart()) : -1; - if (!iface || blocks.length !== 1 || blockAt < 0 || headText.slice(blockAt, blocks[0].getEnd()) !== want) { - failures.push(`${className}: its host static block is not the generated installer of ${hostNameOf(moduleFile)}`); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', blockAt), end: blocks[0].getEnd(), text: '' }); - } - } - } - for (const [file, mod] of modules) { - for (const name of mod.fns.keys()) if (!mod.claimed.has(name)) failures.push(`${file}: function ${name} has no stub on ${ownModule.get(file)}`); - } - if (facets.length > 0 || hostsOnDisk !== null) { - if (hostsOnDisk !== scopedHostsTexts(facets).module) failures.push(`${SCOPED_HOSTS_MODULE} is not the generated host module for the scoped facets on disk`); - } - const generatedSpecifier = (spec) => { - const hit = /^\.\/(engine-[a-z0-9-]+)\.js$/.exec(spec ?? ''); - return Boolean(hit && (ownModule.has(`${hit[1]}.ts`) || `${hit[1]}.ts` === SCOPED_HOSTS_MODULE)); - }; - for (const st of headSf.getStatements()) { - const drop = (Node.isImportDeclaration(st) && generatedSpecifier(st.getModuleSpecifierValue())) || - (Node.isExportDeclaration(st) && !st.getModuleSpecifier() && st.getFullText().includes(SCOPED_MARK)); - if (drop) edits.push({ start: st.getFullStart(), end: st.getEnd(), text: '' }); - } - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let rebuilt = headText; - for (const e of edits) rebuilt = rebuilt.slice(0, e.start) + e.text + rebuilt.slice(e.end); - - const movedText = [...moved.map((m) => m.text), ...movedDocs].join('\n'); - for (const n of prune.removed) { - if (!new RegExp(`(^|[^\\w$])${n.replace(/\$/g, '\\$')}($|[^\\w$])`).test(movedText)) { - failures.push(`the head dropped the import \`${n}\`, which no moved body reads`); - } - } - if (rebuilt !== target) { - const a = rebuilt.split('\n'); - const b = target.split('\n'); - let i = 0; - while (i < Math.max(a.length, b.length) && a[i] === b[i]) i += 1; - failures.push(`undoing the scoped split does not rebuild the base engine.ts (its unread imports pruned): first difference at line ${i + 1}` + - `\n rebuilt: ${JSON.stringify(a[i] ?? '')}\n base: ${JSON.stringify(b[i] ?? '')}`); - } - if (moved.length === 0) failures.push('no moved method found: a proof over nothing is not a proof'); - return { failures, moved, pruned: prune.removed, linesBefore: lineCount(baseText), linesAfter: lineCount(headText) }; -} - -function planReportScoped(planned) { - const out = []; - const reasonCounts = new Map(); - let movedLines = 0; - let stubLines = 0; - for (const t of planned.targets) { - const lines = t.movers.reduce((n, r) => n + r.bodyLines, 0); - const stubs = t.movers.reduce((n, r) => n + r.stubLines, 0); - movedLines += lines; - stubLines += stubs; - out.push(`§ ${t.className} -> ${t.moduleFile}: ${t.movers.length}/${t.records.length} methods move (${lines} body lines out, ${stubs} stub lines in)`); - for (const r of t.records) { - if (r.reasons.length === 0) out.push(` move ${r.name} (body ${r.bodyLines} -> stub ${r.stubLines})`); - else out.push(` stay ${r.name} (${r.lineCount}) — ${r.reasons.join('; ')}`); - for (const reason of r.reasons) { - const code = reason.split(':')[0]; - reasonCounts.set(code, (reasonCounts.get(code) ?? 0) + 1); - } - } - } - out.push(''); - out.push(`scoped total: ${planned.targets.reduce((n, t) => n + t.movers.length, 0)}/${planned.targets.reduce((n, t) => n + t.records.length, 0)} ` + - `methods move: ${movedLines} body lines out, ${stubLines} stub lines in`); - out.push(`stay reasons (a method may carry several): ${[...reasonCounts].sort((a, b) => b[1] - a[1]).map(([c, n]) => `${c} ${n}`).join(', ') || 'none'}`); - out.push(`lever (a): ${planned.hostExports.size} engine.ts name(s) exported for the scoped facet modules` + - `${planned.hostExports.size ? ` (${[...planned.hostExports.keys()].sort().join(', ')})` : ''}`); - return out.join('\n'); -} - -function printVerifyScoped(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - const identical = v.moved.filter((m) => m.body && m.params && m.returnType && m.async).length; - console.log(`byte-identity (scoped classes): ${identical}/${v.moved.length} moved bodies identical to base (body, parameters, return type, async); ` + - `engine.ts ${v.linesBefore} -> ${v.linesAfter} lines; undoing the split ${v.failures.some((f) => f.startsWith('undoing')) ? 'does NOT' : 'does'} rebuild the base byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved text reads are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -function scopedModulesOnDisk() { - const out = new Map(); - for (const file of [SCOPED_HOSTS_MODULE, ...SCOPED_CLASSES.map((row) => row[1])]) { - const p = join(SRC_DIR, file); - if (existsSync(p)) out.set(file, readFileSync(p, 'utf8')); - } - return out; -} - -/** `--scoped`: plan, write or re-prove the second pass. */ -async function mainScoped(tm, argv) { - if (argv.includes('--members')) return mainScopedMembers(tm, argv); - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--scoped --verify needs --base '); - const v = verifyScoped(tm, gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), scopedModulesOnDisk()); - printVerifyScoped(v); - return v.failures.length === 0 ? 0 : 1; - } - const input = readFileSync(HOST_PATH, 'utf8'); - if (input.includes(SCOPED_MARK)) { - refuse(`${HOST_BASENAME} already carries ${SCOPED_MARK} stubs: run the second pass on a file whose scoped classes are unsplit (re-run on the latest main, never on its own output)`); - } - const planned = planScoped(tm, input); - console.log(planReportScoped(planned)); - const out = generateScoped(tm, input, planned); - const files = new Map([[HOST_BASENAME, out.host], ...out.modules]); - console.log(`output tree sha256: ${treeHash(files)} (input sha256 ${sha256(input)})`); - const v = verifyScoped(tm, input, out.host, out.modules); - printVerifyScoped(v); - if (v.failures.length > 0) { - console.error('✗ the generated scoped split fails byte-identity: nothing written. Report the fork; never hand-edit the split.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - for (const [file] of out.modules) { - const p = join(SRC_DIR, file); - if (existsSync(p) && !readFileSync(p, 'utf8').includes(SCOPED_MARK)) refuse(`${file} exists and was not written by this script`); - } - writeFileSync(HOST_PATH, out.host); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} module(s) under ${SRC_REL}`); - return 0; -} - -// ── The second pass's members mode: named scoped methods onto the split class (#30020 S1) ── -// -// `--scoped` runs on a file whose scoped classes are unsplit, never on its own -// output, so a scoped method a stay rule held when `main` was split moves by -// `--scoped --members Class#member,…` instead: on the split file, into its -// class's facet module, exactly as the second pass would have written it had -// the rule let it go. Every stay reason of the second pass applies and any one -// refuses: the pass names what it moves and never decides it. Two rules let a -// body move that the second pass kept (#30020: the state stays on the class, -// one owner, ruling 6687865760): -// -// - R1 on an instance host. A bare `this` the body hands on (`return this`, -// `callback(this, …)`) reads `this.facade`, a host entry the class's -// install block fills with the instance itself (`facade: instance`), typed -// `readonly facade: `. The undo is the fourth pass's inverse rewrite. -// - R9, a symbol key. A method keyed `[NAME]` (`symbolKeyOf`) moves into the -// facet member NAME in camelCase; the stub keeps the key and calls that -// member, and the header names the method as the class does. -// -// What grows, and only that: the stub; the class's install block; the facet -// module's header sentence (its list, in class order; words a hand wrote -// after the sentence, from the next line on, are kept as they stand), its host -// interface, its facet class (each member in class order) and its import -// lines. The pass never starts a facet or a host, never widens an export list -// and never switches the header's import paragraph: each refuses (exit 2). -// -// The proof (`--scoped --members --verify --base REF` re-runs it) undoes the -// moves from the head: each facet member back into its stub (R1 inverted, -// `async` and a private docblock back), the install block and the interface -// cut to what the members left behind still read, the header list without the -// names, the import edits inverted (`importEditsOf`) and the unread bindings -// pruned. The result must be the base `engine.ts` (its import bindings only -// moved bodies read pruned) and every scoped module byte for byte, and each -// facet member the text the base method gives. - -/** A scoped method whose body is already a stub: the second pass's, this mode's, or a hand move's. */ -const isScopedStub = (m) => Boolean(m.getBody() && /^\{\s*\/\/ \[#\d+(?: codemod)?\] The body moved to `engine-[a-z0-9-]+\.ts`/.test(m.getBody().getText())); - -/** A scoped method's key on its class: its name, or `[NAME]` for a symbol-keyed one. */ -const scopedLabelOf = (m) => m.getNameNode().getText(); - -/** The analysis context of one scoped class on a split `engine.ts`: `planScoped`'s, with R1 and R9 on. */ -function scopedMembersContext(tm, sf, text, scope, className) { - const cls = sf.getClass(className); - if (!cls) refuse(`no class ${className} in ${HOST_BASENAME}`); - return { text, sf, cls, className, members: instanceMembers(tm, cls), scope, statics: scopedStaticsOf(tm, cls), - pins: {}, needles: {}, classNeedles: {}, identityPort: true, symbolKeys: true }; -} - -/** Read one scoped method as this mode moves it: its stay reasons, host reads, label and facet name. */ -function readScopedMember(tm, ctx, m, moduleFile) { - const read = readMethod(tm, ctx, m); - if (read.readsNonPublicStatic) read.reasons.push('private-static'); - for (const p of m.getParameters()) { - if (p.getName() === facetNameOf(moduleFile) || p.getName() === hostVarOf(moduleFile)) read.reasons.push(`parameter-shadows: ${p.getName()}`); - } - const symbol = symbolKeyOf(tm, ctx, m); - return { ...read, name: scopedLabelOf(m), facetName: symbol ? symbol.facetName : m.getName() }; -} - -/** A private method's docblock (which moves with its body), or null. */ -const movedDocOf = (text, m) => (m.getScope() === 'private' && m.getStart(true) < m.getStart() ? text.slice(m.getStart(true), m.getStart()) : null); - -/** Where each instance method of a scoped class stands: by its label, and by the facet name its body takes. */ -function scopedPositions(tm, ctx) { - const byLabel = new Map(); - const byFacet = new Map(); - for (const m of ctx.cls.getMethods()) { - if (m.isStatic()) continue; - const symbol = symbolKeyOf(tm, ctx, m); - byLabel.set(scopedLabelOf(m), m.getStart()); - byFacet.set(symbol ? symbol.facetName : m.getName(), m.getStart()); - } - return { byLabel, byFacet }; -} - -/** - * A scoped facet module's header sentence (`scopedHeaderSentence`), read - * back: its region (from the header's first line to the line the sentence - * ends) and the names it lists. Null unless the region is that sentence of - * those names byte for byte; what follows it is left as it stands. - */ -function scopedHeaderOf(text, className, title) { - const open = text.indexOf('\n/**\n'); - if (open < 0) return null; - const start = open + 5; - const close = '(its second pass).'; - const at = text.indexOf(`${close}\n`, start); - const headerEnd = text.indexOf('\n */', start); - if (at < 0 || (headerEnd >= 0 && at > headerEnd)) return null; - const end = at + close.length; - const prose = text.slice(start, end).split('\n').map((l) => l.replace(/^ \*( |$)/, '')).join(' '); - const lead = ` the bodies of \`${className}\`'s methods `; - const i = prose.indexOf(lead); - const j = i < 0 ? -1 : prose.indexOf(' moved out of `engine.ts`', i); - if (j < 0) return null; - const names = [...prose.slice(i + lead.length, j).matchAll(/`([^`]+)`/g)].map((m) => m[1]); - return scopedHeaderSentence(className, title, names).join('\n') === text.slice(start, end) ? { region: { start, end }, names } : null; -} - -/** A scoped class's host factory in its install block (`scopedInstallLines`), parsed back; null when it is not that shape. */ -function scopedInstallRegionOf(text, moduleFile) { - const head = ` ${hostVarOf(moduleFile)}.install((instance) => ({\n`; - const i = text.indexOf(head); - if (i < 0 || text.indexOf(head, i + 1) >= 0) return null; - const start = i + head.length; - const end = text.indexOf('\n }));', start); - if (end < 0) return null; - const members = new Map(); - const written = new Set(); - for (const line of text.slice(start, end).split('\n')) { - let m; - if (line === SCOPED_FACADE_INSTALL_LINE) members.set(FACADE_MEMBER, 'facade'); - else if ((m = /^ {6}get ([\w$]+)\(\) \{ return instance\.\1; \},$/.exec(line))) members.set(m[1], 'getter'); - else if ((m = /^ {6}set ([\w$]+)\(v\) \{ instance\.\1 = v; \},$/.exec(line))) written.add(m[1]); - else if ((m = /^ {6}([\w$]+): \(\.\.\.a\) => instance\.\1\(\.\.\.a\),$/.exec(line))) members.set(m[1], 'method'); - else return null; - } - if (scopedInstallLines(members, written).join('\n') !== text.slice(start, end)) return null; - return { start, end, members, written }; -} - -/** - * Decide the moves `names` (`Class#member`) asks for on a split `engine.ts`. - * Refuses (exit 2) on a name no scoped class declares as one instance method, - * a method already a stub, one any stay rule holds, and any shape this mode - * does not grow a written module by. Pure. - */ -function planScopedMembers(tm, text, moduleTexts, names, { classes = SCOPED_CLASSES } = {}) { - if (!names || names.length === 0) refuse('--scoped --members needs a comma-separated list of Class#member names'); - if (new Set(names).size !== names.length) refuse(`--scoped --members names a method twice: ${names.join(', ')}`); - const sf = parse(tm, HOST_PATH, text); - const scope = moduleScope(tm, sf); - const ctxs = new Map(); - const records = []; - for (const q of names) { - const hit = /^([A-Za-z_$][\w$]*)#(.+)$/.exec(q); - if (!hit) refuse(`--scoped --members names ${q}: spell each as Class#member (\`ScopedContext#transaction\`, \`ScopedContext#[SEED_USER_GRANTS]\`)`); - const row = classes.find(([c]) => c === hit[1]); - if (!row) refuse(`--scoped --members names ${q}, and ${hit[1]} is not a scoped class (${classes.map(([c]) => c).join(', ')})`); - const [className, moduleFile, title] = row; - if (!ctxs.has(className)) ctxs.set(className, scopedMembersContext(tm, sf, text, scope, className)); - const ctx = ctxs.get(className); - const found = ctx.cls.getMethods().filter((m) => !m.isStatic() && scopedLabelOf(m) === hit[2]); - if (found.length !== 1) refuse(`--scoped --members names ${q}, which ${className} declares as ${found.length === 0 ? 'no instance method' : 'more than one instance method'}`); - const m = found[0]; - if (isScopedStub(m)) refuse(`${q} is already moved: its body is a stub`); - const read = readScopedMember(tm, ctx, m, moduleFile); - if (read.reasons.length > 0) { - refuse(`${q} stays on the class, as the second pass would keep it: ${read.reasons.map((r) => `${r} (${STAY_REASONS[r.split(':')[0]] ?? r})`).join('; ')}`); - } - for (const [n] of read.moduleRefs) { - if (scope.exported.has(n) && scope.bindings.get(n)?.kind === 'local') continue; - refuse(`${q} reads ${n}, a top-level name ${HOST_BASENAME} does not export: this mode does not widen the generated export lists`); - } - for (const local of read.imports.keys()) { - const b = scope.bindings.get(local); - if (!b || b.kind !== 'import') refuse(`import binding ${local} not found`); - } - records.push({ ...read, className, title, module: moduleFile, node: m, doc: movedDocOf(text, m) }); - } - records.sort((a, b) => a.node.getStart() - b.node.getStart()); - const modules = new Map(); - for (const r of records) modules.set(r.module, [...(modules.get(r.module) ?? []), r]); - for (const [file, movers] of modules) { - const mod = moduleTexts.get(file); - if (mod == null || !mod.includes(SCOPED_MARK)) refuse(`${file} is not on disk as the second pass wrote it: this mode adds to a written facet, never starts one`); - const facet = facetMembersOf(tm, file, mod); - if (!facet) refuse(`${file}: its facet class is not as the second pass wrote it`); - const held = new Set(facet.members.map((x) => x.name)); - const taken = new Set(); - for (const r of movers) { - if (held.has(r.facetName) || taken.has(r.facetName)) refuse(`${r.className}#${r.name}: ${file} already holds, or another mover takes, a facet member ${r.facetName}`); - taken.add(r.facetName); - if (r.host.size > 0 && !interfaceRegionOf(mod, hostNameOf(file))) refuse(`${r.className}#${r.name} reads the class, and ${file} has no host: this mode does not give a facet one`); - } - } - return { sf, scope, ctxs, records, modules }; -} - -/** Apply a `planScopedMembers` plan. Returns `{ host, modules, pruned }` (`modules`: the receiving modules' new texts). Pure. */ -function generateScopedMembers(tm, text, moduleTexts, planned) { - const { scope, ctxs, modules } = planned; - const edits = []; - for (const [file, movers] of modules) { - for (const r of movers) { - const body = r.node.getBody(); - const closeIndent = text.slice(lineStartOf(text, body.getEnd() - 1), body.getEnd() - 1); - if (!/^ *$/.test(closeIndent)) refuse(`${r.className}#${r.name}: the body's closing brace does not open its own line`); - edits.push({ start: body.getStart(), end: body.getEnd(), - text: stubBody({ node: r.node, name: r.facetName, usesHost: r.host.size > 0, docMoved: Boolean(r.doc) }, file, closeIndent, SCOPED_MARK) }); - const asyncKw = r.node.getModifiers().find((x) => x.getKind() === tm.SyntaxKind.AsyncKeyword); - if (asyncKw) edits.push({ start: asyncKw.getStart(), end: r.node.getNameNode().getStart(), text: '' }); - if (r.doc) edits.push({ start: r.node.getStart(true), end: r.node.getStart(), text: '' }); - } - const members = new Map(); - const written = new Set(); - for (const r of movers) for (const [k, kind] of r.host) members.set(k, kind); - for (const r of movers) for (const k of r.writes) written.add(k); - if (members.size === 0) continue; - const inst = scopedInstallRegionOf(text, file); - if (!inst) refuse(`${file}: its host factory in ${HOST_BASENAME}'s install block is not as the second pass writes it`); - const merged = new Map(inst.members); - for (const [k, kind] of members) { - if (merged.has(k) && merged.get(k) !== kind) refuse(`${file}: host member ${k} is a ${merged.get(k)} there and a ${kind} here`); - merged.set(k, kind); - } - const lines = scopedInstallLines(merged, new Set([...inst.written, ...written])).join('\n'); - if (lines !== text.slice(inst.start, inst.end)) edits.push({ start: inst.start, end: inst.end, text: lines }); - } - const out = applyOrderedEdits(text, edits); - const pruned = pruneHostImports(tm, out, usedImportNames(tm, out)); - - const moduleOut = new Map(); - for (const [file, movers] of modules) { - const mod = moduleTexts.get(file); - const { className, title } = movers[0]; - const pos = scopedPositions(tm, ctxs.get(className)); - const hostName = hostNameOf(file); - const modEdits = []; - // The facet members, each before the first held member declared below it on the class. - const facet = facetMembersOf(tm, file, mod); - const at = (map, name) => { - if (!map.has(name)) refuse(`${file}: ${name} names no instance method of ${className}`); - return map.get(name); - }; - const held = facet.members.map((m) => ({ ...m, at: at(pos.byFacet, m.name) })); - const groups = new Map(); - for (const r of movers) { - const next = held.find((m) => m.at > r.node.getStart()); - groups.set(next ? next.name : '', [...(groups.get(next ? next.name : '') ?? []), facetMethodText(r, hostName, className)]); - } - for (const [key, texts] of groups) { - if (key) { - const where = lineStartOf(mod, held.find((m) => m.name === key).node.getStart(true)); - modEdits.push({ start: where, end: where, text: texts.map((t) => `${t}\n\n`).join('') }); - } else { - const where = held.at(-1).node.getEnd(); - modEdits.push({ start: where, end: where, text: texts.map((t) => `\n\n${t}`).join('') }); - } - } - // The header's list gains the names, each before the first listed name declared below it. - const header = scopedHeaderOf(mod, className, title); - if (!header) refuse(`${file}: its header sentence is not as the second pass writes it`); - const listed = [...header.names]; - for (const r of movers) { - const k = listed.findIndex((n) => at(pos.byLabel, n) > r.node.getStart()); - listed.splice(k < 0 ? listed.length : k, 0, r.name); - } - modEdits.push({ start: header.region.start, end: header.region.end, text: scopedHeaderSentence(className, title, listed).join('\n') }); - // The host interface gains what the moved bodies read; the identity port as the instance itself. - const reads = new Map(); - const writes = new Set(); - for (const r of movers) for (const [k, kind] of r.host) reads.set(k, kind); - for (const r of movers) for (const k of r.writes) writes.add(k); - if (reads.size > 0) { - const iface = interfaceRegionOf(mod, hostName); - if (!iface) refuse(`${file}: its host interface is not as the second pass writes it`); - const lines = new Map([...iface.members].map(([k, v]) => [k, v.line])); - for (const [k, kind] of reads) { - const readonly = kind === 'facade' || (kind === 'getter' && !writes.has(k)); - const prev = iface.members.get(k); - if (prev && prev.readonly && !readonly) refuse(`${file}: host member ${k} is read-only there, and a moved body ${kind === 'getter' ? 'assigns' : 'calls'} it`); - if (prev && Boolean(prev.facade) !== (kind === 'facade')) refuse(`${file}: host member ${k} is not the identity port there`); - if (!prev) { - lines.set(k, kind === 'facade' - ? `${SCOPED_FACADE_DOC}\n readonly ${FACADE_MEMBER}: ${className};` - : ` ${readonly ? 'readonly ' : ''}${k}: ${className}['${k}'];`); - } - } - modEdits.push({ start: iface.start, end: iface.end, text: [...lines.keys()].sort().map((k) => lines.get(k)).join('\n') }); - } - modEdits.push(...moduleImportEdits(tm, file, mod, scope, movers, null)); - const next = applyOrderedEdits(mod, modEdits); - if (importsEngineValues(next) !== importsEngineValues(mod)) refuse(`${file}: the move would switch what its header's import paragraph says (a first value import from \`./engine.js\`)`); - moduleOut.set(file, next); - } - return { host: pruned.text, modules: moduleOut, pruned: pruned.removed }; -} - -/** - * Undo this mode's moves out of one receiving module, from its head text and - * its base's import block: drop the named facet members and their names from - * the header's list, keep the host members the rest still `Pick`, invert the - * import edits the moves made and prune what nothing reads. Checks the head on - * the way (`fail`). Returns the text, or null when the head is not a module - * this mode can read. - */ -function undoScopedMembersModule(tm, file, text, mvs, fail, baseText) { - const { className, title } = mvs[0]; - const facetNames = mvs.map((mv) => mv.facetName); - const facet = facetMembersOf(tm, file, text); - const header = scopedHeaderOf(text, className, title); - if (!facet || !header) { fail(`${file}: not a facet module as the second pass writes one`); return null; } - for (const mv of mvs) if (!header.names.includes(mv.name)) fail(`${file}: its header does not list ${mv.name}`); - const union = (ms) => new Set(ms.flatMap((m) => picksOf(m))); - const iface = interfaceRegionOf(text, hostNameOf(file)); - if ((iface ? [...iface.members.keys()].join() : '') !== [...union(facet.members)].sort().join()) fail(`${file}: its host interface is not exactly the members its bodies' Picks name`); - const unread = pruneImports(tm, text, usedImportNames(tm, text)).removed; - if (unread.length > 0) fail(`${file}: imports what nothing in it reads: ${unread.join(', ')}`); - const keep = facet.members.filter((m) => !facetNames.includes(m.name)); - if (keep.length === 0) { fail(`${file}: every member is one this mode moved (it never starts a facet)`); return null; } - const movedText = facet.members.filter((m) => facetNames.includes(m.name)).map((m) => m.text).join('\n'); - const inverse = importEditsOf(tm, file, baseText, text, movedText, fail); - const labels = mvs.map((mv) => mv.name); - const edits = [ - { start: facet.start, end: facet.end, text: keep.map((m) => m.text).join('\n\n') }, - { start: header.region.start, end: header.region.end, text: scopedHeaderSentence(className, title, header.names.filter((n) => !labels.includes(n))).join('\n') }, - ]; - if (iface) { - const kept = union(keep); - edits.push({ start: iface.start, end: iface.end, text: [...iface.members].filter(([k]) => kept.has(k)).map(([, v]) => v.line).join('\n') }); - } - return pruneModuleImports(tm, file, applyOrderedEdits(text, edits), inverse); -} - -/** - * Prove this mode's moves against their base, from the texts alone (it shares - * no state with `generateScopedMembers`). `baseModules` / `headModules`: the - * second pass's modules (the hosts module included) at each side, by file. - * Returns `{ failures, moved, pruned, linesBefore, linesAfter }`. - */ -function verifyScopedMembers(tm, baseText, headText, baseModules, headModules, { classes = SCOPED_CLASSES } = {}) { - const failures = []; - const fail = (msg) => failures.push(msg); - const moved = []; - const baseSf = parse(tm, HOST_PATH, baseText); - const headSf = parse(tm, HOST_PATH, headText); - const scope = moduleScope(tm, baseSf); - const marker = scopedStubMarker(); - const key = (m) => `${m.isStatic() ? 'static ' : ''}${scopedLabelOf(m)}`; - for (const [className, file, title] of classes) { - const headCls = headSf.getClass(className); - if (!baseSf.getClass(className) || !headCls) { fail(`no class ${className} at base or head`); continue; } - const ctx = scopedMembersContext(tm, baseSf, baseText, scope, className); - const baseMethods = new Map(ctx.cls.getMethods().map((m) => [key(m), m])); - const headMethods = new Map(headCls.getMethods().map((m) => [key(m), m])); - if ([...baseMethods.keys()].join() !== [...headMethods.keys()].join()) fail(`${className} does not declare the same methods in the same order at base and head`); - for (const [k, hm] of headMethods) { - const bm = baseMethods.get(k); - if (!bm) continue; - if (isScopedStub(bm) && !isScopedStub(hm)) fail(`${className}#${k}: a stub at base is a body at head`); - if (!isScopedStub(hm) || isScopedStub(bm)) continue; - const hit = marker.exec(hm.getBody().getText()); - if (!hit) { fail(`${className}#${k}: a stub at head that is not a ${SCOPED_MARK} stub`); continue; } - if (hit[1] !== file) { fail(`${className}#${k}: its stub names ${hit[1]}, not its class's module ${file}`); continue; } - moved.push({ className, title, file, hm, bm, ctx, docMoved: Boolean(hit[2]) }); - } - } - const done = (pruned = []) => ({ failures, moved: moved.map((mv) => `${mv.className}#${mv.name ?? scopedLabelOf(mv.bm)}`), pruned, linesBefore: lineCount(baseText), linesAfter: lineCount(headText) }); - if (moved.length === 0) { fail('nothing moved: the head carries no stub its base did not'); return done(); } - for (const mv of moved) { - const { hm, bm, file, className } = mv; - const read = readScopedMember(tm, mv.ctx, bm, file); - mv.name = read.name; - mv.facetName = read.facetName; - const q = `${className}#${read.name}`; - if (read.reasons.length > 0) fail(`${q}: a stay rule holds it at base (${read.reasons.join('; ')})`); - for (const [n] of read.moduleRefs) if (!(scope.exported.has(n) && scope.bindings.get(n)?.kind === 'local')) fail(`${q}: reads ${n}, which ${HOST_BASENAME} does not export at base`); - const text = headModules.get(file); - const facet = text && text.includes(SCOPED_MARK) ? facetMembersOf(tm, file, text) : null; - const fm = facet?.members.find((m) => m.name === read.facetName); - if (!fm) { fail(`${q}: ${file} at head holds no facet member ${read.facetName}`); continue; } - mv.fm = fm.node; - mv.moduleText = text; - const body = hm.getBody(); - const closeIndent = headText.slice(lineStartOf(headText, body.getEnd() - 1), body.getEnd() - 1); - const usesHost = read.host.size > 0; - if (body.getText() !== stubBody({ node: hm, name: read.facetName, usesHost, docMoved: mv.docMoved }, file, closeIndent, SCOPED_MARK)) fail(`${q}: the stub is not the second pass's stub of its base reading`); - if (hm.isAsync()) fail(`${q}: the stub kept \`async\``); - const baseDoc = movedDocOf(baseText, bm); - if (mv.docMoved !== (baseDoc !== null)) fail(`${q}: its stub says its docblock ${mv.docMoved ? 'moved' : 'stayed'}, and the base method is ${baseDoc === null ? 'not a private one with a docblock' : 'a private one with a docblock'}`); - if (fm.text !== facetMethodText({ ...read, node: bm, doc: baseDoc }, hostNameOf(file), className)) { - fail(`${q}: the facet member is not its base method's text (docblock, parameters, return type, body, R1)`); - } - } - - // The modules: the receiving ones undo to their base; every other one is its base. - const touched = new Map(); - for (const mv of moved) if (mv.fm) touched.set(mv.file, [...(touched.get(mv.file) ?? []), mv]); - const undone = new Map(); - for (const file of new Set([...baseModules.keys(), ...headModules.keys()])) { - const b = baseModules.get(file) ?? null; - const h = headModules.get(file) ?? null; - if (!touched.has(file)) { - if (b !== h) fail(`${file}: changed, and no member this mode moved is in it`); - continue; - } - if (b === null) { fail(`${file}: absent at base (this mode never starts a facet)`); continue; } - const u = undoScopedMembersModule(tm, file, h, touched.get(file), fail, b); - if (u === null) continue; - undone.set(file, u); - if (u !== b) fail(`undoing the moves out of ${file} does not rebuild its base (first difference at line ${firstDiffLine(u, b)})`); - } - - // engine.ts: each body, docblock and `async` back; each install block loses what only moved bodies read. - const edits = []; - for (const mv of moved) { - if (!mv.fm) continue; - const body = mv.hm.getBody(); - edits.push({ start: body.getStart(), end: body.getEnd(), text: identityUndoText(tm, mv.fm) }); - if (mv.fm.isAsync()) edits.push({ start: mv.hm.getNameNode().getStart(), end: mv.hm.getNameNode().getStart(), text: 'async ' }); - if (mv.docMoved) edits.push({ start: mv.hm.getStart(), end: mv.hm.getStart(), text: mv.moduleText.slice(mv.fm.getStart(true), mv.fm.getStart()) }); - } - for (const file of touched.keys()) { - const iface = interfaceRegionOf(headModules.get(file), hostNameOf(file)); - if (!iface) continue; - const inst = scopedInstallRegionOf(headText, file); - if (!inst) { fail(`${file}: its host factory in ${HOST_BASENAME} is not as the second pass writes it`); continue; } - for (const [k, v] of iface.members) { - const kind = inst.members.get(k); - const readonly = kind === 'facade' || (kind === 'getter' && !inst.written.has(k)); - if (!kind || v.readonly !== readonly || Boolean(v.facade) !== (kind === 'facade')) fail(`${file}: host member ${k} is not the same member in its interface and its factory`); - } - if (inst.members.size !== iface.members.size) fail(`${file}: its host factory forwards members its interface does not declare`); - const u = undone.get(file); - const keptIface = u ? interfaceRegionOf(u, hostNameOf(file)) : null; - if (!keptIface) continue; - const kept = new Map([...inst.members].filter(([k]) => keptIface.members.has(k))); - if (kept.size !== inst.members.size) { - edits.push({ start: inst.start, end: inst.end, text: scopedInstallLines(kept, new Set([...inst.written].filter((k) => kept.has(k)))).join('\n') }); - } - } - let undoneHost = null; - try { - undoneHost = applyOrderedEdits(headText, edits); - } catch (e) { - if (!(e instanceof CodemodRefusal)) throw e; - fail(`${HOST_BASENAME}: the undo's edits overlap`); - } - const prune = pruneHostImports(tm, baseText, usedImportNames(tm, headText)); - if (undoneHost !== null && undoneHost !== prune.text) { - fail(`undoing the moves does not rebuild the base ${HOST_BASENAME} (first difference at line ${firstDiffLine(undoneHost, prune.text)})`); - } - const movedText = moved.map((mv) => mv.bm.getText()).join('\n'); - for (const n of prune.removed) { - if (!new RegExp(`\\b${n.replace(/\$/g, '\\$')}\\b`).test(movedText)) fail(`${HOST_BASENAME} lost the import binding ${n}, which no moved body reads`); - } - return done(prune.removed); -} - -function planReportScopedMembers(planned) { - const out = [`# codemod-split-engine --scoped --members (${SCOPED_CARD} second pass, #30020): named scoped methods onto the split class`, '']; - for (const [file, movers] of planned.modules) { - out.push(`- ${file}: ${movers.map((r) => `${r.className}#${r.name}${r.facetName !== r.name ? ` as ${r.facetName}` : ''} ` + - `(${r.node.getBody().getEndLineNumber() - r.node.getBody().getStartLineNumber() + 1} body lines${r.identity.length > 0 ? `, ${r.identity.length} bare \`this\` -> \`this.facade\`` : ''}` + - `${r.doc ? ', its docblock with it' : ''})`).join(', ')}`); - } - return out.join('\n'); -} - -function printVerifyScopedMembers(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - console.log(`undo proof (scoped members): ${v.moved.length} moved method(s) (${v.moved.join(', ') || 'none'}); engine.ts ${v.linesBefore} -> ${v.linesAfter} lines; ` + - `undoing the moves ${v.failures.length > 0 ? 'does NOT' : 'does'} rebuild the base engine.ts and its scoped modules byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved bodies read are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -function scopedModulesAt(ref) { - const out = new Map(); - for (const file of [SCOPED_HOSTS_MODULE, ...SCOPED_CLASSES.map((row) => row[1])]) { - try { - out.set(file, execFileSync('git', ['show', `${ref}:${SRC_REL}/${file}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'ignore'] })); - } catch { /* absent at the ref */ } - } - return out; -} - -/** `--scoped --members`: plan, write or re-prove the second pass's members mode. */ -async function mainScopedMembers(tm, argv) { - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--scoped --members --verify needs --base '); - const v = verifyScopedMembers(tm, gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), scopedModulesAt(ref), scopedModulesOnDisk()); - printVerifyScopedMembers(v); - return v.failures.length === 0 ? 0 : 1; - } - const j = argv.indexOf('--members'); - const value = argv[j + 1]; - const names = value && !value.startsWith('--') ? value.split(',').map((s) => s.trim()).filter(Boolean) : []; - const input = readFileSync(HOST_PATH, 'utf8'); - const moduleTexts = scopedModulesOnDisk(); - const planned = planScopedMembers(tm, input, moduleTexts, names); - console.log(planReportScopedMembers(planned)); - const out = generateScopedMembers(tm, input, moduleTexts, planned); - const headModules = new Map([...moduleTexts, ...out.modules]); - console.log(`output tree sha256: ${treeHash(new Map([[HOST_BASENAME, out.host], ...headModules]))} (input sha256 ${sha256(input)})`); - const v = verifyScopedMembers(tm, input, out.host, moduleTexts, headModules); - printVerifyScopedMembers(v); - if (v.failures.length > 0) { - console.error('✗ the generated moves fail the undo proof: nothing written. Report the fork; never hand-edit the moves.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - writeFileSync(HOST_PATH, out.host); - for (const [file, t] of out.modules) writeFileSync(join(SRC_DIR, file), t); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} module(s) under ${SRC_REL}`); - return 0; -} - -// ── The third pass: the hand series' private docblocks (#30053) ────────────── - -/** - * The hand series (#25522, and the two later hand cuts #27495 and #29460) - * moved its bodies out of `engine.ts` before this codemod existed, and kept - * EVERY method's docblock on the class: each function in a hand module - * carries the placeholder `placeholderDoc` writes instead. This codemod's own - * cut pattern moves a PRIVATE method's docblock with its body (a private - * member is no part of the published surface, so nothing outside the class - * reads it there) and keeps a public or protected one on the class, the - * contract. `--hand-docs` applies that rule to the hand series, and touches - * nothing else: - * - * - A hand-series stub is a method whose body opens with a hand marker - * (`HAND_STUB_MARK`), naming its hand module. - * - A private stub's docblock leaves the class and replaces its function's - * placeholder, de-indented one level (the hand series re-indented every - * body it moved, so the function stands at column 0); the stub's marker - * gains `HAND_DOC_MOVED`; the module's header docblock gains - * `HAND_DOCS_NOTE`, once, because its header says each docblock stays on - * the class. - * - A public or protected stub, a private stub with no docblock, and a stub - * whose leading text is anything but one docblock stay as they are. - * - `--modules a.ts,b.ts` moves only the stubs of the named hand modules, so - * the pass can land in slices; a stub already moved is skipped, so a later - * slice runs on an earlier one's output. - * - * The proof is the undo: putting every moved docblock back on its stub - * (re-indented), the placeholder back on its function, and taking the marker - * phrase and the header note out rebuilds the base `engine.ts` and every base - * hand module byte-for-byte (a base an earlier slice landed in is undone the - * same way first, so a slice is proved on its own), once the import bindings - * only a moved docblock's `{@link}` read (`noUnusedLocals` counts a link) are - * pruned from the base with the `//` lines directly above a declaration that - * goes whole; every pruned name must be one a moved docblock links. A - * one-character edit in a moved docblock, a block dropped on either side, a - * public docblock moved, or any other byte changed in those files fails it. - * The public `.d.ts` bar is a report reading on two built dists, as for the - * first two passes. - */ -const HAND_DOCS_CARD = '#30053'; - -/** - * The marker a hand-series stub's body opens with: `[#25522 cut N]` or - * `[#27495]` then "The body moved to", or #29460's untagged "The body lives - * in". Group 1 is the module, group 2 the phrase once moved. - */ -const HAND_STUB_MARK = /^ *\/\/ (?:\[(?:#25522 cut \d+|#27495)\] )?The body (?:moved to|lives in) `(engine-[a-z0-9-]+\.ts)`(, its docblock with it)?/; - -/** The phrase a stub's marker gains after its module's backticked name. */ -const HAND_DOC_MOVED = `, ${DOC_MOVED}`; - -/** The paragraph a hand module's header docblock gains, above its closing line, when a docblock moves into it. */ -const HAND_DOCS_NOTE = [ - ' *', - ` * [${HAND_DOCS_CARD} codemod] A PRIVATE method's docblock has since moved here,`, - ' * onto its function (`--hand-docs` of `scripts/codemod-split-engine.mjs`),', - ' * and the class keeps none for it; a public or protected method\'s docblock', - ' * stays on the class, the contract, and its function keeps the placeholder.', -].join('\n'); - -/** One docblock and the indentation before the member, or null: the only leading text that moves. */ -function soleDocblock(lead) { - const m = /^(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\n( *)$/.exec(lead); - return m ? { doc: m[1], indent: m[2] } : null; -} - -/** The docblock one level out (two spaces), or null when a line is not indented that far. */ -function deindentDoc(doc) { - const lines = doc.split('\n'); - const out = [lines[0]]; - for (const line of lines.slice(1)) { - if (line === '') out.push(line); - else if (line.startsWith(' ')) out.push(line.slice(2)); - else return null; - } - return out.join('\n'); -} - -const reindentDoc = (doc) => doc.split('\n').map((line, i) => (i === 0 || line === '' ? line : ` ${line}`)).join('\n'); - -/** The header docblock's closing line offset in a module, or -1: the first `/**` before any import or export. */ -function headerCloseAt(text) { - const open = text.indexOf('/**'); - const firstStatement = text.search(/^(?:import|export) /m); - if (open < 0 || (firstStatement >= 0 && open > firstStatement)) return -1; - const close = text.indexOf('\n */\n', open); - return close < 0 || (firstStatement >= 0 && close > firstStatement) ? -1 : close; -} - -/** Every hand-series stub of the class, in source order, with what moving its docblock needs. */ -function handStubs(tm, engineText, className = CLASS_NAME) { - const sf = parse(tm, HOST_BASENAME, engineText); - const cls = sf.getClass(className); - if (!cls) refuse(`${HOST_BASENAME} declares no class ${className}`); - const stubs = []; - for (const m of cls.getMethods()) { - const body = m.getBody(); - if (!body) continue; - const line1Start = engineText.indexOf('\n', body.getStart()) + 1; - const line1 = engineText.slice(line1Start, engineText.indexOf('\n', line1Start)); - const hit = HAND_STUB_MARK.exec(line1); - if (!hit) continue; - stubs.push({ - node: m, name: m.getName(), scope: m.getScope(), module: hit[1], moved: Boolean(hit[2]), - lead: engineText.slice(m.getStart(true), m.getStart()), leadStart: m.getStart(true), memberStart: m.getStart(), - // The offset right after the module's closing backtick, where the phrase goes. - phraseAt: line1Start + hit.index + hit[0].length - (hit[2] ? hit[2].length : 0), - }); - } - return stubs; -} - -/** The exported function of that name in a hand module: its leading text and offsets, or null. */ -function handFunction(tm, file, text, name) { - const sf = parse(tm, file, text); - const fn = sf.getFunction(name); - if (!fn || !fn.isExported()) return null; - return { lead: text.slice(fn.getStart(true), fn.getStart()), leadStart: fn.getStart(true), start: fn.getStart() }; -} - -/** Text edits applied end to start; each is `{ start, end, text }`. */ -function applyEdits(text, edits) { - let out = text; - for (const e of [...edits].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.text + out.slice(e.end); - return out; -} - -/** - * The plan: each hand stub's verdict. `modules` is the slice (null: every - * hand module); `moduleTexts` maps a hand module file to its text. - */ -function planHandDocs(tm, engineText, moduleTexts, { modules = null, className = CLASS_NAME } = {}) { - const stubs = handStubs(tm, engineText, className); - const known = new Set(stubs.map((s) => s.module)); - for (const file of modules ?? []) { - if (!known.has(file)) refuse(`--modules names ${file}, which no hand-series stub of ${className} delegates to (known: ${[...known].sort().join(', ')})`); - } - const records = []; - for (const s of stubs) { - const why = (() => { - if (s.moved) return 'already-moved'; - if (s.scope !== 'private') return `${s.scope} (its docblock is the contract and stays on the class)`; - if (s.lead === '') return 'no-docblock'; - if (modules && !modules.includes(s.module)) return 'not-in-slice'; - const sole = soleDocblock(s.lead); - if (!sole) return 'leading-text (anything but one docblock stays)'; - if (deindentDoc(sole.doc) === null) return 'indent (a docblock line is not indented one level)'; - return ''; - })(); - let fn = null; - let reason = why; - if (why === '') { - const text = moduleTexts.get(s.module); - if (text == null) refuse(`${s.module}: the hand module ${s.name} delegates to is not on disk`); - fn = handFunction(tm, s.module, text, s.name); - if (!fn) refuse(`${s.module}: exports no function ${s.name}, the body ${className}#${s.name}'s marker names`); - if (headerCloseAt(text) < 0) refuse(`${s.module}: no header docblock closing in a bare \` */\` line before its first import or export`); - // A function whose docblock says more than the placeholder keeps it, - // and the method keeps its own: merging two docblocks is an edit, not a move. - if (fn.lead !== `${placeholderDoc(s.name, className)}\n`) reason = 'function-docblock (its function carries more than the placeholder)'; - } - records.push({ ...s, reason, fn }); - } - return { records, movers: records.filter((r) => r.reason === '') }; -} - -/** Apply the plan: the new `engine.ts` and every hand module it changed. */ -function generateHandDocs(tm, engineText, moduleTexts, planned) { - const hostEdits = []; - const perModule = new Map(); - for (const r of planned.movers) { - hostEdits.push({ start: r.leadStart, end: r.memberStart, text: '' }); - hostEdits.push({ start: r.phraseAt, end: r.phraseAt, text: HAND_DOC_MOVED }); - const edits = perModule.get(r.module) ?? []; - edits.push({ start: r.fn.leadStart, end: r.fn.start, text: `${deindentDoc(soleDocblock(r.lead).doc)}\n` }); - perModule.set(r.module, edits); - } - const modules = new Map(); - for (const [file, edits] of [...perModule].sort(([a], [b]) => (a < b ? -1 : 1))) { - const text = moduleTexts.get(file); - if (!text.includes(HAND_DOCS_NOTE)) { - const at = headerCloseAt(text); - edits.push({ start: at, end: at, text: `\n${HAND_DOCS_NOTE}` }); - } - modules.set(file, applyEdits(text, edits)); - } - const moved = applyEdits(engineText, hostEdits); - // A JSDoc `{@link X}` is a read `noUnusedLocals` counts, so an import binding - // only a moved docblock linked is dropped, with the `//` lines that explain it. - const { text: host, removed: pruned } = pruneImports(tm, moved, usedImportNames(tm, moved), { dropAttachedComments: true }); - return { host, modules, pruned }; -} - -/** The names a docblock links (`{@link X}`, `{@linkcode X}`, `@see X`; the leftmost name of a dotted one). */ -function linkedNames(doc) { - return new Set([...doc.matchAll(/\{@link(?:code|plain)?\s+([A-Za-z_$][\w$]*)|@see\s+([A-Za-z_$][\w$]*)/g)].map((m) => m[1] ?? m[2])); -} - -/** - * Undo every move a tree's markers record: each moved docblock back on its - * stub (re-indented), the placeholder back on its function, the marker phrase - * and the header note out. `moduleTexts` maps a hand module file to its text. - * Returns the undone texts, the moves it undid, and every way the tree breaks - * the rule (a public docblock moved, a marker over a docblock still on the - * class, a function with no moved docblock, a header with no note). - */ -function undoHandDocs(tm, engineText, moduleTexts, className = CLASS_NAME) { - const failures = []; - const moved = []; - const hostEdits = []; - const perModule = new Map(); - for (const s of handStubs(tm, engineText, className)) { - if (!s.moved) continue; - if (s.scope !== 'private') failures.push(`${s.name}: a ${s.scope} method's docblock moved off the class (only a private one may)`); - if (s.lead !== '') failures.push(`${s.name}: its stub says the docblock moved, but the class still carries leading text`); - const text = moduleTexts.get(s.module); - const fn = text == null ? null : handFunction(tm, s.module, text, s.name); - if (!fn) { failures.push(`${s.name}: ${s.module} exports no function of that name`); continue; } - const sole = soleDocblock(fn.lead); - if (!sole || sole.indent !== '' || fn.lead === `${placeholderDoc(s.name, className)}\n`) { - failures.push(`${s.name}: its stub says the docblock moved, but its function in ${s.module} carries no moved docblock`); - continue; - } - const indent = /^ */.exec(engineText.slice(engineText.lastIndexOf('\n', s.memberStart) + 1, s.memberStart))[0]; - hostEdits.push({ start: s.memberStart, end: s.memberStart, text: `${reindentDoc(sole.doc)}\n${indent}` }); - hostEdits.push({ start: s.phraseAt, end: s.phraseAt + HAND_DOC_MOVED.length, text: '' }); - const edits = perModule.get(s.module) ?? []; - edits.push({ start: fn.leadStart, end: fn.start, text: `${placeholderDoc(s.name, className)}\n` }); - perModule.set(s.module, edits); - moved.push({ name: s.name, module: s.module, lines: sole.doc.split('\n').length, doc: sole.doc }); - } - const modules = new Map(); - for (const [file, text] of moduleTexts) { - const edits = perModule.get(file) ?? []; - if (edits.length > 0 || text.includes(HAND_DOCS_NOTE)) { - const at = text.indexOf(`\n${HAND_DOCS_NOTE}\n */\n`); - if (at < 0) failures.push(`${file}: a docblock moved into it, but its header carries no note saying so above its closing line`); - else edits.push({ start: at, end: at + HAND_DOCS_NOTE.length + 1, text: '' }); - } - modules.set(file, applyEdits(text, edits)); - } - return { host: applyEdits(engineText, hostEdits), modules, moved, failures }; -} - -/** - * The proof: undoing every move in the head lands on exactly what undoing - * every move in the base lands on, `engine.ts` and each hand module byte for - * byte. A base no slice has touched undoes to itself, so against it this is - * "the undo rebuilds the base"; against a base an earlier slice landed in, it - * proves this slice without re-proving that one's text. `baseModules` and - * `headModules` map a hand module file to its text (a file absent from one - * side fails). - */ -function verifyHandDocs(tm, baseText, headText, baseModules, headModules, { className = CLASS_NAME } = {}) { - const head = undoHandDocs(tm, headText, headModules, className); - const base = undoHandDocs(tm, baseText, baseModules, className); - const failures = [...head.failures, ...base.failures.map((f) => `base: ${f}`)]; - const firstDiff = (a, b) => { - const x = a.split('\n'); const y = b.split('\n'); - let i = 0; while (i < Math.max(x.length, y.length) && x[i] === y[i]) i += 1; - return `line ${i + 1}: undone base ${JSON.stringify(x[i] ?? null)} | undone head ${JSON.stringify(y[i] ?? null)}`; - }; - // The one edit the undo does not read back from the head is the import - // prune: recomputed from the head and applied to the base, and every binding - // it drops must be a name a moved docblock links. - const { text: prunedBase, removed: pruned } = pruneImports(tm, base.host, usedImportNames(tm, headText), { dropAttachedComments: true }); - const links = new Set(head.moved.flatMap((m) => [...linkedNames(m.doc)])); - for (const name of pruned) if (!links.has(name)) failures.push(`${name}: the head no longer imports it, and no moved docblock links it`); - if (head.host !== prunedBase) failures.push(`undoing the moves does NOT rebuild the base ${HOST_BASENAME} (${firstDiff(prunedBase, head.host)})`); - const files = [...new Set([...baseModules.keys(), ...headModules.keys()])].sort(); - for (const file of files) { - const b = base.modules.get(file); const h = head.modules.get(file); - if (b == null || h == null) { failures.push(`${file}: only in the ${b == null ? 'head' : 'base'}`); continue; } - if (h !== b) failures.push(`undoing the moves does NOT rebuild the base ${file} (${firstDiff(b, h)})`); - } - const baseMoved = new Set(base.moved.map((m) => m.name)); - return { - failures, moved: head.moved.filter((m) => !baseMoved.has(m.name)), baseMoved: base.moved.length, pruned, - modules: files.length, linesBefore: lineCount(baseText), linesAfter: lineCount(headText), - }; -} - -function planReportHandDocs(planned) { - const out = [`# codemod-split-engine --hand-docs (${HAND_DOCS_CARD}): the hand series' private docblocks`, '']; - const byModule = new Map(); - for (const r of planned.movers) byModule.set(r.module, [...(byModule.get(r.module) ?? []), r]); - let total = 0; - for (const [file, rs] of [...byModule].sort(([a], [b]) => (a < b ? -1 : 1))) { - const lines = rs.reduce((n, r) => n + soleDocblock(r.lead).doc.split('\n').length, 0); - total += lines; - out.push(`- ${file}: ${rs.length} docblock(s), ${lines} line(s): ${rs.map((r) => r.name).join(', ')}`); - } - out.push('', `moves: ${planned.movers.length}/${planned.records.length} hand-series stubs, ${total} docblock line(s)`); - const stays = new Map(); - for (const r of planned.records) if (r.reason) stays.set(r.reason, [...(stays.get(r.reason) ?? []), r.name]); - for (const [reason, names] of stays) out.push(`stays (${reason}): ${names.length}: ${names.join(', ')}`); - return out.join('\n'); -} - -function printVerifyHandDocs(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - console.log(`hand docblocks: ${v.moved.length} moved (${v.moved.reduce((n, m) => n + m.lines, 0)} lines) across ${new Set(v.moved.map((m) => m.module)).size} module(s), ${v.baseMoved} already moved at base; ` + - `${HOST_BASENAME} ${v.linesBefore} -> ${v.linesAfter} lines; undoing every move ${v.failures.some((f) => f.startsWith('undoing')) ? 'does NOT rebuild' : 'rebuilds'} the base, ` + - `undone the same way, for ${HOST_BASENAME} and its ${v.modules} hand module(s) byte-for-byte, once the ${v.pruned.length} import binding(s) ` + - `only a moved docblock linked are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -/** The hand modules `engine.ts`'s hand stubs name, read through `read(file)` (null: absent). */ -function handModuleTexts(tm, engineText, read) { - const out = new Map(); - for (const file of [...new Set(handStubs(tm, engineText).map((s) => s.module))].sort()) { - const text = read(file); - if (text != null) out.set(file, text); - } - return out; -} - -/** `--hand-docs`: plan, write or re-prove the third pass. */ -async function mainHandDocs(tm, argv) { - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--hand-docs --verify needs --base '); - const baseText = gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`); - const headText = readFileSync(HOST_PATH, 'utf8'); - const baseModules = handModuleTexts(tm, baseText, (f) => { try { return gitShow(ref, `${SRC_REL}/${f}`); } catch { return null; } }); - const headModules = handModuleTexts(tm, baseText, readSibling); - const v = verifyHandDocs(tm, baseText, headText, baseModules, headModules); - printVerifyHandDocs(v); - return v.failures.length === 0 ? 0 : 1; - } - const j = argv.indexOf('--modules'); - const modules = j >= 0 ? (argv[j + 1] ?? '').split(',').map((s) => s.trim()).filter(Boolean) : null; - if (j >= 0 && modules.length === 0) refuse('--modules needs a comma-separated list of hand module files'); - const input = readFileSync(HOST_PATH, 'utf8'); - const moduleTexts = handModuleTexts(tm, input, readSibling); - const planned = planHandDocs(tm, input, moduleTexts, { modules }); - console.log(planReportHandDocs(planned)); - const out = generateHandDocs(tm, input, moduleTexts, planned); - const files = new Map([[HOST_BASENAME, out.host], ...moduleTexts, ...out.modules]); - console.log(`output tree sha256: ${treeHash(files)} (input sha256 ${sha256(input)})`); - const v = verifyHandDocs(tm, input, out.host, moduleTexts, new Map([...moduleTexts, ...out.modules])); - printVerifyHandDocs(v); - if (v.failures.length > 0) { - console.error('✗ the generated moves fail the undo proof: nothing written. Report the fork; never hand-edit the moves.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - writeFileSync(HOST_PATH, out.host); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} hand module(s) under ${SRC_REL}`); - return 0; -} - -// ── The fourth pass: named methods onto the split class (#30055) ───────────── -// -// The first pass refuses an `engine.ts` that already carries its stubs: it is -// run on an unsplit file, never on its own output, and `main` has been split -// since #29986. A method a stay rule held then (a path pin since retired, a -// return type since spelled) is moved by THIS pass instead, on the split file: -// `--members a,b` names the methods, and each goes exactly as the first pass -// would have taken it. The same stay rules apply, and any reason refuses: the -// pass names what it moves and never decides it. The stub, the facet member and -// the docblock rule are the first pass's, and the member goes into the facet -// module of its section that the first pass wrote, in class order. That -// module's header, host interface and import lines grow by what the moved -// bodies read, and so do the class's statics route and that facet's host -// factory. Nothing else moves, and the pass never widens a generated export -// list: that refuses (exit 2), and is a decision someone writes here. It -// reroutes a module onto the statics route only by R10 below, and starts a -// facet only by R11. -// -// The proof (`--members --verify --base REF` re-runs it) undoes the moves from -// the head, as the first pass's does: each moved body, docblock and `async` -// goes back onto its stub; each receiving module loses the moved members, the -// host members and import bindings only they read, and its header their names; -// the statics route and the host factory lose what only they read. The result -// must be the base `engine.ts` and modules byte for byte (the base's import -// bindings only moved bodies read pruned from it, as the first pass prunes -// them), every other generated module unchanged, and each moved member its -// base method's text exactly, by a stay-rule reading of the base. -// -// Two shapes a hand edit leaves are read, not refused (#30572). A header the -// hand wrote on after, in its first paragraph, keeps those words after the -// sentence this pass rewrites (`headerNamesOf`), when the two rewrap to the -// header byte for byte. And the one import edit a read of the head cannot tell -// back, a binding a moved body brought that something staying still reads (a -// docblock link the base left unresolved), is inverted from the base's import -// block (`importEditsOf`): the bindings the head added or widened, each one a -// moved member reads, and none the base had dropped or narrowed. -// -// Three closed rules let a body move that reads the engine other than as -// `this.member` (#30020; the state stays on the class, one owner): -// -// - R1, the identity port. A bare `this` in the body (`ql: this`, -// `new ScopedContext(ctx, this)`, `(this as any)._flag`) reads -// `this.facade`, a host entry the factory fills with the engine itself -// (`facade: engine`), so each such site sees the object the method saw. The -// undo is the one inverse rewrite, `this.facade` back to `this`, which is -// unambiguous because a base body that reads `this.facade` refuses -// (`unknown-member`) and so does a class that declares `facade`. A `this` -// in a parameter, a type or a `typeof this` still stays. -// - R3, a computed key. `this[k]`, where `k` is typed as string literals that -// each name a field, reads (and writes) those fields through host getters -// (and setters); the body's text is unchanged. Any other key stays. -// - R4, an exported name. A name `engine.ts` declares and already exports -// (`ScopedContext`) is imported from `./engine.js` (lever (a) of ruling -// 6591753301), and the header's import paragraph says so; no export list -// widens, and a routed module refuses unless its `./engine.js` line -// already imports the name in a form that serves the read (then nothing -// is imported). -// - R8, definite-assignment wiring (`--members constructor`). The -// constructor moves as a method does, into its section's facet as -// `construct` (taking only the parameters its body reads), and its stub -// keeps the signature. A field a strict compiler requires the constructor -// to assign (`requiredFieldsOf`: moved out, it is a TS2564) stays assigned -// on the class: each LEADING `this.F = EXPR;`, EXPR reading no `this` and -// no top-level name of `engine.ts`, becomes `this.F = Facet.constructF(…)` -// in the stub, `constructF` returns EXPR, and the facet body holds a marker -// line in the statement's place, which the undo turns back into it. Any -// other write to such a field keeps the constructor whole -// (`definite-assignment`). -// -// One more rule puts a written module on the statics route (#30020 E4): -// -// - R10, the statics route for a written module. A body that reads a -// non-public static (`ObjectQL.REFERENCE_PROBE_BATCH`) moving into a module -// the first pass wrote off the route takes the route the first pass would -// have given it (`rerouteModule`): the one `import type { ObjectQL }` line -// becomes the routed pair, the host interface types its members by -// `ObjectQLClass`, and the header gains `STATICS_PARA`. A module of any -// other shape refuses, and so does one whose code names `ObjectQL` anywhere -// else. The undo (`unrouteModule`) is the inverse rewrite, applied to the -// head before the moved members come out, due only where the base module -// was off the route and a moved member reads a static; a member the module -// keeps that reads one fails it. -// -// And one rule starts a facet (#30020 E6): -// -// - R11, a facet the anchor names and the first pass never wrote. A section -// whose every method a stay rule held when the file was split (`update`, -// which reads `this` bare) has a module in `SECTION_ANCHORS` and none on -// disk. Its first move writes that module as the first pass writes one for -// the moved members (`moduleText`; a name `engine.ts` imports from the -// leaf is the leaf's there, as it was then), routed when one of them reads -// a non-public static, and makes the edits the first pass makes for a -// facet: `engine.ts` gains the facet's import, under its comment, among -// the facet imports in section order; and, when a body reads the class, -// its host in the hosts import, its install call in the install block -// (sorted) and its line in `HOSTS_MODULE` (`hostsTexts` of one module -// more). A constructor never starts a facet. The undo deletes the module -// and those lines: the started module must be exactly the text a stay-rule -// reading of the base renders, and `engine.ts` and `HOSTS_MODULE` without -// them must be their base byte for byte. -// -// A statement the hand grew on one line past the wrap width (`runStyles`) is -// kept on one line by the move and by the undo alike. - -const MEMBERS_CARD = '#30055'; - -/** A first-pass stub's marker line: its module, whether its docblock moved, whether it hands a host. */ -const STUB_MARK_LINE = new RegExp( - `^ *// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(engine-[a-z0-9-]+\\.ts)\`(, ${DOC_MOVED})?( \\(see \`[A-Za-z]+\`\\))?\\.$`, 'm'); - -const lineStartOf = (text, pos) => text.lastIndexOf('\n', pos - 1) + 1; - -/** The 1-based line at which `a` and `b` first differ. */ -function firstDiffLine(a, b) { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) i += 1; - return a.slice(0, i).split('\n').length; -} - -/** Apply non-overlapping `{ start, end, text }` edits; ties apply in the order given. */ -function applyOrderedEdits(text, edits) { - const sorted = edits.map((e, i) => ({ ...e, i })).sort((a, b) => b.start - a.start || b.end - a.end || b.i - a.i); - let out = text; - let floor = Infinity; - for (const e of sorted) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - return out; -} - -/** - * `pruneImports` for this pass's `engine.ts`, with one difference: the first - * pass's import of the leaf is a `namedStatement`, so a binding dropped from it - * leaves it wrapped as `namedStatement` wraps it (`pruneImports` would rewrite - * a wrapped list one binding per line). Pure. Returns `{ text, removed }`. - */ -function pruneHostImports(tm, text, used) { - const ts = tm.ts; - const sf = parseSourceFile(HOST_PATH, text); - const edits = []; - const removed = []; - for (const st of sf.statements) { - if (!ts.isImportDeclaration(st) || st.moduleSpecifier.text !== leafSpecifier()) continue; - const clause = st.importClause; - const nb = clause && clause.namedBindings; - if (!clause || clause.name || !nb || !ts.isNamedImports(nb) || nb.elements.some((e) => e.propertyName || e.isTypeOnly)) continue; - const names = nb.elements.map((e) => e.name.text); - const kept = names.filter((n) => used.has(n)); - if (kept.length === names.length) continue; - removed.push(...names.filter((n) => !used.has(n))); - const end = text[st.getEnd()] === '\n' ? st.getEnd() + 1 : st.getEnd(); - edits.push(kept.length === 0 - ? { start: st.getStart(sf), end, text: '' } - : { start: st.getStart(sf), end: st.getEnd(), text: namedStatement(clause.isTypeOnly ? 'import type' : 'import', kept, ` from '${leafSpecifier()}';`) }); - } - const rest = pruneImports(tm, applyOrderedEdits(text, edits), used); - return { text: rest.text, removed: [...removed, ...rest.removed].sort() }; -} - -/** The analysis context of an `engine.ts` the first pass has split: `plan`'s, without its unsplit-file guards. */ -function membersContext(tm, text, { pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES, classNeedles = CLASS_PATH_READER_NEEDLES } = {}) { - const sf = parse(tm, HOST_PATH, text); - const cls = sf.getClass(CLASS_NAME); - if (!cls) refuse(`no class ${CLASS_NAME} in ${HOST_BASENAME}`); - return { text, sf, cls, members: instanceMembers(tm, cls), scope: moduleScope(tm, sf), statics: classStaticsOf(tm, cls), pins, needles, classNeedles, identityPort: true }; -} - -const isGeneratedStub = (m) => Boolean(m.getBody() && STUB_MARK_LINE.test(m.getBody().getText())); - -/** The header docblock's opening lines of a facet module (`moduleHeaderLines`), as a region. */ -function headerRegionOf(text) { - const open = text.indexOf('\n/**\n'); - const end = text.indexOf('\n *\n * A MOVE, not a redesign.', open); - return open < 0 || end < 0 ? null : { start: open + 5, end }; -} - -/** - * The names a facet module's header lists, read back; null unless the header - * is `moduleHeaderLines` of them. The list is the header's own, which a hand - * edit to the module may have left behind its members: this pass adds and - * removes its names in it and leaves the rest as it stands. - * - * A hand edit may also have written on after the header's sentence, in the - * same paragraph, about a member it wrote into the module (#30572: one the - * first pass never moved, so the list does not name it). Those words come back - * as `tail`, and the header is accepted only when `moduleHeaderLines` of the - * names and that tail rewraps to it byte for byte: what the pass rewrites is - * then exactly the sentence it owns, with the hand's words after it carried - * over, and the undo rewraps the same tail. - */ -function headerNamesOf(text, title) { - const region = headerRegionOf(text); - if (!region) return null; - const prose = text.slice(region.start, region.end).split('\n').map((l) => l.replace(/^ \*( |$)/, '')).join(' '); - const i = prose.indexOf(' the bodies of '); - const j = i < 0 ? -1 : prose.indexOf(HEADER_SENTENCE_END, i); - if (j < 0) return null; - const names = [...prose.slice(i, j).matchAll(/`([^`]+)`/g)].map((m) => m[1]); - const rest = prose.slice(j + HEADER_SENTENCE_END.length); - const tail = rest === '' ? [] : rest.startsWith(' ') ? rest.slice(1).split(' ') : null; - if (!tail || tail.some((w) => w === '')) return null; - return moduleHeaderLines(title, names, tail).join('\n') === text.slice(region.start, region.end) ? { region, names, tail } : null; -} - -/** A facet module's host interface: its member lines, each `[readonly ]m: Class['m'];`, in order. */ -function interfaceRegionOf(text, hostName) { - const head = `\nexport interface ${hostName} {\n`; - const i = text.indexOf(head); - if (i < 0) return null; - const start = i + head.length; - const end = text.indexOf('\n}', start); - const members = new Map(); - let classType = null; - const lines = text.slice(start, end).split('\n'); - for (let i = 0; i < lines.length; i += 1) { - const line = lines[i]; - if (line === FACADE_DOC || line === SCOPED_FACADE_DOC) { - // The identity port (#30020 R1): its docblock, then `readonly facade: ;` - // (an engine's, or a scoped class's instance's). - const f = new RegExp(`^ {2}readonly ${FACADE_MEMBER}: ([A-Za-z]+);$`).exec(lines[i + 1] ?? ''); - if (!f || (classType && classType !== f[1])) return null; - classType = f[1]; - members.set(FACADE_MEMBER, { line: `${line}\n${lines[i + 1]}`, readonly: true, facade: true }); - i += 1; - continue; - } - const m = /^ {2}(readonly )?([A-Za-z_$][\w$]*): ([A-Za-z]+)\['([A-Za-z_$][\w$]*)'\];$/.exec(line); - if (!m || m[2] !== m[4] || (classType && classType !== m[3])) return null; - classType = m[3]; - members.set(m[2], { line, readonly: Boolean(m[1]) }); - } - const names = [...members.keys()]; - if (names.join() !== [...names].sort().join()) return null; - return { start, end, members, classType }; -} - -/** One facet's host factory in the class's install block (`hostInstallLines`), parsed back; null when it is not that shape. */ -function installRegionOf(text, moduleFile) { - const head = ` ${hostVarOf(moduleFile)}.install((engine) => ({\n`; - const i = text.indexOf(head); - if (i < 0 || text.indexOf(head, i + 1) >= 0) return null; - const start = i + head.length; - const end = text.indexOf('\n }));', start); - if (end < 0) return null; - const members = new Map(); - const written = new Set(); - for (const line of text.slice(start, end).split('\n')) { - let m; - if (line === FACADE_INSTALL_LINE) members.set(FACADE_MEMBER, 'facade'); - else if ((m = /^ {6}get ([\w$]+)\(\) \{ return engine\.\1; \},$/.exec(line))) members.set(m[1], 'getter'); - else if ((m = /^ {6}set ([\w$]+)\(v\) \{ engine\.\1 = v; \},$/.exec(line))) written.add(m[1]); - else if ((m = /^ {6}get ([\w$]+)\(\) \{ return engine\.\1\.bind\(engine\); \},$/.exec(line))) members.set(m[1], 'method'); - else if ((m = /^ {6}([\w$]+): \(\.\.\.a\) => engine\.\1\(\.\.\.a\),$/.exec(line))) members.set(m[1], 'method'); - else return null; - } - if (hostInstallLines(members, written).join('\n') !== text.slice(start, end)) return null; - return { start, end, members, written }; -} - -/** The statics route (`staticsTexts`) in `engine.ts`, parsed back: its kinds and both regions; null when absent or not that shape. */ -function staticsRegionOf(text) { - const head = `export interface ${STATICS_HOST_NAME} {\n`; - const i = text.indexOf(head); - if (i < 0) return null; - const end = text.indexOf('\n}', i); - const kinds = new Map(); - for (const line of text.slice(i + head.length, end).split('\n')) { - const m = new RegExp(`^ {2}readonly ([\\w$]+): \\(typeof ${CLASS_NAME}\\)\\['([\\w$]+)'\\];$`).exec(line); - if (!m || m[1] !== m[2]) return null; - kinds.set(m[1], text.includes(` ${m[1]}: { value: (...args: Parameters)`) ? 'method' : 'getter'); - } - const t = staticsTexts(kinds); - const a = text.indexOf(t.ahead); - const b = text.indexOf(t.block); - if (a < 0 || b < 0 || text.indexOf(t.ahead, a + 1) >= 0 || text.indexOf(t.block, b + 1) >= 0) return null; - return { kinds, ahead: { start: a, end: a + t.ahead.length }, block: { start: b, end: b + t.block.length } }; -} - -// R11 (#30020 E6), a facet the anchor names and the first pass never wrote: -// the module, `engine.ts`'s three edits and `HOSTS_MODULE`'s, each rendered as -// the first pass renders it and each read back for the undo. - -/** The facet modules `HOSTS_MODULE` holds a host for, read back; null unless it is `hostsTexts` of them. */ -function hostsModuleFilesOf(text) { - const files = [...text.matchAll(/^import type \{ [A-Za-z]+Host \} from '\.\/(engine-[a-z0-9-]+)\.js';$/gm)].map((m) => `${m[1]}.ts`); - const facets = files.map((moduleFile) => ({ moduleFile, members: new Map(), written: new Set() })); - return hostsTexts(facets).module === text ? files : null; -} - -/** `HOSTS_MODULE`'s text for these facet modules (`hostsTexts`'s module half, which reads only their names). */ -const hostsModuleText = (files) => hostsTexts(files.map((moduleFile) => ({ moduleFile, members: new Map(), written: new Set() }))).module; - -/** A facet's import in `engine.ts`, under its comment, as `generate` writes it: two lines, each ending in a newline. */ -function facetImportText(file, title, anyHost) { - return `// ${MARK} ${title}: the methods of the same names below hand the bodies` + - `${anyHost ? ` what they read (\`${hostNameOf(file)}\`)` : ' their arguments'}.\n` + - `import { ${facetNameOf(file)} } from './${file.replace(/\.ts$/, '.js')}';\n`; -} - -/** The comment that heads the hosts import in `engine.ts`, as `generate` writes it. */ -const HOSTS_IMPORT_COMMENT = `// ${MARK} The facets' hosts, one per engine, which the static block at the end of the class builds.\n`; - -/** - * Where a started facet's import goes in `engine.ts`: at the comment line of - * the first facet import after it in section order, or, with none written - * after it, at the hosts import's comment. Null when neither is there. - */ -function facetImportAt(text, file, anchors) { - const rows = anchors.filter((row) => row[2]); - for (const row of rows.slice(rows.findIndex((r) => r[2] === file) + 1)) { - const i = text.indexOf(`\nimport { ${facetNameOf(row[2])} } from './${row[2].replace(/\.ts$/, '.js')}';\n`); - if (i < 0) continue; - const at = lineStartOf(text, i); - return text.startsWith(`// ${MARK} ${row[1]}: `, at) ? at : null; - } - const h = text.indexOf(`\n${HOSTS_IMPORT_COMMENT}`); - return h < 0 ? null : h + 1; -} - -/** The hosts import in `engine.ts` (a `namedStatement` of the host names, sorted); null unless it is one in that form. */ -function hostsImportOf(tm, text) { - const ts = tm.ts; - const spec = `./${HOSTS_MODULE.replace(/\.ts$/, '.js')}`; - const sf = parseSourceFile(HOST_PATH, text); - const decls = sf.statements.filter((st) => ts.isImportDeclaration(st) && st.moduleSpecifier.text === spec); - if (decls.length !== 1) return null; - const nb = decls[0].importClause?.namedBindings; - if (!nb || !ts.isNamedImports(nb) || decls[0].importClause.isTypeOnly || nb.elements.some((e) => e.propertyName || e.isTypeOnly)) return null; - const names = nb.elements.map((e) => e.name.text); - const start = decls[0].getStart(sf); - const end = decls[0].getEnd(); - return text.slice(start, end) === namedStatement('import', [...names].sort(), ` from '${spec}';`) ? { start, end, names, spec } : null; -} - -/** The head of the class's install block (`hostsTexts`'s block half), through its `static {` line. */ -const INSTALL_BLOCK_HEAD = [ - ` // ${MARK} Installs each facet's host factory (\`${HOSTS_MODULE}\`): a static block adds`, - ' // no member to the class, so the published `.d.ts` does not move.', - ' static {', - '', -].join('\n'); - -/** One facet's install call, whole, as `hostsTexts` writes it in the install block. */ -const installCallText = (file, members, written) => - ` ${hostVarOf(file)}.install((engine) => ({\n${hostInstallLines(members, written).join('\n')}\n }));\n`; - -/** Where a started facet's install call goes: before the first call whose host sorts after it, else at the block's close. Null without the block. */ -function installCallAt(text, file) { - const i = text.indexOf(INSTALL_BLOCK_HEAD); - if (i < 0 || text.indexOf(INSTALL_BLOCK_HEAD, i + 1) >= 0) return null; - const start = i + INSTALL_BLOCK_HEAD.length; - const end = text.indexOf('\n }\n', start - 1); - if (end < 0) return null; - const mine = hostVarOf(file); - for (const m of text.slice(start, end + 1).matchAll(/^ {4}([\w$]+)\.install\(\(engine\) => \(\{$/gm)) { - if (m[1] > mine) return start + m.index; - } - return end + 1; -} - -/** One facet's install call, whole (from its line start through its closing line's newline); null unless it is `installCallText`'s shape. */ -function installCallRegionOf(text, file) { - const inst = installRegionOf(text, file); - if (!inst) return null; - const head = ` ${hostVarOf(file)}.install((engine) => ({\n`; - const close = '\n }));\n'; - if (text.slice(inst.end, inst.end + close.length) !== close) return null; - return { start: inst.start - head.length, end: inst.end + close.length, inst }; -} - -/** - * A started facet module's text: `moduleText` of the moved members, each - * binding `engine.ts` imports from the leaf read as the leaf's top-level name - * it was when the first pass split the file (it renders those from the leaf, - * after the package imports, as `importPair` writes them). Refuses an aliased - * or default leaf binding, which the first pass never wrote. - */ -function startedModuleText(scope, file, title, records, routed) { - const leaf = leafSpecifier(); - const leafNames = new Set(); - const movers = records.map((r) => { - const imports = new Map(); - const moduleRefs = new Map(r.moduleRefs); - for (const [local, use] of r.imports) { - const b = scope.bindings.get(local); - if (!b || b.specifier !== leaf) { imports.set(local, use); continue; } - if (b.form !== 'named' || b.imported !== local) refuse(`${file}: ${local} is bound from the leaf in a form the first pass does not write`); - leafNames.add(local); - const prev = moduleRefs.get(local); - moduleRefs.set(local, { value: Boolean(prev && prev.value) || (use.value && !b.typeOnly) }); - } - return { ...r, imports, moduleRefs }; - }); - return moduleText(file, title, movers, scope, leafNames, routed); -} - -// R10 (#30020 E4), the statics route for a written module. The first pass -// routes a module when one of its bodies reads a non-public static, and a -// module it wrote without one carries `import type { ObjectQL }`. A body the -// fourth pass moves into such a module that reads a non-public static takes -// the route the first pass would have given the module: the one `./engine.js` -// line becomes the routed pair (`ObjectQLStatics` AS `ObjectQL`, the class as -// `ObjectQLClass`), the host interface types its members by `ObjectQLClass`, -// and the header gains `STATICS_PARA`, so the module is the text the first -// pass writes for a routed module. The members the module already held name -// `ObjectQL` nowhere else (a hand edit that does refuses), so they read what -// they read. The undo is the one inverse rewrite, applied to the head before -// the moved members are taken out, and is due only when the base module was -// not routed and a moved member reads a static. - -/** Is a facet module on the statics route (`ObjectQLStatics` imported AS `ObjectQL`)? */ -const routesStatics = (text) => new RegExp(`^import \\{[^}]*\\b${STATICS_NAME} as ${CLASS_NAME}\\b[^}]*\\} from '\\./engine\\.js';$`, 'm').test(text); - -/** - * The `./engine.js` run of a written module, the statics route's pair, and - * the run R10 writes on either side of it. Off the route the first pass - * writes the class as a type-only name beside the module's other plain - * `./engine.js` names (`InsertManyRowOutcome`, `dependsOnPinned`); on it, the - * pair in its place beside the same names. Both are `importPair`'s form. - */ -const ROUTE_PAIR = [ - [`${STATICS_NAME} as ${CLASS_NAME}`, { value: true }], - [`${CLASS_NAME} as ${CLASS_TYPE_ALIAS}`, { value: false }], -]; -const unroutedEngineImport = (others = new Map()) => importPair('./engine.js', new Map([...others, [CLASS_NAME, { value: false }]])).join('\n'); -const routedEngineImports = (others = new Map()) => importPair('./engine.js', new Map([...others, ...ROUTE_PAIR])).join('\n'); - -/** - * A module's `./engine.js` run as `importPair` uses (`name` or `imported as - * local` -> { value }), its span, and its names other than `skip`; null when - * it has none or a binding that is not a named one. - */ -function engineRunOf(tm, file, text, skip) { - const decls = importDeclsOf(tm, file, text).filter((d) => d.specifier === './engine.js'); - if (decls.length === 0) return null; - const uses = new Map(); - for (const d of decls) { - for (const [local, b] of d.bindings) { - if (b.form !== 'named') return null; - uses.set(b.imported === local ? local : `${b.imported} as ${local}`, { value: b.value }); - } - } - const others = new Map([...uses].filter(([k]) => !skip.includes(k))); - const plain = [...others.keys()].every((k) => !k.includes(' as ')); - return { start: decls[0].start, end: decls.at(-1).end, text: text.slice(decls[0].start, decls.at(-1).end), uses, others, plain }; -} - -/** The identifiers named `name` in a module's code (comments are not code), outside its import declarations and the `skip` regions. */ -function codeIdentifiersNamed(tm, file, text, name, skip = []) { - const ts = tm.ts; - const sf = parseSourceFile(join(SRC_DIR, file), text); - const hits = []; - const visit = (node) => { - if (ts.isImportDeclaration(node)) return; - const at = node.getStart(sf); - if (skip.some(([a, b]) => at >= a && node.getEnd() <= b)) return; - if (ts.isIdentifier(node) && node.text === name) hits.push(at); - ts.forEachChild(node, visit); - }; - ts.forEachChild(sf, visit); - return hits; -} - -/** - * Does a module's code read a static off `ObjectQL` (`ObjectQL.x`)? Comments - * are not code. `members`, when given, narrows the reading to the facet - * class's members of those names. - */ -function readsClassStatic(tm, file, text, members = null) { - const ts = tm.ts; - const sf = parseSourceFile(join(SRC_DIR, file), text); - const facet = facetNameOf(file); - let found = false; - const visit = (node) => { - if (found) return; - if (members && ts.isClassElement(node) && ts.isClassDeclaration(node.parent) && node.parent.name?.text === facet && - !(node.name && ts.isIdentifier(node.name) && members.includes(node.name.text))) return; - if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === CLASS_NAME) { found = true; return; } - ts.forEachChild(node, visit); - }; - ts.forEachChild(sf, (node) => { - // Narrowed to members, only the facet class is read. - if (members && !(ts.isClassDeclaration(node) && node.name?.text === facet)) return; - visit(node); - }); - return found; -} - -/** The header's statics paragraph, in the place the first pass writes it: between the host paragraph and the import paragraph. */ -const staticsParaAt = (text) => { - const cycle = text.includes(VALUES_CYCLE_PARA) ? VALUES_CYCLE_PARA : TYPES_CYCLE_PARA; - return { routed: `\n *\n${STATICS_PARA}\n *\n${cycle}`, plain: `\n *\n${cycle}` }; -}; - -/** - * R10's rewrite: a written module off the statics route, put on it. Refuses - * (exit 2) any module that is not exactly the first pass's unrouted shape for - * it: on the route already, a `./engine.js` import other than the one - * type-only `ObjectQL`, no host interface, a header without one import - * paragraph, or `ObjectQL` / `ObjectQLClass` named anywhere else in its code. - */ -function rerouteModule(tm, file, text) { - if (routesStatics(text)) refuse(`${file}: already on the statics route`); - const run = engineRunOf(tm, file, text, [CLASS_NAME]); - if (!run || run.uses.get(CLASS_NAME)?.value !== false || !run.plain || run.text !== unroutedEngineImport(run.others)) { - refuse(`${file}: its \`./engine.js\` import is not the one a module off the statics route carries (\`${CLASS_NAME}\` type-only beside plain names, as the first pass writes it): this pass reroutes only that shape`); - } - const iface = interfaceRegionOf(text, hostNameOf(file)); - if (!iface || iface.classType !== CLASS_NAME) refuse(`${file}: it has no host interface typed by \`${CLASS_NAME}\`: this pass reroutes a module with a host only`); - const others = codeIdentifiersNamed(tm, file, text, CLASS_NAME, [[iface.start, iface.end]]); - if (others.length > 0) refuse(`${file}: its code names \`${CLASS_NAME}\` outside its import and its host interface (static-route-conflict: the route makes that name the statics)`); - if (codeIdentifiersNamed(tm, file, text, CLASS_TYPE_ALIAS).length > 0 || text.includes(`as ${CLASS_TYPE_ALIAS}`)) { - refuse(`${file}: it names \`${CLASS_TYPE_ALIAS}\`, the name the statics route gives the class`); - } - const para = staticsParaAt(text); - if (text.includes(STATICS_PARA) || text.indexOf(para.plain) < 0 || text.indexOf(para.plain) !== text.lastIndexOf(para.plain)) { - refuse(`${file}: its header carries no single import paragraph as the first pass writes one`); - } - const ifaceText = text.slice(iface.start, iface.end) - .replace(new RegExp(`: ${CLASS_NAME}\\['`, 'g'), `: ${CLASS_TYPE_ALIAS}['`) - .replace(`readonly ${FACADE_MEMBER}: ${CLASS_NAME};`, `readonly ${FACADE_MEMBER}: ${CLASS_TYPE_ALIAS};`); - const out = applyOrderedEdits(text, [ - { start: run.start, end: run.end, text: routedEngineImports(run.others) }, - { start: iface.start, end: iface.end, text: ifaceText }, - ]); - return withCyclePara(out.replace(para.plain, para.routed), file); -} - -/** - * R10's undo: a module the fourth pass put on the statics route, taken off - * it, from its head text alone (its moved members still in it). Checks the - * shape on the way (`fail`): exactly the routed pair from `./engine.js`, the - * statics paragraph once, in its place, and `ObjectQLClass` named only by the - * host interface. Returns the text, or null after a failure. - */ -function unrouteModule(tm, file, text, fail) { - const run = engineRunOf(tm, file, text, ROUTE_PAIR.map(([k]) => k)); - if (!run || ROUTE_PAIR.some(([k, u]) => run.uses.get(k)?.value !== u.value) || !run.plain || run.text !== routedEngineImports(run.others)) { - fail(`${file}: its \`./engine.js\` lines are not the statics route's pair as R10 writes it`); return null; - } - const iface = interfaceRegionOf(text, hostNameOf(file)); - if (!iface || iface.classType !== CLASS_TYPE_ALIAS) { fail(`${file}: its host interface is not typed by \`${CLASS_TYPE_ALIAS}\``); return null; } - if (codeIdentifiersNamed(tm, file, text, CLASS_TYPE_ALIAS, [[iface.start, iface.end]]).length > 0) { fail(`${file}: its code names \`${CLASS_TYPE_ALIAS}\` outside its host interface`); return null; } - const para = staticsParaAt(text); - const at = text.indexOf(para.routed); - if (at < 0 || text.indexOf(STATICS_PARA) !== text.lastIndexOf(STATICS_PARA)) { fail(`${file}: its header does not carry the statics paragraph once, in its place`); return null; } - const ifaceText = text.slice(iface.start, iface.end) - .replace(new RegExp(`: ${CLASS_TYPE_ALIAS}\\['`, 'g'), `: ${CLASS_NAME}['`) - .replace(`readonly ${FACADE_MEMBER}: ${CLASS_TYPE_ALIAS};`, `readonly ${FACADE_MEMBER}: ${CLASS_NAME};`); - return applyOrderedEdits(text, [ - { start: run.start, end: run.end, text: unroutedEngineImport(run.others) }, - { start: iface.start, end: iface.end, text: ifaceText }, - { start: at, end: at + para.routed.length, text: para.plain }, - ]); -} - -/** The facet class of a module and its members' texts, each from its line start; null unless they are joined by one blank line. */ -function facetMembersOf(tm, moduleFile, text) { - const sf = parse(tm, join(SRC_DIR, moduleFile), text); - const facet = sf.getClass(facetNameOf(moduleFile)); - if (!facet) return null; - const open = `export class ${facetNameOf(moduleFile)} {\n`; - const bodyStart = text.indexOf(open); - if (bodyStart < 0) return null; - const start = bodyStart + open.length; - const end = facet.getEnd() - 2; - const members = facet.getMembers().map((m) => ({ name: m.getName(), node: m, text: text.slice(lineStartOf(text, m.getStart(true)), m.getEnd()) })); - if (members.length === 0 || members.map((m) => m.text).join('\n\n') !== text.slice(start, end)) return null; - return { start, end, members }; -} - -/** The `Pick` keys a facet member's `this` names, or [] when it takes no host. */ -function picksOf(member) { - const p = member.node.getParameters()[0]; - if (!p || p.getName() !== 'this') return []; - const m = /^this: Pick<[A-Za-z]+, (.+)>$/.exec(p.getText()); - return m ? m[1].split(' | ').map((q) => q.slice(1, -1)) : ['']; -} - -/** A module's import declarations, each with its bindings (local -> { form, imported, value }). */ -function importDeclsOf(tm, moduleFile, text) { - const ts = tm.ts; - const sf = parseSourceFile(join(SRC_DIR, moduleFile), text); - return sf.statements.filter((st) => ts.isImportDeclaration(st)).map((st) => { - const clause = st.importClause; - const declType = Boolean(clause && clause.isTypeOnly); - const bindings = new Map(); - if (clause && clause.name) bindings.set(clause.name.text, { form: 'default', value: !declType }); - const nb = clause && clause.namedBindings; - if (nb && ts.isNamespaceImport(nb)) bindings.set(nb.name.text, { form: 'namespace', value: !declType }); - if (nb && ts.isNamedImports(nb)) { - for (const e of nb.elements) bindings.set(e.name.text, { form: 'named', imported: (e.propertyName ?? e.name).text, value: !declType && !e.isTypeOnly }); - } - return { specifier: st.moduleSpecifier.text, start: st.getStart(sf), end: st.getEnd(), bindings }; - }); -} - -/** The lines one specifier's bindings render to in a facet module: the leaf and `engine.ts` by `importPair`, a package by `specifierImportLines`. */ -function specifierLines(specifier, bindings, styles = {}) { - if (specifier === leafSpecifier() || specifier === './engine.js') { - if ([...bindings].some(([local, e]) => e.form !== 'named' || e.imported !== local)) return null; - return importPair(specifier, new Map([...bindings].map(([n, e]) => [n, { value: e.value }])), styles); - } - return specifierImportLines(specifier, bindings); -} - -/** - * Drop the import bindings nothing in a facet module reads, re-rendering each - * specifier's lines as the first pass writes them (`specifierLines`), so a - * pruned leaf list wraps as `namedStatement` wraps it. `inverse` is the import - * edits a move made that a read cannot tell back (`importEditsOf`): the - * bindings it added are dropped though something left still reads them, and - * the ones it widened from type-only to value are made type-only again. - */ -function pruneModuleImports(tm, moduleFile, text, inverse = { added: new Set(), widened: new Set() }) { - const used = usedImportNames(tm, text); - const decls = importDeclsOf(tm, moduleFile, text); - const edits = []; - for (const specifier of new Set(decls.map((d) => d.specifier))) { - const run = decls.filter((d) => d.specifier === specifier); - const have = new Map(); - for (const d of run) for (const [local, e] of d.bindings) have.set(local, e); - const key = (local) => importKey(specifier, local); - const kept = new Map([...have] - .filter(([local]) => used.has(local) && !inverse.added.has(key(local))) - .map(([local, e]) => [local, inverse.widened.has(key(local)) ? { ...e, value: false } : e])); - if (kept.size === have.size && [...kept].every(([local, e]) => e.value === have.get(local).value)) continue; - const start = run[0].start; - if (kept.size === 0) { - const end = text[run.at(-1).end] === '\n' ? run.at(-1).end + 1 : run.at(-1).end; - edits.push({ start, end, text: '' }); - } else { - const lines = specifierLines(specifier, kept, runStyles(text, run, specifier) ?? {}); - if (!lines) refuse(`${moduleFile}: ${specifier} is imported in a form this pass does not write`); - edits.push({ start, end: run.at(-1).end, text: lines.join('\n') }); - } - } - return applyOrderedEdits(text, edits); -} - -/** - * Decide the moves `names` asks for on a split `engine.ts`. Refuses (exit 2) - * on a name the class does not declare as one method, a method already a stub, - * one any stay rule of the first pass holds, and on any shape this pass does - * not grow a written module by (see the section above). Pure. - */ -function planMembers(tm, text, moduleTexts, names, { anchors = SECTION_ANCHORS, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES, classNeedles = CLASS_PATH_READER_NEEDLES } = {}) { - if (!names || names.length === 0) refuse('--members needs a comma-separated list of ObjectQL method names'); - if (new Set(names).size !== names.length) refuse(`--members names a method twice: ${names.join(', ')}`); - const ctx = membersContext(tm, text, { pins, needles, classNeedles }); - const methodNames = new Set(ctx.cls.getMethods().map((m) => m.getName())); - const stalePins = Object.keys(pins).filter((n) => !methodNames.has(n) && !ctx.scope.bindings.has(n)); - if (stalePins.length > 0) refuse(`PATH_READER_PINS names what ${HOST_BASENAME} no longer declares: ${stalePins.join(', ')}`); - const sectionOf = readSections(ctx.cls, anchors); - const records = []; - for (const name of names) { - // The constructor (#30020 R8): read with the statements R8 keeps on the - // class left out; their right sides' imports go with the facet. - const isCtor = name === 'constructor'; - const found = isCtor ? ctx.cls.getConstructors() : ctx.cls.getMethods().filter((m) => m.getName() === name); - if (found.length !== 1) refuse(`--members names ${name}, which ${CLASS_NAME} declares as ${found.length === 0 ? `no ${isCtor ? 'constructor' : 'method'}` : `more than one ${isCtor ? 'constructor' : 'method'}`}`); - const m = found[0]; - if (isGeneratedStub(m)) refuse(`${name} is already moved: its body is a ${MARK} stub`); - const da = isCtor ? definiteAssignmentsOf(tm, ctx, m) : null; - const read = readMethod(tm, ctx, m, { skip: da ? da.r8.map((a) => [a.start, a.end]) : [] }); - if (da) { - read.reasons.push(...da.reasons); - if (ctx.members.has(CTOR_FACET_MEMBER)) read.reasons.push(`ctor-facet-name: ${CTOR_FACET_MEMBER}`); - for (const a of da.r8) { - for (const [local, use] of a.imports) { - const prev = read.imports.get(local); - read.imports.set(local, { value: Boolean(prev && prev.value) || use.value }); - } - } - } - const section = sectionOf(m); - if (!section) read.reasons.unshift('no-section'); - else if (section[2] === null) read.reasons.unshift('section-kept'); - else for (const p of m.getParameters()) if (p.getName() === facetNameOf(section[2])) read.reasons.push(`parameter-shadows: ${p.getName()}`); - if (read.reasons.length > 0) { - refuse(`${name} stays on the class, as the first pass would keep it: ${read.reasons.map((r) => `${r} (${STAY_REASONS[r.split(':')[0]] ?? r})`).join('; ')}`); - } - const docStart = m.getStart(true); - const doc = !isCtor && m.getScope() === 'private' && docStart < m.getStart() ? text.slice(docStart, m.getStart()) : null; - const ctorParts = da ? { r8: da.r8, facetNames: [...da.r8.map((a) => a.fn), CTOR_FACET_MEMBER] } : {}; - records.push({ name, node: m, module: section[2], section: section[1], doc: isCtor ? null : doc, ...read, ...ctorParts }); - } - records.sort((a, b) => a.node.getStart() - b.node.getStart()); - const modules = new Map(); - for (const r of records) modules.set(r.module, [...(modules.get(r.module) ?? []), r]); - const reroutes = new Set(); - const starts = new Set(); - for (const [file, movers] of modules) { - const mod = moduleTexts.get(file); - // R11 (#30020 E6): a module the anchor names and the disk lacks is started, - // as the first pass writes one for these movers. - const starting = mod == null; - if (starting) { - if (movers.some((r) => r.r8)) refuse(`${file} is not on disk, and a constructor never starts a facet (R11 starts one for methods)`); - for (const n of [facetNameOf(file), hostNameOf(file), hostVarOf(file)]) { - if (ctx.scope.bindings.has(n)) refuse(`${HOST_BASENAME} already binds ${n}, a name R11 generates for ${file}`); - } - if (movers.some((r) => r.host.size > 0)) { - const hosts = moduleTexts.get(HOSTS_MODULE); - if (hosts == null || !hostsModuleFilesOf(hosts)) refuse(`${HOSTS_MODULE} is not on disk as the first pass wrote it: R11 adds ${file}'s host to it`); - } - starts.add(file); - } else if (!mod.includes(MARK)) refuse(`${file} is not on disk as the first pass wrote it: this pass grows a written facet, and starts one only for a module the disk lacks (R11)`); - // R10 (#30020 E4): a mover that reads a non-public static puts a module - // off the route on it, as the first pass routes a module for one; the - // rewrite refuses any module that is not the first pass's unrouted shape. - // A module R11 starts is routed as the first pass routes one. - let routed = starting ? movers.some((r) => r.readsNonPublicStatic) : routesStatics(mod); - if (!starting && !routed && movers.some((r) => r.readsNonPublicStatic)) { - rerouteModule(tm, file, mod); - reroutes.add(file); - routed = true; - } - const hasHost = starting || interfaceRegionOf(mod, hostNameOf(file)) !== null; - const typeImportsClass = !starting && new RegExp(`^import type \\{[^}]*\\b${CLASS_NAME}\\b[^}]*\\} from '\\./engine\\.js';$`, 'm').test(mod); - for (const r of movers) { - if (r.host.size > 0 && !hasHost) refuse(`${r.name} reads the class, and ${file} has no host: this pass does not give a facet one`); - if (r.r8 && r.r8.length > 0 && !hasHost) refuse(`${r.name}: R8 types its facet members by the host interface's class, and ${file} has no host`); - if (starting) { - for (const local of [...r.imports.keys(), ...r.moduleRefs.keys()]) { - if (local === facetNameOf(file) || local === hostNameOf(file) || local === CLASS_TYPE_ALIAS) refuse(`${file}: ${r.name} reads ${local}, a name this script generates in that module`); - } - } - if (r.facetNames && !starting) { - const held = facetMembersOf(tm, file, mod)?.members.map((x) => x.name) ?? []; - for (const n of r.facetNames) if (held.includes(n)) refuse(`${r.name}: ${file} already holds a facet member ${n}`); - } - if (r.host.size > 0 && r.node.getParameters().some((p) => p.getName() === hostVarOf(file))) { - refuse(`${r.name}: a parameter is named ${hostVarOf(file)}, which its stub reads as the facet's host`); - } - if (r.classStatics.size > 0 && !routed) refuse(`${r.name} reads statics of ${CLASS_NAME}, none of them non-public, and ${file} does not take the statics route: this pass reroutes a module only for a body that reads a non-public static (R10)`); - if (routed && (r.imports.has(CLASS_TYPE_ALIAS) || r.moduleRefs.has(CLASS_TYPE_ALIAS))) refuse(`${file}: ${r.name} reads ${CLASS_TYPE_ALIAS}, a name the statics route generates in that module`); - if (routed) { - const blockers = [...r.routeBlockers, ...(r.classOther ? ['static-route-conflict'] : [])]; - if (blockers.length > 0) refuse(`${r.name} stays on the class, as the first pass would keep it in a routed module: ${blockers.join('; ')}`); - } - for (const [n, use] of r.moduleRefs) { - // A started module imports the class as the first pass does (`importLines`). - if (n === CLASS_NAME && (starting || routed || (!use.value && typeImportsClass))) continue; - // R4 (#30020): a name `engine.ts` already exports is imported from it - // (lever (a) of ruling 6591753301); no export list widens. - if (n !== CLASS_NAME && ctx.scope.exported.has(n) && ctx.scope.bindings.get(n)?.kind === 'local') { - // A routed module's `./engine.js` line is the statics pair's: a name it - // already imports there, in a form that serves the read, needs no edit. - // A started module's line is written whole (`importLines`). - const held = routed && !starting ? engineRunOf(tm, file, mod, [])?.uses.get(n) : null; - if (routed && !starting && !(held && (held.value || !use.value))) refuse(`${r.name} reads ${n}, a name ${HOST_BASENAME} exports, and ${file} takes the statics route: this pass does not import into a routed module's \`./engine.js\` line`); - continue; - } - refuse(`${r.name} reads ${n}, a top-level name of ${HOST_BASENAME}: this pass does not widen the generated export lists`); - } - for (const local of r.imports.keys()) { - const b = ctx.scope.bindings.get(local); - if (!b || b.kind !== 'import') refuse(`import binding ${local} not found`); - } - } - } - return { ctx, records, modules, reroutes, starts, anchors }; -} - -/** Apply a `planMembers` plan. Returns `{ host, modules, pruned }` (`modules`: the receiving modules' new texts). Pure. */ -function generateMembers(tm, text, moduleTexts, planned) { - const { ctx, modules } = planned; - const starts = planned.starts ?? new Set(); - const edits = []; - const newStatics = new Map(); - const startedHosts = []; - for (const [file, movers] of modules) { - if (starts.has(file)) { - // R11: the started facet's import, under its comment, in section order. - const at = facetImportAt(text, file, planned.anchors ?? SECTION_ANCHORS); - if (at === null) refuse(`${HOST_BASENAME}: no facet import or hosts import to place ${file}'s import by, as the first pass writes them`); - edits.push({ start: at, end: at, text: facetImportText(file, movers[0].section, movers.some((r) => r.host.size > 0)) }); - } - for (const r of movers) { - const body = r.node.getBody(); - const lineStart = lineStartOf(text, body.getEnd() - 1); - const closeIndent = text.slice(lineStart, body.getEnd() - 1); - if (!/^ *$/.test(closeIndent)) refuse(`${r.name}: the body's closing brace does not open its own line`); - edits.push({ start: body.getStart(), end: body.getEnd(), text: r.r8 - ? ctorStubBody({ node: r.node, usesHost: r.host.size > 0, r8: r.r8, paramsRead: r.paramsRead }, file, closeIndent) - : stubBody({ node: r.node, name: r.name, usesHost: r.host.size > 0, docMoved: Boolean(r.doc) }, file, closeIndent) }); - if (r.r8) continue; - const asyncKw = r.node.getModifiers().find((x) => x.getKind() === tm.SyntaxKind.AsyncKeyword); - if (asyncKw) edits.push({ start: asyncKw.getStart(), end: r.node.getNameNode().getStart(), text: '' }); - if (r.doc) edits.push({ start: r.node.getStart(true), end: r.node.getStart(), text: '' }); - for (const [k, kind] of r.classStatics) newStatics.set(k, kind); - } - const members = new Map(); - const written = new Set(); - for (const r of movers) for (const [k, kind] of r.host) members.set(k, kind); - for (const r of movers) for (const k of r.writes) written.add(k); - if (members.size === 0) continue; - if (starts.has(file)) { - // R11: its install call, among the others in host-name order. - if (installRegionOf(text, file)) refuse(`${file}: ${HOST_BASENAME} already installs a host factory for it`); - const at = installCallAt(text, file); - if (at === null) refuse(`${HOST_BASENAME}: its install block is not as the first pass wrote it`); - edits.push({ start: at, end: at, text: installCallText(file, members, written) }); - startedHosts.push(file); - continue; - } - const inst = installRegionOf(text, file); - if (!inst) refuse(`${file}: its host factory in ${HOST_BASENAME}'s install block is not as the first pass wrote it`); - const merged = new Map(inst.members); - for (const [k, kind] of members) { - if (merged.has(k) && merged.get(k) !== kind) refuse(`${file}: host member ${k} is a ${merged.get(k)} there and a ${kind} here`); - merged.set(k, kind); - } - const mergedWritten = new Set([...inst.written, ...written]); - const lines = hostInstallLines(merged, mergedWritten).join('\n'); - if (lines !== text.slice(inst.start, inst.end)) edits.push({ start: inst.start, end: inst.end, text: lines }); - } - if (startedHosts.length > 0) { - // R11: the hosts import gains each started facet's host. - const imp = hostsImportOf(tm, text); - if (!imp) refuse(`${HOST_BASENAME}: its hosts import is not as the first pass wrote it`); - const names = [...imp.names, ...startedHosts.map(hostVarOf)].sort(); - edits.push({ start: imp.start, end: imp.end, text: namedStatement('import', names, ` from '${imp.spec}';`) }); - } - if (newStatics.size > 0) { - const region = staticsRegionOf(text); - if (!region) refuse(`${HOST_BASENAME}: its statics route is not as the first pass wrote it`); - const merged = new Map(region.kinds); - for (const [k, kind] of newStatics) merged.set(k, kind); - if (merged.size > region.kinds.size) { - const t = staticsTexts(merged); - edits.push({ start: region.ahead.start, end: region.ahead.end, text: t.ahead }); - edits.push({ start: region.block.start, end: region.block.end, text: t.block }); - } - } - const out = applyOrderedEdits(text, edits); - const pruned = pruneHostImports(tm, out, usedImportNames(tm, out)); - - const moduleOut = new Map(); - if (startedHosts.length > 0) { - // R11: `HOSTS_MODULE` is the first pass's text for one module more. - const files = hostsModuleFilesOf(moduleTexts.get(HOSTS_MODULE) ?? ''); - if (!files) refuse(`${HOSTS_MODULE} is not on disk as the first pass wrote it`); - moduleOut.set(HOSTS_MODULE, hostsModuleText([...files, ...startedHosts])); - } - for (const [file, movers] of modules) { - if (starts.has(file)) { - // R11: the module the first pass writes for these movers. - moduleOut.set(file, startedModuleText(ctx.scope, file, movers[0].section, movers, movers.some((r) => r.readsNonPublicStatic))); - continue; - } - // R10: a module this plan reroutes is put on the statics route first, and grows from there. - const mod = planned.reroutes?.has(file) ? rerouteModule(tm, file, moduleTexts.get(file)) : moduleTexts.get(file); - const title = movers[0].section; - const modEdits = []; - // The members, in class order among the ones the module holds. - const facet = facetMembersOf(tm, file, mod); - if (!facet) refuse(`${file}: its facet class is not as the first pass wrote it`); - const ctorAt = ctx.cls.getConstructors()[0]?.getStart(); - const classPos = (name) => { - const ms = ctx.cls.getMethods().filter((m) => m.getName() === name); - // A moved constructor's facet members (R8's, then `construct`) stand where the constructor does. - if (ms.length === 0 && ctorAt !== undefined && isCtorFacetName(name)) return ctorAt; - if (ms.length !== 1) refuse(`${file}: facet member ${name} has ${ms.length} methods of that name on the class`); - return ms[0].getStart(); - }; - const held = facet.members.map((m) => ({ ...m, at: classPos(m.name) })); - const hostName = hostNameOf(file); - const classType = interfaceRegionOf(mod, hostName)?.classType ?? CLASS_NAME; - const groups = new Map(); - for (const r of movers) { - const next = held.find((m) => m.at > r.node.getStart()); - const key = next ? next.name : ''; - const texts = r.r8 ? ctorFacetTexts(r, hostName, classType) : [facetMethodText(r, hostName)]; - groups.set(key, [...(groups.get(key) ?? []), ...texts]); - } - for (const [key, texts] of groups) { - if (key) { - const at = lineStartOf(mod, held.find((m) => m.name === key).node.getStart(true)); - modEdits.push({ start: at, end: at, text: texts.map((t) => `${t}\n\n`).join('') }); - } else { - const at = held.at(-1).node.getEnd(); - modEdits.push({ start: at, end: at, text: texts.map((t) => `\n\n${t}`).join('') }); - } - } - // The header's list gains the names, each before the first listed name declared below it on the class. - const header = headerNamesOf(mod, title); - if (!header) refuse(`${file}: its header is not as the first pass wrote it`); - const listed = [...header.names]; - for (const r of movers) { - const k = listed.findIndex((n) => classPos(n) > r.node.getStart()); - listed.splice(k < 0 ? listed.length : k, 0, ...(r.facetNames ?? [r.name])); - } - modEdits.push({ start: header.region.start, end: header.region.end, text: moduleHeaderLines(title, listed, header.tail).join('\n') }); - // The host interface gains what the moved bodies read. - const reads = new Map(); - const writes = new Set(); - for (const r of movers) for (const [k, kind] of r.host) reads.set(k, kind); - for (const r of movers) for (const k of r.writes) writes.add(k); - if (reads.size > 0) { - const iface = interfaceRegionOf(mod, hostName); - if (!iface) refuse(`${file}: its host interface is not as the first pass wrote it`); - const lines = new Map([...iface.members].map(([k, v]) => [k, v.line])); - for (const [k, kind] of reads) { - const readonly = kind === 'facade' || (kind === 'getter' && !writes.has(k)); - const prev = iface.members.get(k); - if (prev && prev.readonly && !readonly) refuse(`${file}: host member ${k} is read-only there, and a moved body ${kind === 'getter' ? 'assigns' : 'calls'} it`); - if (prev && Boolean(prev.facade) !== (kind === 'facade')) refuse(`${file}: host member ${k} is not the identity port there`); - if (!prev) lines.set(k, kind === 'facade' ? facadeIfaceLine(iface.classType) : ` ${readonly ? 'readonly ' : ''}${k}: ${iface.classType}['${k}'];`); - } - modEdits.push({ start: iface.start, end: iface.end, text: [...lines.keys()].sort().map((k) => lines.get(k)).join('\n') }); - } - // The import lines gain the bindings the moved bodies read, by specifier. - modEdits.push(...moduleImportEdits(tm, file, mod, ctx.scope, movers, CLASS_NAME)); - moduleOut.set(file, withCyclePara(applyOrderedEdits(mod, modEdits), file)); - } - return { host: pruned.text, modules: moduleOut, pruned: pruned.removed }; -} - -/** - * The import edits a move makes to a receiving module: each binding the moved - * bodies read joins its specifier's run, rendered as the first pass writes it, - * and a specifier the module does not import yet goes in at `engine.ts`'s - * import order. R4: a name `engine.ts` exports joins the `./engine.js` lines - * (`skipClass`, the class the host interface already types, excepted). - */ -function moduleImportEdits(tm, file, mod, scope, movers, skipClass) { - const modEdits = []; - const decls = importDeclsOf(tm, file, mod); - const adds = new Map(); // specifier -> Map(local -> binding) - for (const r of movers) { - for (const [local, use] of r.imports) { - const b = scope.bindings.get(local); - const slot = adds.get(b.specifier) ?? new Map(); - const prev = slot.get(local); - slot.set(local, { form: b.form, imported: b.imported, value: Boolean(prev && prev.value) || (use.value && !b.typeOnly) }); - adds.set(b.specifier, slot); - } - // R4: the names `engine.ts` already exports, onto the module's `./engine.js` lines. - for (const [n, use] of r.moduleRefs) { - if (n === skipClass) continue; - // Already on the module's `./engine.js` line in a form that serves the read: no edit. - const held = decls.find((d) => d.specifier === './engine.js' && d.bindings.get(n)?.form === 'named' && d.bindings.get(n).imported === n)?.bindings.get(n); - if (held && (held.value || !use.value)) continue; - const slot = adds.get('./engine.js') ?? new Map(); - const prev = slot.get(n); - slot.set(n, { form: 'named', imported: n, value: Boolean(prev && prev.value) || use.value }); - adds.set('./engine.js', slot); - } - } - const tail = decls.findIndex((d) => d.specifier === leafSpecifier() || d.specifier === './engine.js'); - const inserts = new Map(); // offset -> [{ order, text }] - for (const [specifier, slot] of adds) { - const run = decls.map((d, i) => ({ d, i })).filter(({ d }) => d.specifier === specifier); - if (run.length > 0) { - if (run.at(-1).i - run[0].i !== run.length - 1) refuse(`${file}: the imports of ${specifier} are not one run`); - const have = new Map(); - for (const { d } of run) for (const [local, e] of d.bindings) have.set(local, e); - const styles = runStyles(mod, run.map(({ d }) => d), specifier); - const before = styles && specifierLines(specifier, have, styles); - const span = mod.slice(run[0].d.start, run.at(-1).d.end); - if (!before || before.join('\n') !== span) refuse(`${file}: the imports of ${specifier} are not as the first pass wrote them`); - const merged = new Map(have); - for (const [local, e] of slot) { - const prev = merged.get(local); - if (prev && (prev.form !== e.form || prev.imported !== e.imported)) refuse(`${file}: ${local} is bound differently there`); - merged.set(local, { ...e, value: Boolean(prev && prev.value) || e.value }); - } - modEdits.push({ start: run[0].d.start, end: run.at(-1).d.end, text: specifierLines(specifier, merged, styles).join('\n') }); - continue; - } - for (const [local] of slot) if (decls.some((d) => d.bindings.has(local))) refuse(`${file}: ${local} is bound there from another specifier`); - const lines = specifierLines(specifier, slot); - if (!lines) refuse(`${file}: ${specifier} would be imported in a form this pass does not write`); - const rank = scope.importOrder.get(specifier); - let at; - let text = `${lines.join('\n')}\n`; - if (specifier === leafSpecifier()) { - const engineDecl = decls.find((d) => d.specifier === './engine.js'); - at = engineDecl ? lineStartOf(mod, engineDecl.start) : null; - } else { - const next = decls.slice(0, tail < 0 ? decls.length : tail).find((d) => { - const o = scope.importOrder.get(d.specifier); - return o !== undefined && o > rank; - }); - at = next ? lineStartOf(mod, next.start) : tail >= 0 ? lineStartOf(mod, decls[tail].start) : null; - } - if (at === null) { at = decls.at(-1).end; text = `\n${lines.join('\n')}`; } - inserts.set(at, [...(inserts.get(at) ?? []), { order: specifier === leafSpecifier() ? Infinity : rank, text }]); - } - for (const [at, list] of inserts) { - list.sort((a, b) => a.order - b.order); - modEdits.push({ start: at, end: at, text: list.map((x) => x.text).join('') }); - } - return modEdits; -} - -/** One import binding's identity in a module: its specifier and its local name. */ -const importKey = (specifier, local) => `${specifier}\u0000${local}`; - -/** - * The import edits this pass made to a receiving module, read off its base - * and head import blocks (#30572): the bindings the head has and the base had - * not (`added`), and the ones the base bound type-only and the head binds as a - * value (`widened`). The prune alone cannot undo either when the module's - * remaining text still reads the name: a docblock link the base carried - * unresolved resolves once a moved body's import binds it, and a binding a - * staying member reads as a type reads as one still. So the proof inverts the - * edits it reads here instead, and each is checked on the way (`fail`): it is - * one the moved members' own text reads (a moved body, or its docblock), and - * the head never narrowed or dropped a base binding, which no undo could - * restore. The comparison stays byte for byte: the edits name bindings only, - * and the lines they leave are rendered as the first pass writes them. - */ -function importEditsOf(tm, file, baseText, headText, movedText, fail) { - const bindingsOf = (text) => { - const out = new Map(); - for (const d of importDeclsOf(tm, file, text)) for (const [local, e] of d.bindings) out.set(importKey(d.specifier, local), { local, ...e }); - return out; - }; - const base = bindingsOf(baseText); - const head = bindingsOf(headText); - const added = new Set(); - const widened = new Set(); - const readByMoved = (local) => new RegExp(`\\b${local.replace(/\$/g, '\\$')}\\b`).test(movedText); - for (const [k, h] of head) { - const b = base.get(k); - if (b && b.value === h.value) continue; - if (b && b.value && !h.value) { fail(`${file}: binds ${h.local} type-only, where its base bound it as a value`); continue; } - if (!readByMoved(h.local)) { fail(`${file}: ${b ? 'binds as a value' : 'imports'} ${h.local}, which ${b ? 'its base bound type-only' : 'its base did not'} and no moved member reads`); continue; } - (b ? widened : added).add(k); - } - for (const [k, b] of base) if (!head.has(k)) fail(`${file}: dropped the import binding ${b.local}, which no undo can restore`); - return { added, widened }; -} - -/** - * Undo this pass's moves out of one receiving module, from its head text and - * its base's import block: drop the named members and their names from the - * header's list, keep the host members the rest still `Pick`, invert the - * import edits the moves made (`importEditsOf`) and prune the imports nothing - * reads. Checks the head on the way (`fail`): the header lists them, the - * interface is the union of the `Pick`s, and no import binding is unread. - * Returns the text, or null when the head is not a module this pass can read. - */ -function undoMembersModule(tm, file, headText, names, title, fail, baseText) { - if (importsEngineValues(headText) !== headText.includes(VALUES_CYCLE_PARA)) fail(`${file}: its header's import paragraph does not say what its \`./engine.js\` lines import`); - // R10's undo first: a module its base held off the statics route comes off - // it, its moved members still in it, when one of them reads a static. - let text = headText; - if (!routesStatics(headText) && readsClassStatic(tm, file, headText, names)) fail(`${file}: a member this pass moved reads a static, and the module is off the statics route (R10)`); - if (routesStatics(headText) && !routesStatics(baseText)) { - if (!readsClassStatic(tm, file, headText, names)) fail(`${file}: on the statics route at head and off it at base, and no member this pass moved reads a static (R10)`); - text = unrouteModule(tm, file, headText, fail); - if (text === null) return null; - } - const facet = facetMembersOf(tm, file, text); - const header = headerNamesOf(text, title); - if (!facet || !header) { fail(`${file}: not a facet module as the first pass writes one`); return null; } - for (const n of names) if (!header.names.includes(n)) fail(`${file}: its header does not list ${n}`); - const union = (ms) => new Set(ms.flatMap((m) => picksOf(m))); - const iface = interfaceRegionOf(text, hostNameOf(file)); - const headUnion = union(facet.members); - if ((iface ? [...iface.members.keys()].join() : '') !== [...headUnion].sort().join()) fail(`${file}: its host interface is not exactly the members its bodies' Picks name`); - const unread = pruneImports(tm, text, usedImportNames(tm, text)).removed; - if (unread.length > 0) fail(`${file}: imports what nothing in it reads: ${unread.join(', ')}`); - const keep = facet.members.filter((m) => !names.includes(m.name)); - if (keep.length === 0) { fail(`${file}: every member is one this pass moved (it never starts a facet)`); return null; } - const movedText = facet.members.filter((m) => names.includes(m.name)).map((m) => m.text).join('\n'); - const inverse = importEditsOf(tm, file, baseText, text, movedText, fail); - const edits = [ - { start: facet.start, end: facet.end, text: keep.map((m) => m.text).join('\n\n') }, - { start: header.region.start, end: header.region.end, text: moduleHeaderLines(title, header.names.filter((n) => !names.includes(n)), header.tail).join('\n') }, - ]; - if (iface) { - const kept = union(keep); - edits.push({ start: iface.start, end: iface.end, text: [...iface.members].filter(([k]) => kept.has(k)).map(([, v]) => v.line).join('\n') }); - } - const undone = applyOrderedEdits(text, edits); - if (text !== headText && readsClassStatic(tm, file, undone)) fail(`${file}: R10 took it off the statics route, and a member it keeps reads a static`); - return withCyclePara(pruneModuleImports(tm, file, undone, inverse), file); -} - -/** The statics `ObjectQL.x` each routed module's text reads. */ -function routedStaticReads(texts) { - const reads = new Set(); - const routedImport = new RegExp(`^import \\{[^}]*\\b${STATICS_NAME} as ${CLASS_NAME}\\b`, 'm'); - for (const t of texts) { - if (!t || !routedImport.test(t)) continue; - for (const m of t.matchAll(new RegExp(`\\b${CLASS_NAME}\\.([A-Za-z_$][\\w$]*)`, 'g'))) reads.add(m[1]); - } - return reads; -} - -/** R8's marker line in a moved constructor's facet body, parsed: the field and the facet member. */ -const R8_MARKER = new RegExp(`// ${MARK.replace(/[[\]]/g, '\\$&')} R8: \`this\\.([\\w$]+)\` is assigned on the class \\(\`([\\w$]+)\`\\)\\.`, 'g'); - -/** - * `verifyMembers` for a moved constructor (#30020 R8): its base reading - * (R8's statements, then the rest as a method is read) holds no stay reason; - * the stub, each R8 facet member and `construct` are what `generateMembers` - * writes from that base. Sets `mv.fm` (`construct`), `mv.r8Fms` and - * `mv.facetNames` for the undo. - */ -function verifyCtorMove(tm, base, headText, headModules, mv, fail) { - const { hm, bm, file } = mv; - if (mv.docMoved) fail('constructor: its stub says its docblock moved, and a constructor keeps its docblock'); - const da = definiteAssignmentsOf(tm, base, bm); - const read = readMethod(tm, base, bm, { skip: da.r8.map((a) => [a.start, a.end]) }); - const reasons = [...read.reasons, ...da.reasons]; - if (reasons.length > 0) fail(`constructor: a stay rule holds it at base (${reasons.join('; ')})`); - if ((read.host.size > 0) !== mv.usesHost) fail(`constructor: its stub ${mv.usesHost ? 'hands' : 'hands no'} host, and its base body reads ${read.host.size > 0 ? 'the class' : 'no class member'}`); - const text = headModules.get(file); - const facet = text && text.includes(MARK) ? facetMembersOf(tm, file, text) : null; - const names = [...da.r8.map((a) => a.fn), CTOR_FACET_MEMBER]; - const fms = names.map((n) => facet?.members.find((m) => m.name === n)); - if (fms.some((fm) => !fm)) { fail(`constructor: ${file} at head does not hold every facet member ${names.join(', ')}`); return; } - mv.facetNames = names; - mv.fm = fms.at(-1).node; - mv.r8Fms = new Map(fms.slice(0, -1).map((fm) => [fm.name, fm.node])); - mv.moduleText = text; - const body = hm.getBody(); - const closeIndent = headText.slice(lineStartOf(headText, body.getEnd() - 1), body.getEnd() - 1); - if (body.getText() !== ctorStubBody({ node: hm, usesHost: mv.usesHost, r8: da.r8, paramsRead: read.paramsRead }, file, closeIndent)) { - fail('constructor: the stub is not the R8 stub its base reading gives'); - } - const hostName = hostNameOf(file); - const iface = interfaceRegionOf(text, hostName); - if (da.r8.length > 0 && !iface) { fail(`constructor: ${file} has no host interface to type R8's members by`); return; } - const r = { node: bm, host: read.host, identity: read.identity, r8: da.r8, paramsRead: read.paramsRead }; - const want = ctorFacetTexts(r, hostName, iface?.classType ?? CLASS_NAME); - fms.forEach((fm, i) => { - if (fm.text !== want[i]) fail(`constructor: the facet member ${fm.name} is not its base constructor's text (R8 ${i < da.r8.length ? 'right side' : 'body'})`); - }); -} - -/** - * The undo of a moved constructor's body, read off the head alone: R1's - * inverse on `construct`, then each R8 marker back into `this.F = EXPR;`, - * EXPR the one `return` of the facet member the marker names. Null (and a - * failure) when a marker names no R8 member, or a member no marker names. - */ -function ctorUndoText(tm, mv, fail) { - const { Node } = tm; - let text = identityUndoText(tm, mv.fm); - const seen = new Set(); - let bad = false; - text = text.replace(R8_MARKER, (whole, field, fn) => { - const fm = mv.r8Fms.get(fn); - const st = fm?.getBody()?.getStatements() ?? []; - if (!fm || seen.has(fn) || st.length !== 1 || !Node.isReturnStatement(st[0]) || !st[0].getExpression()) { - fail(`constructor: the R8 marker for \`this.${field}\` names no single-return facet member ${fn}`); - bad = true; - return whole; - } - seen.add(fn); - return `this.${field} = ${st[0].getExpression().getText()};`; - }); - for (const fn of mv.r8Fms.keys()) if (!seen.has(fn)) { fail(`constructor: no R8 marker names the facet member ${fn}`); bad = true; } - return bad ? null : text; -} - -/** - * Prove this pass's moves against their base, from the texts alone (it - * shares no state with `generateMembers`). `baseModules` / `headModules`: the - * first pass's generated modules (leaf and hosts module included) at each - * side, by file. Returns `{ failures, moved, pruned, linesBefore, linesAfter }`. - */ -function verifyMembers(tm, baseText, headText, baseModules, headModules, { - anchors = SECTION_ANCHORS, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES, classNeedles = CLASS_PATH_READER_NEEDLES, -} = {}) { - const failures = []; - const fail = (msg) => failures.push(msg); - const moved = []; - const base = membersContext(tm, baseText, { pins, needles, classNeedles }); - const headCls = parse(tm, HOST_PATH, headText).getClass(CLASS_NAME); - const done = (pruned = []) => ({ failures, moved: moved.map((mv) => mv.name), pruned, linesBefore: lineCount(baseText), linesAfter: lineCount(headText) }); - if (!headCls) { fail(`no class ${CLASS_NAME} at head`); return done(); } - const key = (m) => `${m.isStatic() ? 'static ' : ''}${m.getName()}`; - const baseMethods = new Map(base.cls.getMethods().map((m) => [key(m), m])); - const headMethods = new Map(headCls.getMethods().map((m) => [key(m), m])); - if ([...baseMethods.keys()].join() !== [...headMethods.keys()].join()) fail(`${CLASS_NAME} does not declare the same methods in the same order at base and head`); - for (const [k, hm] of headMethods) { - const bm = baseMethods.get(k); - if (!bm) continue; - if (isGeneratedStub(bm) && !isGeneratedStub(hm)) fail(`${k}: a stub at base is a body at head`); - if (!isGeneratedStub(hm) || isGeneratedStub(bm)) continue; - const m = STUB_MARK_LINE.exec(hm.getBody().getText()); - moved.push({ name: hm.getName(), hm, bm, file: m[1], docMoved: Boolean(m[2]), usesHost: Boolean(m[3]) }); - } - // The constructor (#30020 R8): a stub at head over a body at base. - const baseCtors = base.cls.getConstructors(); - const headCtors = headCls.getConstructors(); - if (baseCtors.length !== headCtors.length) fail(`${CLASS_NAME} declares ${baseCtors.length} constructor(s) at base and ${headCtors.length} at head`); - else if (baseCtors.length === 1) { - const [bm] = baseCtors; - const [hm] = headCtors; - if (isGeneratedStub(bm) && !isGeneratedStub(hm)) fail('constructor: a stub at base is a body at head'); - if (isGeneratedStub(hm) && !isGeneratedStub(bm)) { - const m = STUB_MARK_LINE.exec(hm.getBody().getText()); - moved.push({ name: 'constructor', ctor: true, hm, bm, file: m[1], docMoved: Boolean(m[2]), usesHost: Boolean(m[3]) }); - } - } - if (moved.length === 0) fail('nothing moved: the head carries no stub its base did not'); - const sectionOf = readSections(base.cls, anchors); - for (const mv of moved) { - const { name, hm, bm, file } = mv; - const section = sectionOf(bm); - if (!section || section[2] !== file) { fail(`${name}: its stub names ${file}, and its section's module is ${section?.[2] ?? 'none'}`); continue; } - mv.title = section[1]; - if (mv.ctor) { verifyCtorMove(tm, base, headText, headModules, mv, fail); continue; } - const read = readMethod(tm, base, bm); - if (read.reasons.length > 0) fail(`${name}: a stay rule holds it at base (${read.reasons.join('; ')})`); - if ((read.host.size > 0) !== mv.usesHost) fail(`${name}: its stub ${mv.usesHost ? 'hands' : 'hands no'} host, and its base body reads ${read.host.size > 0 ? 'the class' : 'no class member'}`); - const text = headModules.get(file); - const facet = text && text.includes(MARK) ? facetMembersOf(tm, file, text) : null; - const fm = facet?.members.find((m) => m.name === name); - if (!fm) { fail(`${name}: ${file} at head holds no facet member ${name}`); continue; } - mv.fm = fm.node; - mv.moduleText = text; - const body = hm.getBody(); - const closeIndent = headText.slice(lineStartOf(headText, body.getEnd() - 1), body.getEnd() - 1); - if (body.getText() !== stubBody({ node: hm, name, usesHost: mv.usesHost, docMoved: mv.docMoved }, file, closeIndent)) fail(`${name}: the stub is not the first pass's stub`); - if (hm.isAsync()) fail(`${name}: the stub kept \`async\``); - const baseDoc = bm.getScope() === 'private' && bm.getStart(true) < bm.getStart() ? baseText.slice(bm.getStart(true), bm.getStart()) : null; - mv.record = { ...read, name, node: bm, doc: baseDoc }; - if (mv.docMoved !== (baseDoc !== null)) fail(`${name}: its stub says its docblock ${mv.docMoved ? 'moved' : 'stayed'}, and the base method is ${baseDoc === null ? 'not a private one with a docblock' : 'a private one with a docblock'}`); - if (fm.text !== facetMethodText({ name, node: bm, host: read.host, doc: baseDoc, identity: read.identity }, hostNameOf(file))) { - fail(`${name}: the facet member is not its base method's text (docblock, parameters, return type, body)`); - } - } - - // The modules: the receiving ones undo to their base; every other one is its base. - const touched = new Map(); - for (const mv of moved) if (mv.fm) touched.set(mv.file, [...(touched.get(mv.file) ?? []), mv]); - // R11: a receiving module absent at base was started; its undo is its deletion. - const started = new Set([...touched.keys()].filter((f) => !baseModules.has(f))); - const startedHosts = [...started].filter((f) => interfaceRegionOf(headModules.get(f), hostNameOf(f)) !== null); - const undone = new Map(); - for (const file of new Set([...baseModules.keys(), ...headModules.keys()])) { - const b = baseModules.get(file) ?? null; - const h = headModules.get(file) ?? null; - if (file === HOSTS_MODULE && startedHosts.length > 0) { - // R11: the hosts module is its base with the started facets' hosts, and nothing else. - const files = h === null ? null : hostsModuleFilesOf(h); - if (!files) { fail(`${HOSTS_MODULE}: not as the first pass writes it at head`); continue; } - for (const f of started) { - if (files.includes(f) !== startedHosts.includes(f)) fail(`${HOSTS_MODULE}: ${files.includes(f) ? 'holds' : 'lacks'} a host for ${f}, which ${startedHosts.includes(f) ? 'has' : 'has no'} host interface`); - } - const u = hostsModuleText(files.filter((f) => !started.has(f))); - if (u !== b) fail(`undoing the started facets out of ${HOSTS_MODULE} does not rebuild its base (first difference at line ${firstDiffLine(u, b ?? '')})`); - continue; - } - if (!touched.has(file)) { - if (b !== h) fail(`${file}: changed, and no member this pass moved is in it`); - continue; - } - if (b === null) { - // R11: exactly the text the first pass writes for the moved members, read off the base. - const mvs = touched.get(file); - if (mvs.some((mv) => mv.ctor)) { fail(`${file}: absent at base, and a constructor never starts a facet`); continue; } - const records = [...mvs].sort((x, y) => x.bm.getStart() - y.bm.getStart()).map((mv) => mv.record); - const routed = records.some((r) => r.readsNonPublicStatic); - if (routesStatics(h) !== routed) fail(`${file}: ${routesStatics(h) ? 'on' : 'off'} the statics route, and ${routed ? 'a' : 'no'} moved member reads a non-public static`); - let want = null; - try { - want = startedModuleText(base.scope, file, mvs[0].title, records, routed); - } catch (e) { - if (!(e instanceof CodemodRefusal)) throw e; - fail(`${file}: its base members do not render as a started facet (${e.message})`); - } - if (want !== null && want !== h) fail(`${file}: started, and not the module the first pass writes for its members (first difference at line ${firstDiffLine(h, want)})`); - undone.set(file, ''); - continue; - } - const mvs = touched.get(file); - const u = undoMembersModule(tm, file, h, mvs.flatMap((mv) => mv.facetNames ?? [mv.name]), mvs[0].title, fail, b); - if (u === null) continue; - undone.set(file, u); - if (u !== b) fail(`undoing the moves out of ${file} does not rebuild its base (first difference at line ${firstDiffLine(u, b)})`); - } - - // engine.ts: each body, docblock and `async` back; the route and the host factories lose what only moved bodies read. - const edits = []; - for (const mv of moved) { - if (!mv.fm) continue; - const body = mv.hm.getBody(); - if (mv.ctor) { - const undo = ctorUndoText(tm, mv, fail); - if (undo !== null) edits.push({ start: body.getStart(), end: body.getEnd(), text: undo }); - continue; - } - edits.push({ start: body.getStart(), end: body.getEnd(), text: identityUndoText(tm, mv.fm) }); - if (mv.fm.isAsync()) edits.push({ start: mv.hm.getNameNode().getStart(), end: mv.hm.getNameNode().getStart(), text: 'async ' }); - if (mv.docMoved) edits.push({ start: mv.hm.getStart(), end: mv.hm.getStart(), text: mv.moduleText.slice(mv.fm.getStart(true), mv.fm.getStart()) }); - } - const sections = [...headModules.keys()].filter((f) => f !== LEAF_MODULE && f !== HOSTS_MODULE); - const statics = staticsRegionOf(headText); - if (statics) { - const readAtHead = routedStaticReads(sections.map((f) => headModules.get(f))); - for (const k of statics.kinds.keys()) if (!readAtHead.has(k)) fail(`${STATICS_NAME} carries ${k}, which no routed facet body reads`); - const readUndone = routedStaticReads(sections.map((f) => undone.get(f) ?? headModules.get(f))); - const kept = new Map([...statics.kinds].filter(([k]) => readUndone.has(k))); - if (kept.size !== statics.kinds.size) { - const t = staticsTexts(kept); - edits.push({ start: statics.ahead.start, end: statics.ahead.end, text: t.ahead }); - edits.push({ start: statics.block.start, end: statics.block.end, text: t.block }); - } - } else if (headText.includes(`export interface ${STATICS_HOST_NAME} {`)) { - fail(`${HOST_BASENAME}: its statics route is not as the first pass writes it`); - } - for (const file of started) { - // R11: the facet's import and its comment come out of engine.ts. - const mvs = touched.get(file); - const t = facetImportText(file, mvs[0].title, mvs.some((mv) => mv.usesHost)); - const at = headText.indexOf(`\n${t}`); - if (at < 0 || headText.indexOf(`\n${t}`, at + 1) >= 0) fail(`${file}: ${HOST_BASENAME} does not import its facet once, as the first pass writes the import`); - else edits.push({ start: at + 1, end: at + 1 + t.length, text: '' }); - } - if (startedHosts.length > 0) { - const imp = hostsImportOf(tm, headText); - const gone = new Set(startedHosts.map(hostVarOf)); - if (!imp || startedHosts.some((f) => !imp.names.includes(hostVarOf(f)))) fail(`${HOST_BASENAME}: its hosts import does not import each started facet's host as the first pass writes it`); - else edits.push({ start: imp.start, end: imp.end, text: namedStatement('import', imp.names.filter((n) => !gone.has(n)).sort(), ` from '${imp.spec}';`) }); - } - for (const file of touched.keys()) { - const head = headModules.get(file); - const iface = interfaceRegionOf(head, hostNameOf(file)); - if (!iface) continue; - const inst = installRegionOf(headText, file); - if (!inst) { fail(`${file}: its host factory in ${HOST_BASENAME} is not as the first pass writes it`); continue; } - for (const [k, v] of iface.members) { - const kind = inst.members.get(k); - const readonly = kind === 'facade' || (kind === 'getter' && !inst.written.has(k)); - if (!kind || v.readonly !== readonly || Boolean(v.facade) !== (kind === 'facade')) fail(`${file}: host member ${k} is not the same member in its interface and its factory`); - } - if (inst.members.size !== iface.members.size) fail(`${file}: its host factory forwards members its interface does not declare`); - if (started.has(file)) { - // R11: its whole install call comes out. - const call = installCallRegionOf(headText, file); - if (!call) fail(`${file}: its install call in ${HOST_BASENAME} is not as the first pass writes one`); - else edits.push({ start: call.start, end: call.end, text: '' }); - continue; - } - const u = undone.get(file); - const keptIface = u ? interfaceRegionOf(u, hostNameOf(file)) : null; - if (!keptIface) continue; - const kept = new Map([...inst.members].filter(([k]) => keptIface.members.has(k))); - if (kept.size !== inst.members.size) { - edits.push({ start: inst.start, end: inst.end, text: hostInstallLines(kept, new Set([...inst.written].filter((k) => kept.has(k)))).join('\n') }); - } - } - let undoneHost = null; - try { - undoneHost = applyOrderedEdits(headText, edits); - } catch (e) { - if (!(e instanceof CodemodRefusal)) throw e; - fail(`${HOST_BASENAME}: the undo's edits overlap`); - } - const prune = pruneHostImports(tm, baseText, usedImportNames(tm, headText)); - if (undoneHost !== null && undoneHost !== prune.text) { - fail(`undoing the moves does not rebuild the base ${HOST_BASENAME} (first difference at line ${firstDiffLine(undoneHost, prune.text)})`); - } - const movedText = moved.map((mv) => mv.bm.getText()).join('\n'); - for (const n of prune.removed) { - if (!new RegExp(`\\b${n.replace(/\$/g, '\\$')}\\b`).test(movedText)) fail(`${HOST_BASENAME} lost the import binding ${n}, which no moved body reads`); - } - return done(prune.removed); -} - -function planReportMembers(planned) { - const out = [`# codemod-split-engine --members (${MEMBERS_CARD}): named methods onto the split class`, '']; - for (const [file, movers] of planned.modules) { - out.push(`- ${file}: ${movers.map((r) => `${r.name} (${r.bodyLines ?? r.node.getBody().getEndLineNumber() - r.node.getBody().getStartLineNumber() + 1} body lines${r.doc ? ', its docblock with it' : ''})`).join(', ')}`); - } - return out.join('\n'); -} - -function printVerifyMembers(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - console.log(`undo proof: ${v.moved.length} moved method(s) (${v.moved.join(', ') || 'none'}); engine.ts ${v.linesBefore} -> ${v.linesAfter} lines; ` + - `undoing the moves ${v.failures.length > 0 ? 'does NOT' : 'does'} rebuild the base engine.ts and its modules byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved bodies read are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -function generatedModulesAt(ref) { - const out = new Map(); - for (const file of [LEAF_MODULE, HOSTS_MODULE, ...SECTION_ANCHORS.map((row) => row[2])]) { - if (!file) continue; - try { - out.set(file, execFileSync('git', ['show', `${ref}:${SRC_REL}/${file}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'ignore'] })); - } catch { /* absent at the ref */ } - } - return out; -} - -async function mainMembers(tm, argv) { - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--members --verify needs --base '); - const v = verifyMembers(tm, gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), generatedModulesAt(ref), generatedModulesOnDisk()); - printVerifyMembers(v); - return v.failures.length === 0 ? 0 : 1; - } - const j = argv.indexOf('--members'); - const value = argv[j + 1]; - const names = value && !value.startsWith('--') ? value.split(',').map((s) => s.trim()).filter(Boolean) : []; - const input = readFileSync(HOST_PATH, 'utf8'); - const moduleTexts = generatedModulesOnDisk(); - const planned = planMembers(tm, input, moduleTexts, names); - console.log(planReportMembers(planned)); - const out = generateMembers(tm, input, moduleTexts, planned); - const headModules = new Map([...moduleTexts, ...out.modules]); - console.log(`output tree sha256: ${treeHash(new Map([[HOST_BASENAME, out.host], ...headModules]))} (input sha256 ${sha256(input)})`); - const v = verifyMembers(tm, input, out.host, moduleTexts, headModules); - printVerifyMembers(v); - if (v.failures.length > 0) { - console.error('✗ the generated moves fail the undo proof: nothing written. Report the fork; never hand-edit the moves.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - writeFileSync(HOST_PATH, out.host); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} module(s) under ${SRC_REL}`); - return 0; -} - -// ── The fifth pass: a hand stub's computing host slot (#30020 H2) ─────────── -// -// A hand-series stub (#25467) builds its host as an object literal of -// one-line forwarders and makes one `.call(host, …)`; the facade gate reads -// that as a delegation. A slot that COMPUTES instead (a block-bodied arrow: a -// `try`, a branch) makes the whole stub a body, so the method stays an -// exception row. `--hand-slots ` moves every such slot of the named -// stubs into the stub's own hand module, the one its marker names: the arrow, -// exactly as it stood, one indentation level out (the slot's own line indent, -// put back by the undo), becomes an exported `const` of the slot's name typed -// AS the host interface's member (`ReferenceNameVisibleHost['x']`), so its -// parameters keep the contextual types the literal gave them; the slot names -// it (`x,`), and `engine.ts` imports it beside the function it already imports -// from that module. What the arrow may read is closed: its own parameters and -// locals, and module-scope names `engine.ts` imports, each imported in the -// hand module from the same specifier by a statement of its own. A `this`, a -// local of the stub, a name `engine.ts` declares, a template or string that -// spans lines, or a line not indented as far as the slot refuses (exit 2). -// -// The proof (`--hand-slots --verify --base REF` re-runs it) undoes every slot -// the head carries moved (a shorthand slot whose hand module exports a const -// of that name under this pass's docblock): the const back into its slot, -// re-indented; its docblock, its import statements and the binding in -// `engine.ts`'s import out. The result must be the base `engine.ts` (the -// base's import bindings only moved slots read pruned from it) and every hand -// module byte for byte. - -const HAND_SLOTS_CARD = '#30020'; - -/** The docblock over a moved slot's const in its hand module. */ -const handSlotDoc = (slot, stub, fn) => ['/**', ...wrapComment(( - `[${HAND_SLOTS_CARD} codemod] The \`${slot}\` slot of the host \`${CLASS_NAME}#${stub}\` hands {@link ${fn}}: ` + - `moved here whole by \`--hand-slots\` of \`${SCRIPT}\`, and the slot names it.`).split(' ')), ' */'].join('\n'); - -/** - * A hand stub of `engine.ts`, parsed: its host literal, the function it - * calls and the module that declares it; null when the method is not a hand - * stub of that shape (const forwarders, ONE host literal, `return fn.call(host, …)`). - */ -function handSlotStubOf(tm, cls, text, name) { - const { Node } = tm; - const found = cls.getMethods().filter((m) => m.getName() === name); - if (found.length !== 1) return { why: `${CLASS_NAME} declares ${found.length === 0 ? 'no method' : 'more than one method'} ${name}` }; - const m = found[0]; - const body = m.getBody(); - if (!body) return { why: `${name} has no body` }; - const line1Start = text.indexOf('\n', body.getStart()) + 1; - const hit = HAND_STUB_MARK.exec(text.slice(line1Start, text.indexOf('\n', line1Start))); - if (!hit) return { why: `${name} is not a hand-series stub (its body does not open with the hand series' marker)` }; - const stmts = body.getStatements(); - const last = stmts.at(-1); - const call = last && Node.isReturnStatement(last) ? last.getExpression() : null; - const callee = call && Node.isCallExpression(call) ? call.getExpression() : null; - if (!callee || !Node.isPropertyAccessExpression(callee) || callee.getName() !== 'call' || !Node.isIdentifier(callee.getExpression())) { - return { why: `${name}: the stub does not end in \`return fn.call(host, …)\`` }; - } - const fn = callee.getExpression().getText(); - const hosts = []; - for (const st of stmts.slice(0, -1)) { - if (!Node.isVariableStatement(st)) return { why: `${name}: a statement before the call is not a const` }; - for (const d of st.getDeclarations()) if (Node.isObjectLiteralExpression(d.getInitializer())) hosts.push(d.getInitializer()); - } - if (hosts.length !== 1) return { why: `${name}: the stub builds ${hosts.length} host literals, not one` }; - return { m, module: hit[1], fn, literal: hosts[0] }; -} - -/** The `this` parameter's type name of an exported function in a hand module, or null. */ -function handHostTypeOf(tm, file, text, fn) { - const f = parse(tm, join(SRC_DIR, file), text).getFunction(fn); - const p = f && f.isExported() ? f.getParameters()[0] : null; - const t = p && p.getName() === 'this' ? p.getTypeNode() : null; - return t && /^[A-Za-z_$][\w$]*$/.test(t.getText()) ? t.getText() : null; -} - -/** An arrow's text one indentation level out (`indent`), or null when a later line is not that far in. */ -function deindentBy(text, indent) { - const lines = text.split('\n'); - const out = [lines[0]]; - for (const line of lines.slice(1)) { - if (line === '') out.push(line); - else if (line.startsWith(indent) && line.trim() !== '') out.push(line.slice(indent.length)); - else return null; - } - return out.join('\n'); -} -const reindentBy = (text, indent) => text.split('\n').map((line, i) => (i === 0 || line === '' ? line : `${indent}${line}`)).join('\n'); - -/** engine.ts's one-line, sorted value import of a hand module, parsed: `{ start, end, names }`, or null. */ -function handImportOf(text, file) { - const specifier = `./${file.replace(/\.ts$/, '.js')}`; - const re = new RegExp(`^import \\{ ([A-Za-z_$][\\w$]*(?:, [A-Za-z_$][\\w$]*)*) \\} from '${specifier.replace(/[.]/g, '\\.')}';$`, 'gm'); - const hits = [...text.matchAll(re)]; - if (hits.length !== 1) return null; - const names = hits[0][1].split(', '); - if (names.join() !== [...names].sort().join()) return null; - return { start: hits[0].index, end: hits[0].index + hits[0][0].length, names, specifier }; -} -const handImportText = (names, specifier) => `import { ${[...names].sort().join(', ')} } from '${specifier}';`; - -/** - * Decide the moves `names` asks for. Refuses (exit 2) on a name that is not a - * hand stub, a stub with no computing slot, and every shape the section above - * closes out. Pure. - */ -function planHandSlots(tm, text, moduleTexts, names) { - const { Node, SyntaxKind } = tm; - if (!names || names.length === 0) refuse('--hand-slots needs a comma-separated list of hand-series stub names'); - if (new Set(names).size !== names.length) refuse(`--hand-slots names a stub twice: ${names.join(', ')}`); - const sf = parse(tm, HOST_PATH, text); - const cls = sf.getClass(CLASS_NAME); - if (!cls) refuse(`no class ${CLASS_NAME} in ${HOST_BASENAME}`); - const scope = moduleScope(tm, sf); - const checker = sf.getProject().getTypeChecker().compilerObject; - const ts = tm.ts; - const records = []; - for (const name of names) { - const stub = handSlotStubOf(tm, cls, text, name); - if (stub.why) refuse(stub.why); - const mod = moduleTexts.get(stub.module); - if (mod == null) refuse(`${stub.module}: the hand module ${name}'s marker names is not on disk`); - const hostType = handHostTypeOf(tm, stub.module, mod, stub.fn); - if (!hostType) refuse(`${stub.module}: exports no function ${stub.fn} whose \`this\` names its host interface`); - if (!handImportOf(text, stub.module)) refuse(`${HOST_BASENAME}: its import of ${stub.module} is not one sorted line of values`); - const slots = []; - for (const p of stub.literal.getProperties()) { - if (!Node.isPropertyAssignment(p)) continue; - const init = p.getInitializer(); - if (!Node.isArrowFunction(init) || !Node.isBlock(init.getBody())) continue; - const slot = p.getName(); - if (!Node.isIdentifier(p.getNameNode())) refuse(`${name}: a computing slot has a computed or quoted name`); - const why = (msg) => refuse(`${name}: its \`${slot}\` slot ${msg}`); - const lineStart = lineStartOf(text, p.getStart()); - const indent = text.slice(lineStart, p.getStart()); - if (!/^ +$/.test(indent)) why('does not open its own line'); - if (init.getDescendants().some((n) => (Node.isTemplateExpression(n) || Node.isNoSubstitutionTemplateLiteral(n) || Node.isStringLiteral(n)) && - n.getStartLineNumber() !== n.getEndLineNumber())) why('holds a template or string spanning lines, which a re-indent would edit'); - const arrowText = text.slice(init.getStart(), init.getEnd()); - const moved = deindentBy(arrowText, indent); - if (moved === null) why('has a line not indented as far as the slot, or a blank line holding spaces'); - if (scope.bindings.has(slot)) why(`is named ${slot}, which ${HOST_BASENAME} already binds`); - if (moduleScope(tm, parse(tm, join(SRC_DIR, stub.module), mod)).bindings.has(slot)) why(`is named ${slot}, which ${stub.module} already binds at module scope`); - const imports = new Map(); // local -> { specifier, form, imported, value } - for (const node of init.getDescendants()) { - if (node.getKind() === SyntaxKind.ThisKeyword) why('reads `this`'); - if (node.getKind() !== SyntaxKind.Identifier || isPropertyNameIdentifier(ts, node.compilerNode)) continue; - const parent = node.getParent(); - const symbol = Node.isShorthandPropertyAssignment(parent) && parent.getNameNode() === node - ? checker.getShorthandAssignmentValueSymbol(parent.compilerNode) : checker.getSymbolAtLocation(node.compilerNode); - for (const decl of symbol?.declarations ?? []) { - if (decl.getSourceFile() !== sf.compilerNode) continue; - if (decl.pos >= init.compilerNode.pos && decl.end <= init.compilerNode.end) continue; - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const b = scope.bindings.get(node.getText()); - const value = !inTypePosition(tm, node, init); - const prev = imports.get(node.getText()); - imports.set(node.getText(), { specifier: b.specifier, form: b.form, imported: b.imported, value: Boolean(prev && prev.value) || (value && !b.typeOnly) }); - continue; - } - why(`reads ${node.getText()}, which ${isModuleScopeDecl(ts, decl) ? `${HOST_BASENAME} declares` : 'the stub declares'}`); - } - } - slots.push({ slot, prop: p, init, indent, moved, imports }); - } - if (slots.length === 0) refuse(`${name}: its host literal holds no computing slot (a block-bodied arrow)`); - records.push({ name, ...stub, hostType, slots }); - } - return { records }; -} - -/** The import statements a hand module gains for a slot's reads: one per specifier it does not import yet. */ -function handSlotImportLines(file, mod, imports, decls) { - const bySpecifier = new Map(); - for (const [local, b] of imports) { - const have = decls.find((d) => d.bindings.has(local)); - if (have) { - const e = have.bindings.get(local); - if (have.specifier !== b.specifier || e.form !== b.form || e.imported !== b.imported || (b.value && !e.value)) { - refuse(`${file}: binds ${local} otherwise than ${HOST_BASENAME} does`); - } - continue; - } - if (decls.some((d) => d.specifier === b.specifier)) refuse(`${file}: already imports from ${b.specifier}, and this pass adds whole statements only`); - if (!bySpecifier.has(b.specifier)) bySpecifier.set(b.specifier, new Map()); - bySpecifier.get(b.specifier).set(local, b); - } - const lines = []; - for (const [specifier, bindings] of [...bySpecifier].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { - const out = specifierLines(specifier, bindings); - if (!out) refuse(`${file}: ${specifier} would be imported in a form this pass does not write`); - lines.push(...out); - } - return lines; -} - -/** Apply a `planHandSlots` plan. Returns `{ host, modules, pruned }`. Pure. */ -function generateHandSlots(tm, text, moduleTexts, planned) { - const edits = []; - const byModule = new Map(); - for (const r of planned.records) byModule.set(r.module, [...(byModule.get(r.module) ?? []), r]); - const modules = new Map(); - for (const [file, rs] of [...byModule].sort(([a], [b]) => (a < b ? -1 : 1))) { - const mod = moduleTexts.get(file); - const decls = importDeclsOf(tm, file, mod); - if (decls.length === 0) refuse(`${file}: imports nothing, so there is no import block to add to`); - const imports = new Map(); - for (const r of rs) for (const s of r.slots) for (const [k, v] of s.imports) imports.set(k, v); - const lines = handSlotImportLines(file, mod, imports, decls); - const at = decls.at(-1).end; - let next = mod.slice(0, at) + lines.map((l) => `\n${l}`).join('') + mod.slice(at); - if (!next.endsWith('\n')) refuse(`${file}: does not end in a line break`); - for (const r of rs) { - for (const s of r.slots) { - next += `\n${handSlotDoc(s.slot, r.name, r.fn)}\nexport const ${s.slot}: ${r.hostType}['${s.slot}'] = ${s.moved};\n`; - } - } - modules.set(file, next); - const imp = handImportOf(text, file); - edits.push({ start: imp.start, end: imp.end, text: handImportText([...imp.names, ...rs.flatMap((r) => r.slots.map((s) => s.slot))], imp.specifier) }); - } - for (const r of planned.records) for (const s of r.slots) edits.push({ start: s.prop.getStart(), end: s.prop.getEnd(), text: s.slot }); - const out = applyOrderedEdits(text, edits); - const pruned = pruneHostImports(tm, out, usedImportNames(tm, out)); - return { host: pruned.text, modules, pruned: pruned.removed }; -} - -/** - * Undo every moved slot a tree carries, from its texts alone. Returns the - * undone `engine.ts` and hand modules, the slots it undid (with the arrow - * text, for the prune check), and every way the tree breaks the pass's form. - */ -function undoHandSlots(tm, text, moduleTexts) { - const { Node } = tm; - const failures = []; - const moved = []; - const sf = parse(tm, HOST_PATH, text); - const cls = sf.getClass(CLASS_NAME); - if (!cls) return { host: text, modules: moduleTexts, moved, failures: [`no class ${CLASS_NAME} in ${HOST_BASENAME}`] }; - const hostEdits = []; - const perModule = new Map(); // file -> { removals: [{start,end}], slots: [] } - for (const s of handStubs(tm, text)) { - const stub = handSlotStubOf(tm, cls, text, s.name); - if (stub.why) continue; - const mod = moduleTexts.get(stub.module); - if (mod == null) continue; - const msf = parse(tm, join(SRC_DIR, stub.module), mod); - for (const p of stub.literal.getProperties()) { - if (!Node.isShorthandPropertyAssignment(p)) continue; - const slot = p.getName(); - const doc = handSlotDoc(slot, s.name, stub.fn); - const st = msf.getVariableStatement(slot); - if (!st || !mod.includes(doc)) continue; - const decl = st.getDeclarations()[0]; - const init = decl?.getInitializer(); - const lead = mod.slice(lineStartOf(mod, st.getStart(true)) - 1, st.getStart()); - if (!st.isExported() || st.getDeclarations().length !== 1 || !init || !Node.isArrowFunction(init) || lead !== `\n${doc}\n` || mod[st.getEnd()] !== '\n') { - failures.push(`${slot}: ${stub.module} holds it, under this pass's docblock, not as this pass writes it`); - continue; - } - const hostType = handHostTypeOf(tm, stub.module, mod, stub.fn); - if (st.getText() !== `export const ${slot}: ${hostType}['${slot}'] = ${init.getText()};`) failures.push(`${slot}: its const is not typed as ${hostType ?? 'the host'}'s member`); - const indent = text.slice(lineStartOf(text, p.getStart()), p.getStart()); - hostEdits.push({ start: p.getStart(), end: p.getEnd(), text: `${slot}: ${reindentBy(init.getText(), indent)}` }); - const entry = perModule.get(stub.module) ?? { removals: [], slots: [] }; - entry.removals.push({ start: lineStartOf(mod, st.getStart(true)) - 1, end: st.getEnd() + 1 }); - entry.slots.push(slot); - perModule.set(stub.module, entry); - moved.push({ name: s.name, slot, module: stub.module, text: init.getText() }); - } - } - const modules = new Map(moduleTexts); - for (const [file, entry] of perModule) { - const mod = moduleTexts.get(file); - const usedAtHead = usedImportNames(tm, mod); - const unread = importDeclsOf(tm, file, mod).flatMap((d) => [...d.bindings.keys()]).filter((k) => !usedAtHead.has(k)); - if (unread.length > 0) failures.push(`${file}: imports what nothing in it reads: ${unread.join(', ')}`); - let undone = applyEdits(mod, entry.removals.map((r) => ({ ...r, text: '' }))); - const used = usedImportNames(tm, undone); - const drops = []; - for (const d of importDeclsOf(tm, file, undone)) { - const unused = [...d.bindings.keys()].filter((k) => !used.has(k)); - if (unused.length === 0) continue; - if (unused.length !== d.bindings.size) { failures.push(`${file}: an import statement binds names only moved slots read beside names the rest reads`); continue; } - if (undone[d.start - 1] !== '\n') { failures.push(`${file}: an import only moved slots read does not open its own line`); continue; } - drops.push({ start: d.start - 1, end: d.end, text: '' }); - } - undone = applyEdits(undone, drops); - modules.set(file, undone); - const imp = handImportOf(text, file); - if (!imp || entry.slots.some((n) => !imp.names.includes(n))) { failures.push(`${HOST_BASENAME}: does not import every moved slot of ${file} in its one import line of it`); continue; } - hostEdits.push({ start: imp.start, end: imp.end, text: handImportText(imp.names.filter((n) => !entry.slots.includes(n)), imp.specifier) }); - } - let host = text; - try { - host = applyOrderedEdits(text, hostEdits); - } catch (e) { - if (!(e instanceof CodemodRefusal)) throw e; - failures.push(`${HOST_BASENAME}: the undo's edits overlap`); - } - return { host, modules, moved, failures }; -} - -/** - * The proof: undoing every moved slot in the head lands on the base, - * `engine.ts` (its import bindings only moved slots read pruned) and each - * hand module byte for byte. A base this pass has already run on is undone - * the same way first, so a later run proves only its own slots. - */ -function verifyHandSlots(tm, baseText, headText, baseModules, headModules) { - const head = undoHandSlots(tm, headText, headModules); - const base = undoHandSlots(tm, baseText, baseModules); - const failures = [...head.failures, ...base.failures.map((f) => `base: ${f}`)]; - const { text: prunedBase, removed: pruned } = pruneHostImports(tm, base.host, usedImportNames(tm, headText)); - const movedText = head.moved.map((m) => m.text).join('\n'); - for (const n of pruned) if (!new RegExp(`\\b${n.replace(/\$/g, '\\$')}\\b`).test(movedText)) failures.push(`${n}: the head no longer imports it, and no moved slot reads it`); - if (head.host !== prunedBase) failures.push(`undoing the moves does NOT rebuild the base ${HOST_BASENAME} (first difference at line ${firstDiffLine(head.host, prunedBase)})`); - for (const file of [...new Set([...baseModules.keys(), ...headModules.keys()])].sort()) { - const b = base.modules.get(file); const h = head.modules.get(file); - if (b == null || h == null) { failures.push(`${file}: only in the ${b == null ? 'head' : 'base'}`); continue; } - if (h !== b) failures.push(`undoing the moves does NOT rebuild the base ${file} (first difference at line ${firstDiffLine(h, b)})`); - } - const baseMoved = new Set(base.moved.map((m) => `${m.name}#${m.slot}`)); - const moved = head.moved.filter((m) => !baseMoved.has(`${m.name}#${m.slot}`)); - if (moved.length === 0) failures.push('nothing moved: the head carries no moved slot its base did not'); - return { failures, moved, pruned, linesBefore: lineCount(baseText), linesAfter: lineCount(headText) }; -} - -function planReportHandSlots(planned) { - const out = [`# codemod-split-engine --hand-slots (${HAND_SLOTS_CARD}): the hand stubs' computing host slots`, '']; - for (const r of planned.records) out.push(`- ${r.name} -> ${r.module}: ${r.slots.map((s) => `${s.slot} (${s.moved.split('\n').length} lines)`).join(', ')}`); - return out.join('\n'); -} - -function printVerifyHandSlots(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - console.log(`hand slots: ${v.moved.length} moved (${v.moved.map((m) => `${m.name}#${m.slot}`).join(', ') || 'none'}); ${HOST_BASENAME} ${v.linesBefore} -> ${v.linesAfter} lines; ` + - `undoing the moves ${v.failures.length > 0 ? 'does NOT' : 'does'} rebuild the base ${HOST_BASENAME} and its hand modules byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved slots read are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -/** `--hand-slots`: plan, write or re-prove the fifth pass. */ -async function mainHandSlots(tm, argv) { - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--hand-slots --verify needs --base '); - const baseText = gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`); - const baseModules = handModuleTexts(tm, baseText, (f) => { try { return gitShow(ref, `${SRC_REL}/${f}`); } catch { return null; } }); - const headModules = handModuleTexts(tm, baseText, readSibling); - const v = verifyHandSlots(tm, baseText, readFileSync(HOST_PATH, 'utf8'), baseModules, headModules); - printVerifyHandSlots(v); - return v.failures.length === 0 ? 0 : 1; - } - const j = argv.indexOf('--hand-slots'); - const value = argv[j + 1]; - const names = value && !value.startsWith('--') ? value.split(',').map((s) => s.trim()).filter(Boolean) : []; - const input = readFileSync(HOST_PATH, 'utf8'); - const moduleTexts = handModuleTexts(tm, input, readSibling); - const planned = planHandSlots(tm, input, moduleTexts, names); - console.log(planReportHandSlots(planned)); - const out = generateHandSlots(tm, input, moduleTexts, planned); - const headModules = new Map([...moduleTexts, ...out.modules]); - console.log(`output tree sha256: ${treeHash(new Map([[HOST_BASENAME, out.host], ...headModules]))} (input sha256 ${sha256(input)})`); - const v = verifyHandSlots(tm, input, out.host, moduleTexts, headModules); - printVerifyHandSlots(v); - if (v.failures.length > 0) { - console.error('✗ the generated moves fail the undo proof: nothing written. Report the fork; never hand-edit the moves.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - writeFileSync(HOST_PATH, out.host); - for (const [file, t] of out.modules) writeFileSync(join(SRC_DIR, file), t); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} hand module(s) under ${SRC_REL}`); - return 0; -} - -// ── Entry ──────────────────────────────────────────────────────────────────── - -const USAGE = [ - 'usage: node scripts/codemod-split-engine.mjs [--write] plan (or apply) the split of an UNSPLIT engine.ts', - ' node scripts/codemod-split-engine.mjs --verify --base REF re-prove a split on disk against engine.ts at REF', - ' node scripts/codemod-split-engine.mjs --scoped [--write] plan (or apply) the second pass: ObjectRepository and ScopedContext', - ' node scripts/codemod-split-engine.mjs --scoped --verify --base REF re-prove the second pass on disk against engine.ts at REF', - ' node scripts/codemod-split-engine.mjs --scoped --members C#A,C#B [--write] plan (or apply) the second pass\'s members mode: move the named scoped methods onto the split class', - ' node scripts/codemod-split-engine.mjs --scoped --members --verify --base REF re-prove the members mode on disk against engine.ts and its scoped modules at REF', - ' node scripts/codemod-split-engine.mjs --hand-docs [--modules A.ts,B.ts] [--write] plan (or apply) the third pass: the hand series\' private docblocks', - ' node scripts/codemod-split-engine.mjs --hand-docs --verify --base REF re-prove the third pass on disk against engine.ts and its hand modules at REF', - ' node scripts/codemod-split-engine.mjs --members A,B [--write] plan (or apply) the fourth pass: move the named ObjectQL methods onto the split class', - ' node scripts/codemod-split-engine.mjs --members --verify --base REF re-prove the fourth pass on disk against engine.ts and its modules at REF', - ' node scripts/codemod-split-engine.mjs --hand-slots A,B [--write] plan (or apply) the fifth pass: move the named hand stubs\' computing host slots into their hand modules', - ' node scripts/codemod-split-engine.mjs --hand-slots --verify --base REF re-prove the fifth pass on disk against engine.ts and its hand modules at REF', - ' node scripts/codemod-split-engine.mjs --self-test', - ' node scripts/codemod-split-engine.mjs --help', -].join('\n'); - -async function main(argv) { - // Answered before any guard: `--help` reads no tree, so the "already split" - // refusal below must never be what a reader asking for usage gets. - if (argv.includes('--help') || argv.includes('-h')) { - console.log(USAGE); - return 0; - } - if (argv.includes('--self-test')) { - await selfTest(); - if (process.exitCode === 1) return 1; - if (!selfTestReachedVerdict) { - console.error('\n✗ codemod-split-engine self-test: selfTest() returned without reaching its verdict,\n' + - 'so no success line was printed. Exiting 0 here would report a self-test that never\n' + - 'finished as a self-test that passed.'); - return 1; - } - return 0; - } - const tm = await loadTsMorph(); - if (argv.includes('--scoped')) return mainScoped(tm, argv); - if (argv.includes('--hand-docs')) return mainHandDocs(tm, argv); - if (argv.includes('--members')) return mainMembers(tm, argv); - if (argv.includes('--hand-slots')) return mainHandSlots(tm, argv); - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--verify needs --base '); - const v = verify(tm, gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), generatedModulesOnDisk(), { readSibling }); - printVerify(v); - return v.failures.length === 0 ? 0 : 1; - } - const input = readFileSync(HOST_PATH, 'utf8'); - if (input.includes(MARK)) refuse(`${HOST_BASENAME} already carries ${MARK} stubs: run the script on an unsplit file (re-run on the latest main, never on its own output)`); - const planned = plan(tm, input); - console.log(planReport(planned)); - const out = generate(tm, input, planned); - const files = new Map([[HOST_BASENAME, out.host], ...out.modules]); - console.log(`output tree sha256: ${treeHash(files)} (input sha256 ${sha256(input)})`); - const v = verify(tm, input, out.host, out.modules, { readSibling }); - printVerify(v); - if (v.failures.length > 0) { - console.error('✗ the generated split fails byte-identity: nothing written. Report the fork; never hand-edit the split.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - for (const [file] of out.modules) { - const p = join(SRC_DIR, file); - if (existsSync(p) && !readFileSync(p, 'utf8').includes(MARK)) refuse(`${file} exists and was not written by this script`); - } - writeFileSync(HOST_PATH, out.host); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} module(s) under ${SRC_REL}`); - return 0; -} - - -/** - * The relative specifiers a module's VALUE imports and re-exports name: an - * `import type` / `export type` declaration, or a named list whose every - * member is `type`-marked, is erased by the compiler and is left out. - */ -function valueSpecifiers(src) { - const out = []; - for (const m of src.matchAll(/^[ \t]*(?:import|export)\s+(type\s+)?([^;'"]*?)\s*from\s*'(\.{1,2}\/[^']+)'/gm)) { - if (m[1]) continue; - const inner = /^\{([^}]*)\}$/.exec(m[2].trim()); - if (inner && inner[1].split(',').map((s) => s.trim()).filter(Boolean).every((s) => s.startsWith('type '))) continue; - out.push(m[3]); - } - for (const m of src.matchAll(/^[ \t]*import\s*'(\.{1,2}\/[^']+)'/gm)) out.push(m[1]); - return out; -} - -// ── Self-test ──────────────────────────────────────────────────────────────── -// -// The proofs above are this script's whole value, and a proof that cannot fail -// proves nothing, so the self-test feeds each one an input it must REFUSE. The -// roster pins battery NAMES with a floor each, the roster's own size is pinned, -// and the verdict sets a flag the dispatch reads (AGENTS.md, "Writing a -// `--self-test`"), so a battery that stops running, or a `return` above the -// verdict, cannot read as a pass. - -let selfTestReachedVerdict = false; - -const SELF_TEST_BATTERIES = Object.freeze({ - 'stay rules': 20, - 'facets, statics and docblocks': 17, - 'top-level moves': 11, - 'byte-identity proof': 10, - 'import prune': 4, - 'refusals': 6, - 'scoped classes (second pass)': 16, - 'hand-series docblocks (third pass)': 19, - 'named methods onto the split class (fourth pass)': 23, - 'identity port, computed keys and exported names (fourth pass, #30020)': 23, - 'hand-series host slots (fifth pass, #30020)': 17, - 'constructor and definite-assignment wiring (fourth pass, #30020 R8)': 17, - 'statics route for a written module (fourth pass, #30020 R10)': 21, - 'a facet the anchor names and the first pass never wrote (fourth pass, #30020 R11)': 18, - 'scoped members, instance identity port and symbol keys (second pass, #30020 S1)': 25, -}); -const SELF_TEST_BATTERY_FLOOR = 5; - -const FIXTURE_ANCHORS = Object.freeze([ - ['count', 'Lifecycle', 'engine-lifecycle.ts'], - ['keptSection', 'Kept', null], -]); -const FIXTURE_NEEDLES = Object.freeze({ 'PINNED_TEXT': 'a fixture reader', 'needleInMethod(': 'a fixture reader' }); -const FIXTURE_CLASS_NEEDLES = Object.freeze({ 'classReaderText(': 'a fixture reader that also reads the leaf' }); -const FIXTURE_PINS = Object.freeze({ pinnedMethod: 'a fixture reader' }); -const fixturePlan = (tm, text) => plan(tm, text, - { anchors: FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }); - -function fixtureSource(extraMethods = '') { - const pad = Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - return `import type { Knex } from 'knex'; -import { helperImported } from './other.js'; -import { onlyMovedReads } from './moved-only.js'; -import { seamHelper } from './engine-seam.js'; - -/** A value the leaf takes, read by a moved body. */ -const LOCAL_VALUE = 1; -type LocalType = { n: number }; -export interface ExportedShape { a: number } - -// A reader takes this one out of the file by path. -const PINNED = 'PINNED_TEXT'; -function dependsOnPinned(): string { - return PINNED; -} -function namesClass(d: ObjectQL): ObjectQL { - return d; -} -const VIA_SEAM = seamHelper(); -export const DERIVED = LOCAL_VALUE + 1; -function classReaderText(n: number): number { - return n; -} - -export class ObjectQL { - private count = 0; - private knex: any = null; - protected logger: { warn(m: string): void } = console; - private readonly fn = (x: string): string => x; - private static readonly SECRET = 1; - private static bump = 0; - - /** A private docblock: it moves with the body. */ - private async movable(object: string, trx?: Knex.Transaction): Promise { -${pad} - const a = helperImported(object) as ExportedShape | string; - this.logger.warn(String(a) + onlyMovedReads()); - return this.other(String(a)) + String(trx ? this.count : 0); - } - - /** A protected docblock: it stays on the facade. */ - protected other(x: string): string { - return x; - } - - protected writes(): void { -${pad} - this.count = 1; - } - - protected asValue(): string[] { -${pad} - return ['a'].map(this.other); - } - - protected readsLocal(): number { -${pad} - return LOCAL_VALUE + dependsOnPinned().length; - } - - protected namesLocalType(): LocalType | null { -${pad} - return null; - } - - public inferred() { -${pad} - return 1; - } - - protected scoped(object: string): string { -${pad} - return this.getBuilder(object); - } - - protected getBuilder(object: string): string { - return object; - } - - protected defaulted(x: string = 'a'): string { -${pad} - return x; - } - - protected callsField(): string { -${pad} - return this.fn('a'); - } - - protected readsStatic(): number { -${pad} - return ObjectQL.SECRET; - } - - protected bumpsStatic(): number { -${pad} - ObjectQL.bump += 1; - return ObjectQL.SECRET; - } - - protected namesClassType(): ObjectQL | null { -${pad} - return null; - } - - protected delete(): number { -${pad} - return 4; - } - - protected deletesField(): void { -${pad} - delete this.knex; - } - - protected destructured({ a }: { a: number }): number { -${pad} - return a; - } - - protected generic(x: T): T { -${pad} - return this.other(x) as T; - } - - static staticHelper(n: number): number { -${pad} - return n + ObjectQL.SECRET; - } - - static usesThis(): number { -${pad} - return this.SECRET; - } - - protected pinnedMethod(): number { -${pad} - return 3; - } - - protected carriesNeedle(): number { -${pad} - return needleInMethod(1); - } - - protected carriesClassNeedle(): number { -${pad} - return classReaderText(1); - } -${extraMethods} - protected keptSection(): number { -${pad} - return 2 + VIA_SEAM + namesClass(this).count; - } -} - -function needleInMethod(n: number): number { - return n; -} -`; -} - -/** - * The fourth pass's fixture: the first pass's, with two methods a pin held - * when it split the file (`FOURTH_FIXTURE_PINS`), one private that reads a - * new host member, a new private static and an import only it reads, one - * protected that names a type only it imports. - */ -const FOURTH_FIXTURE_PINS = Object.freeze({ ...FIXTURE_PINS, pinnedHost: 'a fixture reader', pinnedTyped: 'a fixture reader' }); -function fourthFixtureSource() { - const pad = Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - const extra = ` - /** A pinned private docblock: the fourth pass moves it with the body. */ - private async pinnedHost(object: string): Promise { -${pad} - return this.other(object) + String(this.count) + String(this.knex) + helperImported(object) + String(ObjectQL.SECRET) + String(ObjectQL.bump) + fourthOnly(); - } - - /** A pinned protected docblock: it stays on the class. */ - protected pinnedTyped(x: FourthShape): number { -${pad} - return x.n; - } -`; - return fixtureSource(extra).replace("import { seamHelper } from './engine-seam.js';\n", - "import { seamHelper } from './engine-seam.js';\nimport { fourthOnly } from './fourth-only.js';\nimport type { FourthShape } from './fourth-shape.js';\n"); -} - -const FIXTURE_SCOPED_CLASSES = Object.freeze([ - ['ObjectRepository', 'engine-object-repository.ts', 'Repository'], - ['ScopedContext', 'engine-scoped-context.ts', 'Context'], -]); - -/** An `engine.ts` whose `ObjectQL` the first pass already split, ahead of two unsplit scoped classes. */ -function scopedFixtureSource() { - return `import { helperImported } from './other.js'; -import { onlyScopedReads } from './scoped-only.js'; -import { count } from './engine-count-aggregate.js'; -import { LifecycleFacet } from './engine-lifecycle.js'; - -export class ObjectQL { - run(n: number): number { - // ${MARK} The body moved to \`engine-lifecycle.ts\`. - return LifecycleFacet.run(n); - } -} - -export class ObjectRepository { - constructor( - private objectName: string, - private engine: { find(o: string): Promise; count(o: string): Promise }, - ) {} - - /** A public docblock: it stays on the class. */ - async find(query: any = {}): Promise { - return this.engine.find(this.objectName + String(query)); - } - - async count(): Promise { - return this.engine.count(this.objectName); - } - - inferred() { - return 1; - } -} - -export class ScopedContext { - constructor(private ctx: { user?: string }, private engine: any) {} - - private flag = false; - - private derive(ctx: { user?: string }): ScopedContext { - const child = new ScopedContext(ctx, this.engine); - child.flag = this.flag; - return child; - } - - /** A private docblock: it moves with the body. */ - private readFlag(): boolean { - return this.flag && Boolean(helperImported()); - } - - object(name: string): ObjectRepository { - return new ObjectRepository(name, this.engine); - } - - sudo(): ScopedContext { - this.flag = this.readFlag() || Boolean(onlyScopedReads()); - return this.derive({ ...this.ctx }); - } - - handsSelf(): ScopedContext { - void count; - return this; - } - - get user() { return this.ctx.user; } -} -`; -} - -/** - * `scopedFixtureSource` with two more scoped methods the second pass keeps: a - * symbol-keyed one (`[SEED_KEY]`, `not-identifier-name`) that hands the - * instance on and reads an import nothing else reads, and one keyed by a - * lower-case binding R9 does not take. `facadeField` declares a `facade` - * member on `ScopedContext` (the identity port would shadow it). - */ -function scopedMembersFixtureSource({ facadeField = false } = {}) { - const base = scopedFixtureSource(); - return base - .replace("import { onlyScopedReads } from './scoped-only.js';\n", - "import { onlyScopedReads } from './scoped-only.js';\nimport { SEED_KEY, lowerKey } from './keys.js';\nimport { onlySeedReads } from './seed-only.js';\n") - .replace(' private flag = false;\n', ` private flag = false;\n${facadeField ? '\n private facade = 0;\n' : ''}`) - .replace(' get user() { return this.ctx.user; }\n', [ - ' /** A symbol-keyed method: its docblock stays on the class. */', - ' async [SEED_KEY](): Promise {', - ' if (!this.ctx.user) return this;', - ' return this.derive({ ...this.ctx, user: await onlySeedReads(this.ctx.user) });', - ' }', - '', - ' [lowerKey](): number {', - ' return 1;', - ' }', - '', - ' get user() { return this.ctx.user; }', - '', - ].join('\n')); -} - -function handFixtureEngine() { - return `import { privateDoc, publicDoc, noDoc, richer } from './engine-alpha.js'; -import { betaPrivate } from './engine-beta.js'; -// Type-only, for the link on betaPrivate's docblock. -import type { LinkedOnly } from './engine-beta.js'; - -export class ObjectQL { - private n = 1; - - /** - * A private docblock: it moves. - * - * Second paragraph. - */ - private privateDoc(n: number): number { - // [#25522 cut 1] The body moved to \`engine-alpha.ts\` (see \`AlphaHost\`). - return privateDoc.call({ n: this.n }, n); - } - - /** A public docblock: it stays. */ - publicDoc(): number { - // [#25522 cut 1] The body moved to \`engine-alpha.ts\` (see \`AlphaHost\`). PUBLIC - return publicDoc.call({ n: this.n }); - } - - private noDoc(): number { - // [#25522 cut 1] The body moved to \`engine-alpha.ts\`; it reads no member. - return noDoc(); - } - - /** Its function says more than the placeholder. */ - private richer(): number { - // [#25522 cut 1] The body moved to \`engine-alpha.ts\`; it reads no member. - return richer(); - } - - /** A beta docblock, {@link LinkedOnly}. */ - private betaPrivate(): number { - // The body lives in \`engine-beta.ts\`; it reads no member. - return betaPrivate(); - } - - /** Not a stub: no hand marker. */ - private notAStub(): number { - return this.n; - } -} -`; -} - -function handFixtureModules() { - const head = (what) => `// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#25522 cut 1] ${what}. - */ - -import type { ObjectQL } from './engine.js'; -`; - return new Map([ - ['engine-alpha.ts', `${head('The alpha bodies')} -export interface AlphaHost { readonly n: ObjectQL['n'] } - -${placeholderDoc('privateDoc')} -export function privateDoc(this: AlphaHost, n: number): number { - return this.n + n; -} - -${placeholderDoc('publicDoc')} -export function publicDoc(this: AlphaHost): number { - return this.n; -} - -${placeholderDoc('noDoc')} -export function noDoc(): number { - return 0; -} - -/** - * ${placeholderDoc('richer').slice(4, -3)} - * - * And a note of its own. - */ -export function richer(): number { - return 1; -} -`], - ['engine-beta.ts', `${head('The beta body')} -${placeholderDoc('betaPrivate')} -export function betaPrivate(): number { - return 2; -} -`], - ]); -} - -/** - * The identity-port fixture (#30020): the first pass's, with an `Identity` - * section the first pass writes (`seed` moves) and keeps the rest of on the - * class (each `bare-this` there), and one exported class after `ObjectQL`. - */ -const IDENTITY_FIXTURE_ANCHORS = Object.freeze([ - ['count', 'Lifecycle', 'engine-lifecycle.ts'], - ['seed', 'Identity', 'engine-identity.ts'], - ['keptSection', 'Kept', null], -]); -function identityFixtureSource({ facadeField = false, staticReader = false, startSection = false } = {}) { - const pad = Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - const extra = ` - protected seed(): number { -${pad} - return this.count; - } - - /** Hands the engine on (R1); its object-literal method keeps its own \`this\`. */ - private identity(n: number): Scoped { -${pad} - const nested = { k: 1, get(): number { return this.k; } }; - const self = (this as any)._flag ? this : null; - return new Scoped(n + this.count + nested.get(), self ?? this); - } - - private computed(slot: 'knex' | 'logger'): unknown { -${pad} - const v = this[slot]; - this[slot] = v as never; - return v; - } - - protected keyedString(key: string): unknown { -${pad} - return this[key]; - } - - protected keyedMethod(slot: 'other'): unknown { -${pad} - return this[slot]; - } - - protected handsToLocal(): number { -${pad} - return namesClass(this) === null ? 0 : 1; - } - - protected typedThis(): number { -${pad} - const t: typeof this = this; - return t === null ? 0 : 1; - } - - protected readsFacade(): unknown { -${pad} - return this.facade; - } -${staticReader ? ` - /** Reads a private static (R10) and hands the engine on (R1). */ - protected staticReader(n: number): number { -${pad} - const self = (this as any)._flag ? this : null; - return n + ObjectQL.SECRET + this.count + (self ? 1 : 0); - } -` : ''}${startSection ? ` - /** Hands the engine on (R1): the first pass keeps it, so its section has no module (R11). */ - protected handsOn(n: number): Scoped { -${pad} - return new Scoped(n + this.count, this); - } - - /** Reads a private static and the engine itself: the module R11 starts takes the statics route. */ - private handsOnStatic(n: number): number { -${pad} - return n + ObjectQL.SECRET + ((this as any)._flag ? 1 : 0); - } -` : ''}`; - const source = `${fixtureSource(extra)} -export class Scoped { - constructor(readonly n: number, readonly q: ObjectQL) {} -} -`; - return facadeField ? source.replace(' private count = 0;\n', ' private count = 0;\n private facade = 0;\n') : source; -} - -/** The identity fixture's anchors with a section whose every method the first pass keeps (`startSection`, R11). */ -const START_FIXTURE_ANCHORS = Object.freeze([ - ['count', 'Lifecycle', 'engine-lifecycle.ts'], - ['seed', 'Identity', 'engine-identity.ts'], - ['handsOn', 'Hand-on', 'engine-hand-on.ts'], - ['keptSection', 'Kept', null], -]); - -/** - * The constructor fixture (#30020 R8): the identity fixture with a field only - * a constructor may assign (`log`) and a constructor in the `Identity` - * section that assigns it first (R8), then hands the engine on (R1), writes - * and reads fields, and calls a method. `body` replaces the constructor's - * statements, for the refusals. - */ -const CTOR_FIXTURE_BODY = [ - ' // The log, from the options or made.', - " this.log = opts.log || makeLog('engine');", - ' // A comment the facet keeps.', - ' this.knex = opts.n ?? null;', - ' registerAll(this, this.count);', - ' if ((this as any)._flag) this.knex = 1;', - " this.log.info('made');", -]; -function ctorFixtureSource({ body = CTOR_FIXTURE_BODY, constructField = false } = {}) { - const ctor = ` - constructor(opts: { log?: { info(m: string): void }; n?: number } = {}, spare = 0) { -${body.join('\n')} - } -`; - const source = identityFixtureSource() - .replace("import { seamHelper } from './engine-seam.js';\n", - "import { seamHelper } from './engine-seam.js';\nimport { makeLog } from './log-maker.js';\nimport { registerAll } from './register-all.js';\n") - .replace(' private count = 0;\n', ` private count = 0;\n private log: { info(m: string): void };\n${constructField ? ' private construct = 0;\n' : ''}`) - .replace('\n /** Hands the engine on (R1); its object-literal method keeps its own `this`. */', `${ctor}\n /** Hands the engine on (R1); its object-literal method keeps its own \`this\`. */`); - return source; -} - -/** - * The fifth pass's fixture (#30020 H2): hand stubs whose host literals hold - * a computing slot (`gammaServe`), one that reads the stub's own `this` or a - * local, a slot of forwarders only, and one spanning a template. - */ -function slotFixtureEngine() { - return `import { gammaLocal, gammaOnly, gammaServe, gammaThis, gammaTpl } from './engine-gamma.js'; -import { planOf } from './engine-top-level.js'; -import type { Plan } from './plan-types.js'; - -export class ObjectQL { - private n = 1; - - private gammaServe(x: string): number { - // The body lives in \`engine-gamma.ts\` (see \`GammaHost\`). - const readN = () => this.n; - const host: ThisParameterType = { - get n() { return readN(); }, - judge: (name, plan) => { - try { - const p: Plan = planOf(name, plan); - return p.ok; - } catch { - // A plan that does not compile is judged no. - return false; - } - }, - other: (...a) => this.n + a.length, - }; - return gammaServe.call(host, x); - } - - private gammaThis(x: string): number { - // The body lives in \`engine-gamma.ts\` (see \`GammaHost\`). - const host: ThisParameterType = { - judge: (name) => { - return this.n > name.length; - }, - }; - return gammaThis.call(host, x); - } - - private gammaLocal(x: string): number { - // The body lives in \`engine-gamma.ts\` (see \`GammaHost\`). - const readN = () => this.n; - const host: ThisParameterType = { - judge: (name) => { - return readN() > name.length; - }, - }; - return gammaLocal.call(host, x); - } - - private gammaOnly(x: string): number { - // The body lives in \`engine-gamma.ts\` (see \`GammaHost\`). - const host: ThisParameterType = { - judge: (...a) => planOf(...a).ok, - }; - return gammaOnly.call(host, x); - } - - private gammaTpl(x: string): number { - // The body lives in \`engine-gamma.ts\` (see \`GammaHost\`). - const host: ThisParameterType = { - judge: (name) => { - return \`a -b\` === name; - }, - }; - return gammaTpl.call(host, x); - } -} -`; -} - -function slotFixtureModules() { - return new Map([['engine-gamma.ts', `// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The gamma bodies. - */ - -import type { ObjectQL } from './engine.js'; - -export interface GammaHost { - readonly n: ObjectQL['n']; - judge: (name: string, plan?: unknown) => boolean; - other: (...a: unknown[]) => number; -} - -export function gammaServe(this: GammaHost, x: string): number { - return this.judge(x) ? this.n : this.other(x); -} - -export function gammaThis(this: GammaHost, x: string): number { - return this.judge(x) ? 1 : 0; -} - -export function gammaLocal(this: GammaHost, x: string): number { - return this.judge(x) ? 1 : 0; -} - -export function gammaOnly(this: GammaHost, x: string): number { - return this.judge(x) ? 1 : 0; -} - -export function gammaTpl(this: GammaHost, x: string): number { - return this.judge(x) ? 1 : 0; -} -`]]); -} - -async function selfTest() { - const tm = await loadTsMorph(); - const batterySeen = new Map(); - let battery = null; - let failed = 0; - let cases = 0; - const open = (name) => { battery = name; }; - const check = (label, ok, detail = '') => { - batterySeen.set(battery, (batterySeen.get(battery) ?? 0) + 1); - cases += 1; - if (ok) console.log(` ✓ [${battery}] ${label}`); - else { failed += 1; console.error(` ✗ [${battery}] ${label}${detail ? ` — ${detail}` : ''}`); } - }; - const refused = (fn) => { try { fn(); return false; } catch (e) { return e instanceof CodemodRefusal; } }; - const refusalOf = (fn) => { try { fn(); return ''; } catch (e) { if (e instanceof CodemodRefusal) return e.message; throw e; } }; - - open('stay rules'); - { - const planned = fixturePlan(tm, fixtureSource()); - const why = (name) => (planned.records.find((r) => r.name === name)?.reasons ?? ['']).join('; '); - const stays = (name, code) => check(`${name} stays (${code})`, why(name).split('; ').some((r) => r.startsWith(code)), why(name)); - const moves = (name, because) => check(`${name} moves (${because})`, why(name) === '', why(name)); - moves('movable', 'the canonical body, private members read through the host'); - moves('readsLocal', 'lever (a)/(b): it imports the leaf value and the staying function'); - moves('namesLocalType', 'a non-exported type it names moves to the leaf'); - moves('scoped', 'a method it calls goes as a closure'); - moves('other', 'a body no longer than its stub moves too: the facade gate counts bodies, not lines'); - moves('writes', 'a field it assigns goes through a host setter'); - stays('deletesField', 'this-write'); - moves('delete', 'a reserved word is a valid facet member name'); - stays('asValue', 'method-as-value'); - stays('inferred', 'inferred-return-type'); - moves('defaulted', 'the stub keeps the default and forwards the value'); - stays('destructured', 'parameter-shape'); - moves('generic', 'the stub calls the body instantiated with its type parameters'); - moves('staticHelper', 'a static whose body reads no `this`'); - stays('usesThis', 'static-this'); - moves('readsStatic', 'a private static it reads goes through ObjectQLStatics'); - stays('bumpsStatic', 'static-write'); - stays('namesClassType', 'static-route-conflict'); - check('a pinned method and a method carrying a needle stay (path-reader)', - why('pinnedMethod').startsWith('path-reader') && why('carriesNeedle').startsWith('path-reader'), - `${why('pinnedMethod')} | ${why('carriesNeedle')}`); - check('a method in a section that maps to no module stays (section-kept)', why('keptSection').startsWith('section-kept'), why('keptSection')); - } - - open('top-level moves'); - { - const input = fixtureSource(); - const planned = fixturePlan(tm, input); - const top = (label) => planned.top.records.find((r) => r.label === label); - const why = (label) => (top(label)?.reasons ?? ['']).join('; '); - check('a value, a local type and an exported interface move', ['LOCAL_VALUE', 'LocalType', 'ExportedShape', 'DERIVED'] - .every((n) => why(n) === ''), ['LOCAL_VALUE', 'LocalType', 'ExportedShape', 'DERIVED'].map(why).join(' | ')); - check('a declaration carrying a reader\'s needle stays (path-reader)', why('PINNED').startsWith('path-reader'), why('PINNED')); - check('a declaration carrying a class-scoped needle moves: its reader reads the leaf', why('classReaderText') === '', why('classReaderText')); - check('a declaration naming a stayer stays (needs-stayer)', why('dependsOnPinned').startsWith('needs-stayer'), why('dependsOnPinned')); - check('a declaration naming the class stays (class-reference)', why('namesClass').startsWith('class-reference'), why('namesClass')); - check('a declaration using an engine-* import stays (seam-import)', why('VIA_SEAM').startsWith('seam-import'), why('VIA_SEAM')); - check('a declaration after the class is not in the region', !top('needleInMethod')); - const out = generate(tm, input, planned); - const leaf = out.modules.get(LEAF_MODULE) ?? ''; - check('the leaf header is line comments, never a docblock the bundled .d.ts would publish', - leaf.includes(MARK) && !leaf.slice(0, leaf.indexOf('\n\n', leaf.indexOf(MARK))).includes('/*')); - check('the leaf imports neither engine.ts nor an engine-* module', leaf.length > 0 && !/from '\.\/engine[.-]/.test(leaf), leaf.slice(0, 200)); - check('engine.ts re-exports the exported movers by name, the interface as a type', - /export \{ DERIVED, type ExportedShape \} from '\.\/engine-top-level\.js';/.test(out.host)); - check('lever (a): the staying function a moved body reads is exported for its module, and the module imports it', - /export \{ dependsOnPinned \};/.test(out.host) && - /import \{ ObjectQLStatics as ObjectQL, dependsOnPinned \} from '\.\/engine\.js';/.test(out.modules.get('engine-lifecycle.ts') ?? '')); - } - - open('byte-identity proof'); - { - const input = fixtureSource(); - const planned = fixturePlan(tm, input); - const out = generate(tm, input, planned); - const again = generate(tm, input, fixturePlan(tm, input)); - const v = verify(tm, input, out.host, out.modules); - check('the generated split proves against its base', v.failures.length === 0 && v.moved.length === 12 && v.movedTop.length === 5, - [...v.failures, `moved: ${v.moved.map((m) => m.name).join()}`, `top: ${v.movedTop.map((m) => m.name).join()}`].join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const mod = out.modules.get('engine-lifecycle.ts'); - const edited = new Map([...out.modules, ['engine-lifecycle.ts', mod.replace('const p3 = 3;', 'const p3 = 4;')]]); - check('one edited character in a moved body fails', verify(tm, input, out.host, edited).failures.length > 0); - check('an edited stub signature fails', - verify(tm, input, out.host.replace('trx?: Knex.Transaction): Promise', 'trx?: Knex.Transaction): Promise'), out.modules).failures.length > 0); - check('an extra top-level statement in a module fails', - verify(tm, input, out.host, new Map([...out.modules, ['engine-lifecycle.ts', `${mod}\nexport const extra = 1;\n`]])).failures.length > 0); - check('a proof over no moved method fails', verify(tm, input, input, new Map()).failures.length > 0); - const leaf = out.modules.get(LEAF_MODULE); - const leafWith = (text) => new Map([...out.modules, [LEAF_MODULE, text]]); - check('one edited character in a moved declaration fails', - verify(tm, input, out.host, leafWith(leaf.replace('const LOCAL_VALUE = 1;', 'const LOCAL_VALUE = 2;'))).failures.length > 0); - check('an edited comment above a moved declaration fails', - verify(tm, input, out.host, leafWith(leaf.replace('/** A value the leaf takes', '/** A value the leaf holds'))).failures.length > 0); - check('a leaf that imports engine.ts back fails', - verify(tm, input, out.host, leafWith(leaf.replace('\nconst LOCAL_VALUE', "\nimport { ObjectQL } from './engine.js';\nconst LOCAL_VALUE"))).failures.length > 0); - const swapped = leaf.replace('type LocalType = { n: number };\nexport interface ExportedShape { a: number }', - 'export interface ExportedShape { a: number }\ntype LocalType = { n: number };'); - check('two moved declarations out of base order fail', swapped !== leaf && verify(tm, input, out.host, leafWith(swapped)).failures.length > 0); - } - - open('facets, statics and docblocks'); - { - const input = fixtureSource(); - const out = generate(tm, input, fixturePlan(tm, input)); - const mod = out.modules.get('engine-lifecycle.ts') ?? ''; - check('the bodies move into one stateless facet class of static methods', /\nexport class LifecycleFacet \{\n/.test(mod) && - /\n static async movable\(this: Pick ObjectQL.SECRET },\n });\n }\n\n // ${MARK} Installs`) && !out.host.includes('bump:')); - check('a written field gets a host setter that assigns it on the engine', - out.host.includes(' get count() { return engine.count; },\n set count(v) { engine.count = v; },')); - check('a generic method calls its body instantiated with its own type parameters', - out.host.includes('return (LifecycleFacet.generic).call(lifecycleHost.of(this), x);') && mod.includes(' static generic(this: Pick= 3 && - out.host.includes("import { lifecycleHost } from './engine-facet-hosts.js';")); - check('the host module keeps one FacetHost per facet and imports types only', - hostsMod.includes("export const lifecycleHost = new FacetHost('LifecycleFacet');") && - !/^import (?!type )/m.test(hostsMod) && hostsMod.includes("import type { LifecycleHost } from './engine-lifecycle.js';")); - check('a method goes into the host as a closure called on the engine at call time', - /\n [a-z]\w*: \(\.\.\.a\) => engine\.[a-z]\w*\(\.\.\.a\),\n/.test(out.host), out.host.slice(out.host.indexOf('Installs'))); - check('a stub handing another facet\'s host fails', verify(tm, input, - out.host.replace('.call(lifecycleHost.of(this), x)', '.call(otherHost.of(this), x)'), out.modules).failures.length > 0); - check('an edited host module fails', verify(tm, input, out.host, - new Map([...out.modules, [HOSTS_MODULE, hostsMod.replace('this.hosts.set(engine, host);', '')]])).failures.length > 0); - check('a written field\'s setter left out of the host fails', verify(tm, input, - out.host.replace(' set count(v) { engine.count = v; },\n', ''), out.modules).failures.length > 0); - check('a static method keeps its static stub and calls its facet body directly', - out.host.includes(' static staticHelper(n: number): number {\n // [#29986 codemod] The body moved to `engine-lifecycle.ts`.\n return LifecycleFacet.staticHelper(n);\n }')); - const withMod = (text) => new Map([...out.modules, ['engine-lifecycle.ts', text]]); - check('an edited moved docblock fails', verify(tm, input, out.host, - withMod(mod.replace('it moves with the body', 'it moved with the body'))).failures.length > 0); - check('an edited placeholder fails', verify(tm, input, out.host, - withMod(mod.replace(placeholderDoc('other'), placeholderDoc('other').replace('contract', 'promise')))).failures.length > 0); - check('a static forwarded as the wrong kind fails', verify(tm, input, - out.host.replace('SECRET: { get: () => ObjectQL.SECRET },', 'SECRET: { value: ObjectQL.SECRET },'), out.modules).failures.length > 0); - } - - open('import prune'); - { - const input = fixtureSource(); - const out = generate(tm, input, fixturePlan(tm, input)); - check('an import only a moved body read is pruned from engine.ts', out.pruned.includes('onlyMovedReads') && - !out.host.includes('onlyMovedReads'), out.pruned.join()); - check('an import the staying text still reads is kept', out.host.includes("import { seamHelper } from './engine-seam.js';")); - const v = verify(tm, input, out.host, out.modules); - check('the proof recomputes the prune from the head and names it', v.failures.length === 0 && v.pruned.includes('onlyMovedReads'), v.failures.join(' | ')); - const lost = out.host.replace("import { seamHelper } from './engine-seam.js';\n", ''); - check('an import the head lost that no moved text reads fails', verify(tm, input, lost, out.modules).failures.length > 0); - } - - open('refusals'); - { - check('an anchor the class does not declare refuses', - refused(() => plan(tm, fixtureSource(), { anchors: [['gone', 'x', 'engine-x.ts']], pins: {}, needles: {}, classNeedles: {} }))); - check('anchors out of class order refuse', - refused(() => plan(tm, fixtureSource(), { anchors: [['keptSection', 'x', null], ['count', 'y', 'engine-y.ts']], pins: {}, needles: {}, classNeedles: {} }))); - check('a pin naming what the file lacks refuses', refused(() => plan(tm, fixtureSource(), { anchors: FIXTURE_ANCHORS, pins: { gone: 'x' }, needles: {}, classNeedles: {} }))); - check('a class-scoped needle the file no longer carries refuses', - refused(() => plan(tm, fixtureSource(), { anchors: FIXTURE_ANCHORS, pins: {}, needles: {}, classNeedles: { 'gone text': 'x' } }))); - check('a needle the file no longer carries refuses', refused(() => plan(tm, fixtureSource(), { anchors: FIXTURE_ANCHORS, pins: {}, needles: { 'gone text': 'x' }, classNeedles: {} }))); - // `--help` reads no tree: it answers before the "already split" guard, so - // it exits 0 whether engine.ts on disk is split (as on a branch) or not. - check('--help is answered, never refused, whatever engine.ts holds', (await main(['--help']).catch(() => 2)) === 0); - } - - open('scoped classes (second pass)'); - { - const input = scopedFixtureSource(); - const planned = planScoped(tm, input, { classes: FIXTURE_SCOPED_CLASSES }); - const record = (cls, name) => planned.targets.find((t) => t.className === cls)?.records.find((r) => r.name === name); - const why = (cls, name) => (record(cls, name)?.reasons ?? ['']).join('; '); - check('a forwarding method, an assigning one and one constructing a sibling class move', - ['find', 'count'].every((n) => why('ObjectRepository', n) === '') && ['object', 'sudo', 'readFlag'].every((n) => why('ScopedContext', n) === ''), - ['find', 'count'].map((n) => why('ObjectRepository', n)).concat(['object', 'sudo', 'readFlag'].map((n) => why('ScopedContext', n))).join(' | ')); - check('a method that only shares a hand-series import\'s name is not a hand-series stub', why('ObjectRepository', 'count') === '', why('ObjectRepository', 'count')); - check('a body writing a private member of another instance stays (foreign-private)', why('ScopedContext', 'derive').startsWith('foreign-private'), why('ScopedContext', 'derive')); - check('a body handing the instance on stays (bare-this)', why('ScopedContext', 'handsSelf').startsWith('bare-this'), why('ScopedContext', 'handsSelf')); - check('a public method with an inferred return type stays (inferred-return-type)', why('ObjectRepository', 'inferred').startsWith('inferred-return-type'), why('ObjectRepository', 'inferred')); - const out = generateScoped(tm, input, planned); - const again = generateScoped(tm, input, planScoped(tm, input, { classes: FIXTURE_SCOPED_CLASSES })); - const v = verifyScoped(tm, input, out.host, out.modules, { classes: FIXTURE_SCOPED_CLASSES }); - check('the generated scoped split proves against its base', v.failures.length === 0 && v.moved.length === 5, - [...v.failures, `moved: ${v.moved.map((m) => m.name).join()}`].join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const ctxMod = out.modules.get('engine-scoped-context.ts') ?? ''; - const hostsMod = out.modules.get(SCOPED_HOSTS_MODULE) ?? ''; - check('each stub hands its body the one host of its own instance', - out.host.includes('return ScopedContextFacet.sudo.call(scopedContextHost.of(this));') && - out.host.includes('return ObjectRepositoryFacet.find.call(objectRepositoryHost.of(this), query);'), - out.host.slice(out.host.indexOf('sudo('))); - check('the host module keeps one InstanceHost per class and imports types only', - hostsMod.includes("export const scopedContextHost = new InstanceHost('ScopedContextFacet', 'ScopedContext');") && - !/^import (?!type )/m.test(hostsMod)); - check('a private docblock moves with its body; a public one stays on the class', - ctxMod.includes(' /** A private docblock: it moves with the body. */\n static readFlag(') && !out.host.includes('A private docblock') && - out.host.includes(' /** A public docblock: it stays on the class. */\n find(query: any = {}): Promise {')); - check('a field a body assigns gets a setter in its class\'s install block', - out.host.includes(' get flag() { return instance.flag; },\n set flag(v) { instance.flag = v; },')); - check('the first pass\'s class is not touched', out.host.includes(` run(n: number): number {\n // ${MARK} The body moved to \`engine-lifecycle.ts\`.\n return LifecycleFacet.run(n);\n }`) && - !out.host.slice(out.host.indexOf('export class ObjectQL'), out.host.indexOf('export class ObjectRepository')).includes(SCOPED_MARK)); - const verifyWith = (host, mods) => verifyScoped(tm, input, host, mods, { classes: FIXTURE_SCOPED_CLASSES }).failures.length > 0; - check('one edited character in a moved body fails', verifyWith(out.host, - new Map([...out.modules, ['engine-scoped-context.ts', ctxMod.replace('{ ...this.ctx }', '{ ...this.ctx, x: 1 }')]]))); - check('a stub handing the other class\'s host fails', verifyWith(out.host.replace('ScopedContextFacet.sudo.call(scopedContextHost.of(this))', 'ScopedContextFacet.sudo.call(objectRepositoryHost.of(this))'), out.modules)); - check('a written field\'s setter left out of the install block fails', verifyWith(out.host.replace(' set flag(v) { instance.flag = v; },\n', ''), out.modules)); - check('an edited host module fails', verifyWith(out.host, new Map([...out.modules, [SCOPED_HOSTS_MODULE, hostsMod.replace('this.hosts.set(instance, host);', '')]]))); - check('an import only a moved body read is pruned, and the proof names it', out.pruned.includes('onlyScopedReads') && v.pruned.includes('onlyScopedReads'), out.pruned.join()); - check('a scoped class the file does not declare refuses', - refused(() => planScoped(tm, input, { classes: [['Gone', 'engine-gone.ts', 'Gone']] }))); - } - - open('hand-series docblocks (third pass)'); - { - const input = handFixtureEngine(); - const mods = handFixtureModules(); - const planned = planHandDocs(tm, input, mods); - const why = (name) => planned.records.find((r) => r.name === name)?.reason ?? ''; - check('a private stub with one docblock moves; public, undocumented and richer-function stubs stay', - why('privateDoc') === '' && why('betaPrivate') === '' && why('publicDoc').startsWith('public') && - why('noDoc') === 'no-docblock' && why('richer').startsWith('function-docblock') && why('notAStub') === '', - planned.records.map((r) => `${r.name}=${r.reason}`).join(' | ')); - const out = generateHandDocs(tm, input, mods, planned); - const again = generateHandDocs(tm, input, mods, planHandDocs(tm, input, mods)); - const alpha = out.modules.get('engine-alpha.ts') ?? ''; - check('the moved docblock replaces the placeholder, one level out, and the class keeps none', - alpha.includes('/**\n * A private docblock: it moves.\n *\n * Second paragraph.\n */\nexport function privateDoc(') && - !out.host.includes('A private docblock') && out.host.includes(' private privateDoc(n: number): number {\n')); - check('the stub\'s marker gains the phrase after its module', - out.host.includes(`// [#25522 cut 1] The body moved to \`engine-alpha.ts\`${HAND_DOC_MOVED} (see \`AlphaHost\`).`)); - check('a public docblock stays on the class and its function keeps the placeholder', - out.host.includes(' /** A public docblock: it stays. */\n publicDoc(') && alpha.includes(`${placeholderDoc('publicDoc')}\nexport function publicDoc(`)); - check('the module header gains the note once, above its closing line', - alpha.split(HAND_DOCS_NOTE).length === 2 && alpha.includes(`${HAND_DOCS_NOTE}\n */\n`)); - const v = verifyHandDocs(tm, input, out.host, mods, new Map([...mods, ...out.modules])); - check('the generated moves prove against their base', v.failures.length === 0 && v.moved.length === 2, v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const slice = generateHandDocs(tm, input, mods, planHandDocs(tm, input, mods, { modules: ['engine-alpha.ts'] })); - const sliceMods = new Map([...mods, ...slice.modules]); - const rest = generateHandDocs(tm, slice.host, sliceMods, planHandDocs(tm, slice.host, sliceMods)); - check('a slice moves only its modules, and the next slice on its output lands where one run lands', - !slice.modules.has('engine-beta.ts') && slice.host.includes('A beta docblock') && - rest.host === out.host && (rest.modules.get('engine-beta.ts') ?? '') === out.modules.get('engine-beta.ts') && - planHandDocs(tm, slice.host, sliceMods).records.find((r) => r.name === 'privateDoc')?.reason === 'already-moved'); - { - const restMods = new Map([...sliceMods, ...rest.modules]); - const onSlice = verifyHandDocs(tm, slice.host, rest.host, sliceMods, restMods); - const onBase = verifyHandDocs(tm, input, rest.host, mods, restMods); - check('the next slice proves against the earlier slice\'s output, counting only its own moves, and against the unsliced base', - onSlice.failures.length === 0 && onSlice.moved.length === 1 && onSlice.baseMoved === 1 && onBase.failures.length === 0 && onBase.moved.length === 2, - [...onSlice.failures, ...onBase.failures].join(' | ')); - } - const fails = (host, edited) => verifyHandDocs(tm, input, host, mods, new Map([...mods, ...out.modules, ...edited])).failures.length > 0; - check('one edited character in a moved docblock fails', fails(out.host, [['engine-alpha.ts', alpha.replace('Second paragraph.', 'Second paragraph!')]])); - check('one edited character elsewhere in a hand module fails', fails(out.host, [['engine-alpha.ts', alpha.replace('return this.n + n;', 'return this.n - n;')]])); - check('a moved docblock dropped from its function fails', fails(out.host, [['engine-alpha.ts', alpha.replace(/\/\*\*\n \* A private docblock[\s\S]*?\*\/\n/, '')]])); - check('a staying docblock dropped from the class fails', fails(out.host.replace(' /** A public docblock: it stays. */\n', ''), [])); - check('a public docblock moved off the class fails', fails( - out.host.replace(' /** A public docblock: it stays. */\n', '').replace('`engine-alpha.ts` (see `AlphaHost`). PUBLIC', `\`engine-alpha.ts\`${HAND_DOC_MOVED} (see \`AlphaHost\`). PUBLIC`), - [['engine-alpha.ts', alpha.replace(`${placeholderDoc('publicDoc')}\n`, '/** A public docblock: it stays. */\n')]])); - check('a marker that says moved over a docblock still on the class fails', fails( - out.host.replace('`engine-alpha.ts` (see `AlphaHost`). PUBLIC', `\`engine-alpha.ts\`${HAND_DOC_MOVED} (see \`AlphaHost\`). PUBLIC`), [])); - check('a module missing its header note fails', fails(out.host, [['engine-alpha.ts', alpha.replace(`\n${HAND_DOCS_NOTE}`, '')]])); - check('an import only a moved docblock links is pruned with the // lines above it (not before its docblock moves), and the proof names it', - out.pruned.join() === 'LinkedOnly' && v.pruned.join() === 'LinkedOnly' && !out.host.includes('LinkedOnly }') && - !out.host.includes('for the link on') && slice.host.includes('for the link on'), `${out.pruned} | ${v.pruned}`); - check('a binding the head dropped that no moved docblock links fails', - fails(out.host.replace("import { betaPrivate } from './engine-beta.js';\n", ''), [])); - check('--modules naming a module no stub delegates to refuses', - refused(() => planHandDocs(tm, input, mods, { modules: ['engine-gone.ts'] }))); - } - - open('named methods onto the split class (fourth pass)'); - { - const opts = { anchors: FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; - const source = fourthFixtureSource(); - const split = generate(tm, source, plan(tm, source, { ...opts, pins: FOURTH_FIXTURE_PINS })); - const input = split.host; - const mods = split.modules; - const names = ['pinnedTyped', 'pinnedHost']; - check('the first pass keeps the pinned methods on the class (path-reader)', - input.includes(' private async pinnedHost(object: string): Promise {\n const p0') && input.includes(' protected pinnedTyped(x: FourthShape): number {\n const p0')); - const planned = planMembers(tm, input, mods, names, opts); - check('the plan takes both into their section\'s written module, in class order', - [...planned.modules.keys()].join() === 'engine-lifecycle.ts' && planned.records.map((r) => r.name).join() === 'pinnedHost,pinnedTyped', - planned.records.map((r) => `${r.name}->${r.module}`).join()); - const out = generateMembers(tm, input, mods, planned); - const again = generateMembers(tm, input, mods, planMembers(tm, input, mods, names, opts)); - const head = new Map([...mods, ...out.modules]); - const v = verifyMembers(tm, input, out.host, mods, head, opts); - check('the generated moves prove against their base', v.failures.length === 0 && v.moved.length === 2, v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const lifecycle = out.modules.get('engine-lifecycle.ts') ?? ''; - check('each stub is the first pass\'s stub, `async` dropped', - out.host.includes(` private pinnedHost(object: string): Promise {\n // ${MARK} The body moved to \`engine-lifecycle.ts\`, ${DOC_MOVED} (see \`LifecycleHost\`).\n return LifecycleFacet.pinnedHost.call(lifecycleHost.of(this), object);\n }`) && - out.host.includes(` protected pinnedTyped(x: FourthShape): number {\n // ${MARK} The body moved to \`engine-lifecycle.ts\`.\n return LifecycleFacet.pinnedTyped(x);\n }`), - out.host.slice(out.host.indexOf('pinnedHost(') - 80, out.host.indexOf('pinnedHost(') + 300)); - check('a private docblock moves with its body; a protected one stays on the class', - lifecycle.includes(' /** A pinned private docblock: the fourth pass moves it with the body. */\n static async pinnedHost(') && !out.host.includes('A pinned private docblock') && - out.host.includes(' /** A pinned protected docblock: it stays on the class. */\n protected pinnedTyped(') && lifecycle.includes(` ${placeholderDoc('pinnedTyped')}\n static pinnedTyped(`)); - const listed = headerNamesOf(lifecycle, 'Lifecycle')?.names ?? []; - check('the header lists both, in class order after the members declared above them', - listed.indexOf('pinnedHost') > listed.indexOf('generic') && listed.indexOf('pinnedTyped') === listed.indexOf('pinnedHost') + 1, listed.join()); - check('a host member only a moved body reads joins the interface and the factory', - lifecycle.includes(" readonly knex: ObjectQLClass['knex'];") && out.host.includes(' get knex() { return engine.knex; },') && !input.includes('get knex()')); - check('a private static only a moved body reads joins the statics route', - out.host.includes(" readonly bump: (typeof ObjectQL)['bump'];") && out.host.includes(' bump: { get: () => ObjectQL.bump },') && !input.includes("['bump']")); - check('the module imports what the moved members read, ahead of the leaf; engine.ts drops what only the bodies read and keeps the type a stub still names, and the proof names the drops', - /import \{ fourthOnly \} from '\.\/fourth-only\.js';\nimport type \{ FourthShape \} from '\.\/fourth-shape\.js';\n(import[^\n]*\n)*import[^\n]*'\.\/engine-top-level\.js'/.test(lifecycle) && - out.pruned.join() === 'fourthOnly,helperImported' && v.pruned.join() === 'fourthOnly,helperImported' && - out.host.includes("import type { FourthShape } from './fourth-shape.js';"), `${out.pruned} | ${v.pruned}`); - check('a name the class does not declare refuses', refused(() => planMembers(tm, input, mods, ['gone'], opts))); - check('a method already moved refuses', refused(() => planMembers(tm, input, mods, ['movable'], opts))); - check('a method a stay rule holds refuses (inferred-return-type, and a pin that still stands)', - refused(() => planMembers(tm, input, mods, ['inferred'], opts)) && refused(() => planMembers(tm, input, mods, ['pinnedMethod'], opts))); - const fails = (host, edited) => verifyMembers(tm, input, host, mods, new Map([...head, ...edited]), opts).failures.length > 0; - check('one edited character in a moved body fails', fails(out.host, [['engine-lifecycle.ts', lifecycle.replace('return x.n;', 'return x.n + 1;')]])); - check('a host member no body reads, in the interface and the factory, fails', fails( - out.host.replace(' get knex() { return engine.knex; },', ' get knex() { return engine.knex; },\n get zed() { return engine.zed; },'), - [['engine-lifecycle.ts', lifecycle.replace(" readonly knex: ObjectQLClass['knex'];", " readonly knex: ObjectQLClass['knex'];\n readonly zed: ObjectQLClass['zed'];")]])); - check('an import nothing in the module reads fails', fails(out.host, [['engine-lifecycle.ts', lifecycle.replace("import { fourthOnly } from './fourth-only.js';", "import { fourthOnly, unread } from './fourth-only.js';")]])); - check('a stub that kept `async` fails', fails(out.host.replace(' private pinnedHost(object: string)', ' private async pinnedHost(object: string)'), [])); - check('an edit elsewhere in engine.ts, or in a module no moved member is in, fails', - fails(out.host.replace(' return 2 + VIA_SEAM', ' return 3 + VIA_SEAM'), []) && - fails(out.host, [[LEAF_MODULE, (mods.get(LEAF_MODULE) ?? '').replace('const LOCAL_VALUE = 1;', 'const LOCAL_VALUE = 2;')]])); - check('a head that moved nothing fails', verifyMembers(tm, input, input, mods, mods, opts).failures.some((f) => f.startsWith('nothing moved'))); - - // #30572's two shapes: a header a hand edit wrote on after, and a docblock link the base left unresolved. - const baseLife = mods.get('engine-lifecycle.ts') ?? ''; - const baseHeader = headerNamesOf(baseLife, 'Lifecycle'); - const withHeader = (lines) => baseLife.slice(0, baseHeader.region.start) + lines.join('\n') + baseLife.slice(baseHeader.region.end); - const tail = '`handWritten` was written here, beside the gate whose verdict it answers.'.split(' '); - const handMods = new Map([...mods, ['engine-lifecycle.ts', withHeader(moduleHeaderLines('Lifecycle', baseHeader.names, tail))]]); - const hand = generateMembers(tm, input, handMods, planMembers(tm, input, handMods, names, opts)); - const handHead = new Map([...handMods, ...hand.modules]); - const handLife = hand.modules.get('engine-lifecycle.ts') ?? ''; - const handRead = headerNamesOf(handLife, 'Lifecycle'); - const hv = verifyMembers(tm, input, hand.host, handMods, handHead, opts); - check('a header a hand edit wrote on after is accepted: the list grows, the hand\'s words follow it unedited, and the moves prove', - hv.failures.length === 0 && hv.moved.length === 2 && handRead?.tail.join(' ') === tail.join(' ') && - handRead.names.join() === (headerNamesOf(lifecycle, 'Lifecycle')?.names ?? []).join(), hv.failures.join(' | ')); - check('a hand tail that does not rewrap as the pass wraps it refuses', refused(() => generateMembers(tm, input, - new Map([...mods, ['engine-lifecycle.ts', withHeader([...moduleHeaderLines('Lifecycle', baseHeader.names), ' * `handWritten`', ' * was', ' * written', ' * here.'])]]), - planMembers(tm, input, mods, names, opts)))); - check('one edited character in the hand\'s words at head fails', - verifyMembers(tm, input, hand.host, handMods, new Map([...handHead, ['engine-lifecycle.ts', handLife.replace('verdict it answers.', 'verdict it answers!')]]), opts).failures.length > 0); - const linkDoc = (extra) => baseLife.replace(placeholderDoc('writes'), `/** The body of \`ObjectQL#writes\`; see {@link FourthShape}${extra}. */`); - const linkMods = new Map([...mods, ['engine-lifecycle.ts', linkDoc('')]]); - const link = generateMembers(tm, input, linkMods, planMembers(tm, input, linkMods, names, opts)); - const linkHead = new Map([...linkMods, ...link.modules]); - const linkLife = link.modules.get('engine-lifecycle.ts') ?? ''; - const lv = verifyMembers(tm, input, link.host, linkMods, linkHead, opts); - check('a base docblock link a moved body\'s import comes to resolve: the undo drops the binding the move added, and the moves prove byte for byte', - linkLife.includes("import type { FourthShape } from './fourth-shape.js';") && !linkDoc('').includes("from './fourth-shape.js'") && - lv.failures.length === 0 && lv.moved.length === 2, lv.failures.join(' | ')); - { - const extraMods = new Map([...mods, ['engine-lifecycle.ts', linkDoc(' and {@link ExtraLinked}')]]); - const extra = generateMembers(tm, input, extraMods, planMembers(tm, input, extraMods, names, opts)); - const extraLife = (extra.modules.get('engine-lifecycle.ts') ?? '').replace("import type { FourthShape } from './fourth-shape.js';", "import type { ExtraLinked, FourthShape } from './fourth-shape.js';"); - const ev = verifyMembers(tm, input, extra.host, extraMods, new Map([...extraMods, ...extra.modules, ['engine-lifecycle.ts', extraLife]]), opts); - check('a binding the head added that only a staying docblock links, and no moved member reads, fails', - extraLife.includes('ExtraLinked, FourthShape') && ev.failures.some((f) => f.includes('ExtraLinked') && f.includes('no moved member reads')), ev.failures.join(' | ')); - } - } - - open('identity port, computed keys and exported names (fourth pass, #30020)'); - { - const opts = { anchors: IDENTITY_FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; - const source = identityFixtureSource(); - const split = generate(tm, source, plan(tm, source, opts)); - const input = split.host; - const mods = split.modules; - const names = ['computed', 'identity']; - check('the first pass keeps the methods that read `this` bare on the class (bare-this)', - input.includes(' private identity(n: number): Scoped {\n const p0') && input.includes(" private computed(slot: 'knex' | 'logger'): unknown {\n const p0") && - (mods.get('engine-identity.ts') ?? '').includes('static seed(')); - const planned = planMembers(tm, input, mods, names, opts); - check('the plan takes both into their section\'s written module, in class order', - [...planned.modules.keys()].join() === 'engine-identity.ts' && planned.records.map((r) => r.name).join() === 'identity,computed', - planned.records.map((r) => `${r.name}->${r.module}`).join()); - const out = generateMembers(tm, input, mods, planned); - const again = generateMembers(tm, input, mods, planMembers(tm, input, mods, names, opts)); - const head = new Map([...mods, ...out.modules]); - const v = verifyMembers(tm, input, out.host, mods, head, opts); - check('the generated moves prove against their base', v.failures.length === 0 && v.moved.length === 2, v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const idm = out.modules.get('engine-identity.ts') ?? ''; - const baseIdm = mods.get('engine-identity.ts') ?? ''; - check('R1: each bare `this` reads `this.facade`, and an object-literal method keeps its own `this`', - idm.includes(' const self = (this.facade as any)._flag ? this.facade : null;\n return new Scoped(n + this.count + nested.get(), self ?? this.facade);') && - idm.includes(' const nested = { k: 1, get(): number { return this.k; } };'), idm.slice(idm.indexOf('static identity'), idm.indexOf('static identity') + 900)); - check('R1: the body\'s `this` names the identity port beside the members it reads', - idm.includes("static identity(this: Pick, n: number): Scoped {")); - check('R1: the host interface gains the identity port under its docblock, and the factory hands the engine', - idm.includes(`${FACADE_DOC}\n readonly facade: ObjectQL;`) && out.host.includes(`\n${FACADE_INSTALL_LINE}\n`) && - !baseIdm.includes(FACADE_DOC) && !input.includes(FACADE_INSTALL_LINE)); - check('R3: a computed key over field names reads them through the host, the body\'s text unchanged', - idm.includes("static computed(this: Pick, slot: 'knex' | 'logger'): unknown {\n" + - `${Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n')}\n const v = this[slot];\n this[slot] = v as never;`)); - check('R3: a key the body assigns through gains a setter, in the interface and the factory', - idm.includes(" knex: ObjectQL['knex'];") && idm.includes(" logger: ObjectQL['logger'];") && - out.host.includes(' get knex() { return engine.knex; },\n set knex(v) { engine.knex = v; },')); - check('R4: an exported class engine.ts declares is imported from it as a value, and the header says so', - idm.includes("import { Scoped } from './engine.js';\nimport type { ObjectQL } from './engine.js';") && - idm.includes(VALUES_CYCLE_PARA) && !idm.includes(TYPES_CYCLE_PARA) && baseIdm.includes(TYPES_CYCLE_PARA)); - check('a computed key of any string, or over a method name, stays (bare-this)', - refused(() => planMembers(tm, input, mods, ['keyedString'], opts)) && refused(() => planMembers(tm, input, mods, ['keyedMethod'], opts))); - check('a `this` in a type position stays', refused(() => planMembers(tm, input, mods, ['typedThis'], opts))); - check('R4 imports only what engine.ts exports: a staying name it does not export refuses', - /widen the generated export lists/.test(refusalOf(() => planMembers(tm, input, mods, ['handsToLocal'], opts))), refusalOf(() => planMembers(tm, input, mods, ['handsToLocal'], opts))); - check('a body that already reads `this.facade` refuses, so the undo stays the one inverse (unknown-member)', - /unknown-member: facade/.test(refusalOf(() => planMembers(tm, input, mods, ['readsFacade'], opts)))); - { - const taken = identityFixtureSource({ facadeField: true }); - const tsplit = generate(tm, taken, plan(tm, taken, opts)); - check('a class that declares `facade` refuses the identity port (facade-taken)', - /facade-taken/.test(refusalOf(() => planMembers(tm, tsplit.host, tsplit.modules, ['identity'], opts)))); - } - // A negative control whose edit changed nothing would pass for the wrong reason: it fails the case instead. - const fails = (host, edited) => !(host === out.host && edited.every(([f, t]) => t === head.get(f))) && - verifyMembers(tm, input, host, mods, new Map([...head, ...edited]), opts).failures.length > 0; - check('a `this.facade` the rewrite did not write fails', fails(out.host, [['engine-identity.ts', idm.replace('n + this.count', 'n + this.facade.count')]])); - check('a rewritten site put back to a bare `this` fails', fails(out.host, [['engine-identity.ts', idm.replace('self ?? this.facade', 'self ?? this')]])); - check('a factory that does not hand the engine fails', fails(out.host.replace(`\n${FACADE_INSTALL_LINE}`, ''), [])); - check('an identity port without its docblock fails', fails(out.host, [['engine-identity.ts', idm.replace(`${FACADE_DOC}\n`, '')]])); - check('a header left saying "types only" beside a value import fails', - fails(out.host, [['engine-identity.ts', idm.replace(VALUES_CYCLE_PARA, TYPES_CYCLE_PARA)]])); - { - // A leaf statement a hand grew on one line past the wrap width (#30227 left one in - // engine-security-resolvers.ts): the move and the undo render it back on one line. - const leaf = leafSpecifier(); - const long = ['alphaPlanEntry', 'betaPlanEntry', 'computeStoredExpressionsLong', 'deltaProjectionPlanner', 'epsilonRelatedFields']; - const oneLine = `import { ${long.join(', ')} } from '${leaf}';`; - const decls = importDeclsOf(tm, 'engine-identity.ts', `${oneLine}\nimport type { ObjectQL } from './engine.js';\n`); - const run = decls.filter((d) => d.specifier === leaf); - const styles = runStyles(`${oneLine}\nimport type { ObjectQL } from './engine.js';\n`, run, leaf); - const grown = new Map([...run[0].bindings, ['GAMMA_SLOT', { form: 'named', imported: 'GAMMA_SLOT', value: true }]]); - const rendered = specifierLines(leaf, grown, styles ?? {}); - check('a leaf import a hand grew on one line past the wrap width reads as `line`, and a name a move adds keeps it on one line', - oneLine.length > 120 && styles?.value === 'line' && - rendered?.join('\n') === `import { ${[...grown.keys()].sort().join(', ')} } from '${leaf}';` && - specifierLines(leaf, grown, {}).join('\n') !== rendered.join('\n'), JSON.stringify({ styles, rendered })); - const wrapped = namedStatement('import', long, ` from '${leaf}';`); - check('the first pass\'s own wrapped statement reads as `wrap`', - wrapped.includes('\n') && runStyles(wrapped, importDeclsOf(tm, 'engine-identity.ts', wrapped), leaf)?.value === 'wrap'); - const neither = `import { ${long.slice(0, 3).join(', ')},\n ${long.slice(3).join(', ')} } from '${leaf}';`; - check('a statement in neither form reads as null, so the pass refuses the run rather than rewrap it', - runStyles(neither, importDeclsOf(tm, 'engine-identity.ts', neither), leaf) === null); - } - } - - open('statics route for a written module (fourth pass, #30020 R10)'); - { - const opts = { anchors: IDENTITY_FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; - const source = identityFixtureSource({ staticReader: true }); - const split = generate(tm, source, plan(tm, source, opts)); - const input = split.host; - const mods = split.modules; - const baseIdm = mods.get('engine-identity.ts') ?? ''; - const routedLife = mods.get('engine-lifecycle.ts') ?? ''; - check('the first pass keeps the static reader on the class (bare-this) and writes its section\'s module off the statics route', - input.includes(' protected staticReader(n: number): number {\n const p0') && baseIdm.includes('static seed(') && - !routesStatics(baseIdm) && baseIdm.includes(`\n${unroutedEngineImport()}\n`) && routesStatics(routedLife)); - const planned = planMembers(tm, input, mods, ['staticReader'], opts); - check('the plan reroutes that module for a mover that reads a non-public static', - [...planned.reroutes].join() === 'engine-identity.ts' && planned.records.map((r) => r.name).join() === 'staticReader'); - const out = generateMembers(tm, input, mods, planned); - const again = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['staticReader'], opts)); - const head = new Map([...mods, ...out.modules]); - const v = verifyMembers(tm, input, out.host, mods, head, opts); - check('the generated move proves against its base', v.failures.length === 0 && v.moved.join() === 'staticReader', v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const idm = out.modules.get('engine-identity.ts') ?? ''; - const engineLines = (t) => importDeclsOf(tm, 'x.ts', t).filter((d) => d.specifier === './engine.js').map((d) => t.slice(d.start, d.end)).join('\n'); - check('the `./engine.js` line becomes the routed pair, exactly as the first pass writes it for a module it routes', - engineLines(idm) === routedEngineImports() && !idm.includes(unroutedEngineImport()) && - engineLines(routedLife).includes("import { ObjectQLStatics as ObjectQL, ") && engineLines(routedLife).endsWith("\nimport type { ObjectQL as ObjectQLClass } from './engine.js';"), engineLines(idm)); - check('the host interface types every member by the class alias, the identity port too', - idm.includes(" readonly count: ObjectQLClass['count'];") && idm.includes(`${FACADE_DOC}\n readonly facade: ObjectQLClass;`) && - !/: ObjectQL\[/.test(idm) && !idm.includes('facade: ObjectQL;')); - check('the header gains the statics paragraph between the host paragraph and the import paragraph, which now says values', - idm.includes(`\n *\n${STATICS_PARA}\n *\n${VALUES_CYCLE_PARA}\n */`) && routedLife.includes(`\n *\n${STATICS_PARA}\n *\n`) && - baseIdm.includes(`\n *\n${TYPES_CYCLE_PARA}\n */`) && !baseIdm.includes(STATICS_PARA)); - check('the moved body reads `ObjectQL.SECRET` unedited, through the forwarder the route already carries', - idm.includes(' return n + ObjectQL.SECRET + this.count + (self ? 1 : 0);') && out.host === pruneHostImports(tm, out.host, usedImportNames(tm, out.host)).text && - out.host.includes(" readonly SECRET: (typeof ObjectQL)['SECRET'];")); - { - // The move without R10's rewrite: the body reads `ObjectQL.SECRET` through a type-only import. - const offRoute = generateMembers(tm, input, mods, { ...planned, reroutes: new Set() }); - const ov = verifyMembers(tm, input, offRoute.host, mods, new Map([...mods, ...offRoute.modules]), opts); - check('a moved member that reads a static in a module left off the route fails', - !routesStatics(offRoute.modules.get('engine-identity.ts') ?? '') && ov.failures.some((f) => f.includes('off the statics route')), ov.failures.join(' | ')); - } - check('the rewrite and its undo are inverses on the base module', - withCyclePara(unrouteModule(tm, 'engine-identity.ts', rerouteModule(tm, 'engine-identity.ts', baseIdm), () => {}) ?? '', 'engine-identity.ts') === baseIdm); - // A negative control whose edit changed nothing would pass for the wrong reason: it fails the case instead. - const fails = (edited, re = null) => { - if (edited.every(([f, t]) => t === head.get(f))) return false; - const fs = verifyMembers(tm, input, out.host, mods, new Map([...head, ...edited]), opts).failures; - return fs.length > 0 && (!re || fs.some((f) => re.test(f))); - }; - check('a head without the statics paragraph fails', fails([['engine-identity.ts', idm.replace(`\n *\n${STATICS_PARA}`, '')]], /statics paragraph/)); - check('a head whose `./engine.js` lines are not the routed pair fails', - fails([['engine-identity.ts', idm.replace(`import type { ObjectQL as ObjectQLClass } from './engine.js';`, `import { ObjectQL as ObjectQLClass } from './engine.js';`)]], /routed pair|statics route's pair/)); - check('a host interface member left typed by the class itself fails', - fails([['engine-identity.ts', idm.replace(" readonly count: ObjectQLClass['count'];", " readonly count: ObjectQL['count'];")]])); - { - // A module put on the route though no moved member reads a static: the undo refuses it. - const plain = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['computed'], opts)); - const plainIdm = plain.modules.get('engine-identity.ts') ?? ''; - const forced = rerouteModule(tm, 'engine-identity.ts', plainIdm); - const pv = verifyMembers(tm, input, plain.host, mods, new Map([...mods, ...plain.modules, ['engine-identity.ts', forced]]), opts); - check('a module rerouted though no member the pass moved reads a static fails', - !routesStatics(plainIdm) && routesStatics(forced) && pv.failures.some((f) => f.includes('no member this pass moved reads a static')), pv.failures.join(' | ')); - } - check('a module whose code names `ObjectQL` outside its import and host interface refuses the route (static-route-conflict)', - /static-route-conflict/.test(refusalOf(() => planMembers(tm, input, new Map([...mods, ['engine-identity.ts', baseIdm.replace(' return this.count;', ' return this.count as ObjectQL[\'count\'];')]]), ['staticReader'], opts)))); - check('R4 into a module this pass reroutes refuses, as it does for a routed one', - /takes the statics route/.test(refusalOf(() => planMembers(tm, input, mods, ['identity', 'staticReader'], opts)))); - { - const r4 = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['identity'], opts)); - const r4Mods = new Map([...mods, ...r4.modules]); - // E5's shape (`engine-insert.ts`): other plain `./engine.js` names beside the type-only class. - const r4Idm = r4.modules.get('engine-identity.ts') ?? ''; - const r4Run = engineRunOf(tm, 'engine-identity.ts', r4Idm, [CLASS_NAME]); - const r4Refusal = refusalOf(() => rerouteModule(tm, 'engine-identity.ts', r4Idm)); - const r4Routed = r4Refusal ? '' : rerouteModule(tm, 'engine-identity.ts', r4Idm); - check('a module whose `./engine.js` line carries other plain names beside the type-only class is rerouted, keeping them beside the pair', - !r4Refusal && r4Run && r4Run.others.size > 0 && r4Run.text === unroutedEngineImport(r4Run.others) && - engineLines(r4Routed) === routedEngineImports(r4Run.others) && routesStatics(r4Routed), r4Refusal || engineLines(r4Routed)); - check('R10 undoes that reroute to the module it read, other names and all', - !r4Refusal && unrouteModule(tm, 'engine-identity.ts', r4Routed, () => {}) === r4Idm); - // staticReader made to read `Scoped`, which the rerouted module already imports. - const scopedHost = r4.host.replace(' return n + ObjectQL.SECRET + this.count + (self ? 1 : 0);', ' return n + ObjectQL.SECRET + this.count + (self ? 1 : 0) + new Scoped(0, this).n;'); - let scopedMod = ''; - const scopedRefusal = refusalOf(() => { - scopedMod = generateMembers(tm, scopedHost, r4Mods, planMembers(tm, scopedHost, r4Mods, ['staticReader'], opts)).modules.get('engine-identity.ts') ?? ''; - }); - check('R4 of a name a routed module already imports on its `./engine.js` line needs no edit there', - !scopedRefusal && scopedHost !== r4.host && scopedMod.includes('new Scoped(0, this.facade).n') && engineLines(scopedMod) === routedEngineImports(r4Run.others), - scopedRefusal || engineLines(scopedMod)); - check('a module whose `./engine.js` import is not as the first pass writes it refuses the route', - /not the one/.test(refusalOf(() => planMembers(tm, input, new Map([...mods, ['engine-identity.ts', baseIdm.replace(unroutedEngineImport(), unroutedEngineImport().replace('{ ', '{'))]]), ['staticReader'], opts)))); - } - check('a module already on the route is not rerouted', refused(() => rerouteModule(tm, 'engine-lifecycle.ts', routedLife))); - } - - open('a facet the anchor names and the first pass never wrote (fourth pass, #30020 R11)'); - { - const opts = { anchors: START_FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; - const source = identityFixtureSource({ startSection: true }); - const split = generate(tm, source, plan(tm, source, opts)); - const input = split.host; - const mods = split.modules; - const file = 'engine-hand-on.ts'; - const names = ['handsOnStatic', 'handsOn']; - check('the first pass keeps every method of the section on the class (bare-this) and writes no module for it', - !mods.has(file) && input.includes(' protected handsOn(n: number): Scoped {\n const p0') && - input.includes(' private handsOnStatic(n: number): number {\n const p0') && mods.has('engine-identity.ts') && mods.has(HOSTS_MODULE)); - const planned = planMembers(tm, input, mods, names, opts); - check('the plan starts the module its anchor names, the members in class order', - [...planned.starts].join() === file && [...planned.modules.keys()].join() === file && - planned.records.map((r) => r.name).join() === 'handsOn,handsOnStatic', planned.records.map((r) => `${r.name}->${r.module}`).join()); - const out = generateMembers(tm, input, mods, planned); - const again = generateMembers(tm, input, mods, planMembers(tm, input, mods, names, opts)); - const head = new Map([...mods, ...out.modules]); - const v = verifyMembers(tm, input, out.host, mods, head, opts); - check('the generated moves prove against their base, the module absent there', v.failures.length === 0 && v.moved.length === 2, v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const hom = out.modules.get(file) ?? ''; - check('the started module is the first pass\'s text for its members: header list, routed, the identity port, the private docblock with its body', - headerNamesOf(hom, 'Hand-on')?.names.join() === 'handsOn,handsOnStatic' && routesStatics(hom) && hom.includes(`\n *\n${STATICS_PARA}\n *\n${VALUES_CYCLE_PARA}\n */`) && - hom.includes(`${FACADE_DOC}\n readonly facade: ObjectQLClass;`) && hom.includes('export class HandOnFacet {') && - hom.includes(' /** Reads a private static and the engine itself: the module R11 starts takes the statics route. */\n static handsOnStatic(') && - hom.includes(' return new Scoped(n + this.count, this.facade);') && hom.includes("import { ObjectQLStatics as ObjectQL, Scoped } from './engine.js';\nimport type { ObjectQL as ObjectQLClass } from './engine.js';"), hom); - check('engine.ts imports the facet under its comment, in section order, ahead of the hosts import', - out.host.includes(`import { IdentityFacet } from './engine-identity.js';\n${facetImportText(file, 'Hand-on', true)}${HOSTS_IMPORT_COMMENT}`), out.host.slice(0, 1600)); - check('the hosts import gains the host, sorted, and the install block its call, sorted, handing the engine', - out.host.includes("import { handOnHost, identityHost, lifecycleHost } from './engine-facet-hosts.js';") && - out.host.includes(` static {\n handOnHost.install((engine) => ({\n count: (`) === false && /\n {4}handOnHost\.install\(\(engine\) => \(\{\n[^]*?\n {4}\}\)\);\n {4}identityHost\.install/.test(out.host) && - (installRegionOf(out.host, file)?.members.get('facade') === 'facade')); - check('the hosts module is the first pass\'s text for one module more', - out.modules.get(HOSTS_MODULE) === hostsModuleText(['engine-hand-on.ts', 'engine-identity.ts', 'engine-lifecycle.ts']) && - (out.modules.get(HOSTS_MODULE) ?? '').includes("export const handOnHost = new FacetHost('HandOnFacet');") && - hostsModuleFilesOf(mods.get(HOSTS_MODULE) ?? '')?.join() === 'engine-identity.ts,engine-lifecycle.ts'); - check('the stubs name the started module and hand its host', - out.host.includes(' return HandOnFacet.handsOn.call(handOnHost.of(this), n);') && out.host.includes(' return HandOnFacet.handsOnStatic.call(handOnHost.of(this), n);')); - // A negative control whose edit changed nothing would pass for the wrong reason: it fails the case instead. - const fails = (host, edited, re = null) => { - if (host === out.host && edited.every(([f, t]) => t === head.get(f))) return false; - const fs = verifyMembers(tm, input, host, mods, new Map([...head, ...edited]), opts).failures; - return fs.length > 0 && (!re || fs.some((f) => re.test(f))); - }; - check('a started module with one line more than the first pass writes fails', - fails(out.host, [[file, hom.replace('export class HandOnFacet {', '// hand\nexport class HandOnFacet {')]], /not the module the first pass writes/)); - check('a started module taken off the statics route fails', - fails(out.host, [[file, hom.replace(`\n *\n${STATICS_PARA}`, '')]], /off the statics route|not the module/)); - check('a hosts module that lacks the started facet\'s host fails', - fails(out.host, [[HOSTS_MODULE, mods.get(HOSTS_MODULE)]], /lacks a host for engine-hand-on\.ts/)); - check('an engine.ts that keeps a second copy of the facet import fails', - fails(out.host.replace(HOSTS_IMPORT_COMMENT, `${facetImportText(file, 'Hand-on', true)}${HOSTS_IMPORT_COMMENT}`), [], /import its facet once/)); - check('an engine.ts without the started facet\'s install call fails', - fails(out.host.replace(/\n {4}handOnHost\.install\(\(engine\) => \(\{\n[^]*?\n {4}\}\)\);/, ''), [], /handOnHost|host factory|HandOnHost|install/)); - check('a module started where its base already had one is the written-module path, not R11', - refused(() => planMembers(tm, input, new Map([...mods, [file, '// not the first pass\n']]), names, opts))); - check('a name R11 generates that engine.ts already binds refuses', - /a name R11 generates/.test(refusalOf(() => planMembers(tm, input.replace('export class ObjectQL {', 'const handOnHost = 0;\nexport class ObjectQL {'), mods, names, opts)))); - { - const noHosts = new Map([...mods].filter(([f]) => f !== HOSTS_MODULE)); - check('a body that reads the class refuses to start a facet without the hosts module the first pass wrote', - /R11 adds engine-hand-on\.ts's host/.test(refusalOf(() => planMembers(tm, input, noHosts, names, opts)))); - } - check('a section that maps to no module still keeps its method (section-kept)', - /section-kept/.test(refusalOf(() => planMembers(tm, input, mods, ['keptSection'], opts)))); - } - - open('constructor and definite-assignment wiring (fourth pass, #30020 R8)'); - { - const opts = { anchors: IDENTITY_FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; - const splitOf = (source) => generate(tm, source, plan(tm, source, opts)); - const source = ctorFixtureSource(); - const split = splitOf(source); - const input = split.host; - const mods = split.modules; - check('the first pass keeps the constructor on the class, whole', - input.includes(" this.log = opts.log || makeLog('engine');\n // A comment the facet keeps.") && (mods.get('engine-identity.ts') ?? '').includes('static seed(')); - const planned = planMembers(tm, input, mods, ['constructor'], opts); - const r = planned.records[0]; - check('the plan takes the constructor into its section\'s module, with R8 keeping the leading `this.log = …` on the class', - [...planned.modules.keys()].join() === 'engine-identity.ts' && r.name === 'constructor' && - r.r8.map((a) => `${a.field}:${a.fn}`).join() === 'log:constructLog' && r.facetNames.join() === 'constructLog,construct', - JSON.stringify({ r8: r.r8?.map((a) => a.field), names: r.facetNames })); - const out = generateMembers(tm, input, mods, planned); - const again = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['constructor'], opts)); - const head = new Map([...mods, ...out.modules]); - const v = verifyMembers(tm, input, out.host, mods, head, opts); - check('the generated move proves against its base', v.failures.length === 0 && v.moved.join() === 'constructor', v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const idm = out.modules.get('engine-identity.ts') ?? ''; - check('the stub: the marker, R8\'s assignment from its facet member, then one `construct` call with the parameters the body reads', - out.host.includes(' constructor(opts: { log?: { info(m: string): void }; n?: number } = {}, spare = 0) {\n' + - ' // [#29986 codemod] The body moved to `engine-identity.ts` (see `IdentityHost`).\n' + - ' this.log = IdentityFacet.constructLog(opts);\n' + - ' IdentityFacet.construct.call(identityHost.of(this), opts);\n }\n'), out.host.slice(out.host.indexOf(' constructor('), out.host.indexOf(' constructor(') + 400)); - check('R8: the facet member returns the right side, typed as the field, taking only the parameters it reads', - idm.includes(" static constructLog(opts: { log?: { info(m: string): void }; n?: number } = {}): ObjectQL['log'] {\n return opts.log || makeLog('engine');\n }"), - idm.slice(idm.indexOf('static constructLog') - 200, idm.indexOf('static constructLog') + 300)); - check('the body: `construct` reads the host, R1 hands `this.facade`, and the marker stands where R8\'s statement did', - idm.includes(" static construct(this: Pick, opts: { log?: { info(m: string): void }; n?: number } = {}): void {\n" + - ' // The log, from the options or made.\n' + - ` ${r8MarkerText('log', 'constructLog')}\n` + - ' // A comment the facet keeps.\n this.knex = opts.n ?? null;\n registerAll(this.facade, this.count);\n' + - ' if ((this.facade as any)._flag) this.knex = 1;\n'), idm.slice(idm.indexOf('static construct('), idm.indexOf('static construct(') + 600)); - check('the imports only the constructor read leave engine.ts for the facet, and the header lists both members', - out.pruned.slice().sort().join() === 'makeLog,registerAll' && idm.includes("import { makeLog } from './log-maker.js';") && - idm.includes("import { registerAll } from './register-all.js';") && /`constructLog`,\s+\*?\s*`construct`/.test(idm), out.pruned.join()); - check('a field the body writes gains a setter; the one R8 kept on the class does not', - out.host.includes(' set knex(v) { engine.knex = v; },') && !out.host.includes('set log(v)')); - // Refusals: what R8 does not carry keeps the constructor whole. - const refusal = (body) => { const sp = splitOf(ctorFixtureSource({ body })); return refusalOf(() => planMembers(tm, sp.host, sp.modules, ['constructor'], opts)); }; - const late = refusal([CTOR_FIXTURE_BODY[3], CTOR_FIXTURE_BODY[1], CTOR_FIXTURE_BODY[6]]); - check('a required field written after another statement refuses (definite-assignment)', /definite-assignment: log/.test(late), late); - const readsThis = refusal([" this.log = this.knex ? makeLog('k') : makeLog('engine');", CTOR_FIXTURE_BODY[6]]); - check('an R8 right side that reads `this` refuses (definite-assignment)', /definite-assignment: log/.test(readsThis), readsThis); - const readsLocal = refusal([' this.log = makeLog(namesClass.name);', CTOR_FIXTURE_BODY[6]]); - check('an R8 right side that reads a top-level name of engine.ts refuses (definite-assignment)', /definite-assignment: log/.test(readsLocal), readsLocal); - { - const sp = splitOf(ctorFixtureSource({ constructField: true })); - check('a class that declares `construct` refuses (ctor-facet-name)', /ctor-facet-name/.test(refusalOf(() => planMembers(tm, sp.host, sp.modules, ['constructor'], opts)))); - } - const fails = (host, edited) => !(host === out.host && edited.every(([f, t]) => t === head.get(f))) && - verifyMembers(tm, input, host, mods, new Map([...head, ...edited]), opts).failures.length > 0; - check('an edited R8 right side fails', fails(out.host, [['engine-identity.ts', idm.replace("makeLog('engine');\n }", "makeLog('Engine');\n }")]])); - check('a stub that dropped R8\'s assignment fails', fails(out.host.replace(' this.log = IdentityFacet.constructLog(opts);\n', ''), [])); - check('a marker that names another facet member fails', fails(out.host, [['engine-identity.ts', idm.replace(r8MarkerText('log', 'constructLog'), r8MarkerText('log', 'constructLogs'))]])); - check('a statement the body moved back above the marker fails', - fails(out.host, [['engine-identity.ts', idm.replace(` ${r8MarkerText('log', 'constructLog')}\n // A comment the facet keeps.\n this.knex = opts.n ?? null;`, ` this.knex = opts.n ?? null;\n ${r8MarkerText('log', 'constructLog')}\n // A comment the facet keeps.`)]])); - } - - open('hand-series host slots (fifth pass, #30020)'); - { - const input = slotFixtureEngine(); - const mods = slotFixtureModules(); - const planned = planHandSlots(tm, input, mods, ['gammaServe']); - check('the plan names the one computing slot of the stub', - planned.records.length === 1 && planned.records[0].slots.map((s) => s.slot).join() === 'judge' && planned.records[0].hostType === 'GammaHost', - JSON.stringify(planned.records.map((r) => [r.name, r.slots.map((s) => s.slot)]))); - const out = generateHandSlots(tm, input, mods, planned); - const again = generateHandSlots(tm, input, mods, planHandSlots(tm, input, mods, ['gammaServe'])); - const head = new Map([...mods, ...out.modules]); - const v = verifyHandSlots(tm, input, out.host, mods, head); - check('the generated move proves against its base', v.failures.length === 0 && v.moved.length === 1, v.failures.join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const gamma = out.modules.get('engine-gamma.ts') ?? ''; - check('the slot names its const, and engine.ts imports it beside the function', - out.host.includes(' judge,\n other: (...a) => this.n + a.length,') && - out.host.includes("import { gammaLocal, gammaOnly, gammaServe, gammaThis, gammaTpl, judge } from './engine-gamma.js';")); - check('the hand module holds the arrow one level out, typed as the host member, under the docblock', - gamma.endsWith(`\n${handSlotDoc('judge', 'gammaServe', 'gammaServe')}\nexport const judge: GammaHost['judge'] = (name, plan) => {\n try {\n const p: Plan = planOf(name, plan);\n return p.ok;\n } catch {\n // A plan that does not compile is judged no.\n return false;\n }\n};\n`), gamma.slice(-500)); - check('the hand module imports what the arrow reads, by statements of its own after its last import', - gamma.includes("import type { ObjectQL } from './engine.js';\nimport { planOf } from './engine-top-level.js';\nimport type { Plan } from './plan-types.js';\n")); - check('engine.ts drops the import only the slot read and keeps one another stub still reads, and the proof names the drop', - out.pruned.join() === 'Plan' && v.pruned.join() === 'Plan' && !out.host.includes("from './plan-types.js'") && - out.host.includes("import { planOf } from './engine-top-level.js';"), `${out.pruned} | ${v.pruned}`); - const fails = (host, edited) => !(host === out.host && edited.every(([f, t]) => t === head.get(f))) && - verifyHandSlots(tm, input, host, mods, new Map([...head, ...edited])).failures.length > 0; - check('one edited character in the moved arrow fails', fails(out.host, [['engine-gamma.ts', gamma.replace('return false;', 'return true;')]])); - check('a moved const whose docblock was edited fails', fails(out.host, [['engine-gamma.ts', gamma.replace('moved here whole', 'moved here wholly')]])); - check('an import statement that also binds a name nothing reads fails', - fails(out.host, [['engine-gamma.ts', gamma.replace("import { planOf } from './engine-top-level.js';", "import { planOf, unread } from './engine-top-level.js';")]])); - check('an engine.ts that kept an import only the slot read fails', fails(`import { planOf } from './engine-top-level.js';\n${out.host}`, [])); - check('a head that moved nothing fails', verifyHandSlots(tm, input, input, mods, mods).failures.some((f) => f.startsWith('nothing moved'))); - check('a slot that reads the stub\'s `this` refuses', /reads `this`/.test(refusalOf(() => planHandSlots(tm, input, mods, ['gammaThis'])))); - check('a slot that reads a local of the stub refuses', /the stub declares/.test(refusalOf(() => planHandSlots(tm, input, mods, ['gammaLocal'])))); - check('a stub whose slots all forward refuses', /no computing slot/.test(refusalOf(() => planHandSlots(tm, input, mods, ['gammaOnly'])))); - check('a slot holding a template that spans lines refuses', /spanning lines/.test(refusalOf(() => planHandSlots(tm, input, mods, ['gammaTpl'])))); - check('a method that is not a hand stub refuses', refused(() => planHandSlots(tm, `${input.replace(' // The body lives in `engine-gamma.ts` (see `GammaHost`).\n const readN', ' const readN')}`, mods, ['gammaServe']))); - } - - open('scoped members, instance identity port and symbol keys (second pass, #30020 S1)'); - { - const classes = FIXTURE_SCOPED_CLASSES; - const source = scopedMembersFixtureSource(); - const firstPlan = planScoped(tm, source, { classes }); - const why = (name) => (firstPlan.targets[1].records.find((r) => r.name === name)?.reasons ?? ['']).join('; '); - check('the second pass keeps a body handing the instance on (bare-this) and a symbol-keyed one (not-identifier-name)', - why('handsSelf').startsWith('bare-this') && why('[SEED_KEY]').startsWith('not-identifier-name'), `${why('handsSelf')} | ${why('[SEED_KEY]')}`); - const split = generateScoped(tm, source, firstPlan); - const input = split.host; - const mods = split.modules; - const names = ['ScopedContext#[SEED_KEY]', 'ScopedContext#handsSelf']; - const planned = planScopedMembers(tm, input, mods, names, { classes }); - check('the plan takes both into the class\'s written module, in class order, the symbol key under its facet name', - planned.records.map((r) => `${r.name}>${r.facetName}`).join() === 'handsSelf>handsSelf,[SEED_KEY]>seedKey' && - [...planned.modules.keys()].join() === 'engine-scoped-context.ts', planned.records.map((r) => `${r.name}>${r.facetName}`).join()); - const out = generateScopedMembers(tm, input, mods, planned); - const again = generateScopedMembers(tm, input, mods, planScopedMembers(tm, input, mods, names, { classes })); - const head = new Map([...mods, ...out.modules]); - const v = verifyScopedMembers(tm, input, out.host, mods, head, { classes }); - check('the moves prove against their base (undo rebuilds engine.ts and every scoped module byte for byte)', - v.failures.length === 0 && v.moved.join() === 'ScopedContext#handsSelf,ScopedContext#[SEED_KEY]', [...v.failures, v.moved.join()].join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const ctxMod = out.modules.get('engine-scoped-context.ts') ?? ''; - check('the symbol-keyed stub keeps its key and docblock, drops `async`, and calls the camelCase facet member', - out.host.includes(` /** A symbol-keyed method: its docblock stays on the class. */\n [SEED_KEY](): Promise {\n // ${SCOPED_MARK} The body moved to \`engine-scoped-context.ts\` (see \`ScopedContextHost\`).\n return ScopedContextFacet.seedKey.call(scopedContextHost.of(this));\n }`), - out.host.slice(out.host.indexOf('[SEED_KEY]('), out.host.indexOf('[SEED_KEY](') + 300)); - check('each bare `this` a body handed on reads `this.facade` in the facet member', - ctxMod.includes(" static handsSelf(this: Pick): ScopedContext {\n void count;\n return this.facade;\n }") && - ctxMod.includes(" static async seedKey(this: Pick): Promise {\n if (!this.ctx.user) return this.facade;"), - ctxMod.slice(ctxMod.indexOf('static handsSelf'), ctxMod.indexOf('static handsSelf') + 200)); - check('the symbol-keyed facet member carries the placeholder naming the method by its key', - ctxMod.includes(' /** The body of `ScopedContext#[SEED_KEY]`; the method\'s docblock there is its contract. */\n static async seedKey(')); - check('the host interface gains the identity port, typed as the class, under its own docblock', - ctxMod.includes(`${SCOPED_FACADE_DOC}\n readonly facade: ScopedContext;`)); - check('the install block fills the identity port with the instance itself, in name order', - out.host.includes(' get engine() { return instance.engine; },\n facade: instance,\n get flag() {'), out.host.slice(out.host.indexOf('scopedContextHost.install'))); - check('the header lists the moved names among the others, in class order', - ctxMod.includes(" * methods `readFlag`, `object`, `sudo`, `handsSelf`, `[SEED_KEY]` moved out of\n"), - ctxMod.slice(0, 600)); - check('the imports only moved bodies read leave engine.ts, land in the module, and the proof names them', - out.pruned.join() === 'count,onlySeedReads' && v.pruned.join() === 'count,onlySeedReads' && ctxMod.includes("import { onlySeedReads } from './seed-only.js';") && - !out.host.includes('./seed-only.js'), `${out.pruned} | ${v.pruned}`); - check('the symbol key itself stays imported in engine.ts (the stub keeps the key)', out.host.includes("import { SEED_KEY, lowerKey } from './keys.js';")); - // A hand's words after the header sentence (from the next line on) are kept as they stand. - const tailed = new Map([...mods, ['engine-scoped-context.ts', (mods.get('engine-scoped-context.ts') ?? '').replace(' (its second pass).\n', ' (its second pass).\n * A hand wrote this line after the sentence, wrapped its own way.\n')]]); - const tOut = generateScopedMembers(tm, input, tailed, planScopedMembers(tm, input, tailed, names, { classes })); - const tv = verifyScopedMembers(tm, input, tOut.host, tailed, new Map([...tailed, ...tOut.modules]), { classes }); - check('a hand-written tail after the header sentence is kept, and the moves still prove', - tv.failures.length === 0 && (tOut.modules.get('engine-scoped-context.ts') ?? '').includes('(its second pass).\n * A hand wrote this line after the sentence, wrapped its own way.\n'), tv.failures.join(' | ')); - const fails = (host, edited) => verifyScopedMembers(tm, input, host, mods, new Map([...head, ...edited]), { classes }).failures.length > 0; - check('one edited character in a moved body fails', fails(out.host, [['engine-scoped-context.ts', ctxMod.replace('user: await onlySeedReads(this.ctx.user)', 'user: await onlySeedReads(this.ctx.user!)')]])); - check('a `this.facade` read back as a bare `this` in the facet fails', fails(out.host, [['engine-scoped-context.ts', ctxMod.replace(' return this.facade;\n', ' return this as any;\n')]])); - check('an install block without the identity port fails', fails(out.host.replace(' facade: instance,\n', ''), [])); - check('a header that does not list a moved name fails', fails(out.host, [['engine-scoped-context.ts', ctxMod.replace('`handsSelf`, ', '')]])); - check('a host interface member no Pick names fails', fails(out.host, [['engine-scoped-context.ts', ctxMod.replace(' readonly facade: ScopedContext;\n', ' readonly facade: ScopedContext;\n readonly user: ScopedContext[\'user\'];\n')]])); - check('an import nothing in the module reads fails', fails(out.host, [['engine-scoped-context.ts', ctxMod.replace("import { onlySeedReads } from './seed-only.js';", "import { onlySeedReads, unread } from './seed-only.js';")]])); - check('a stub calling another facet member fails', fails(out.host.replace('ScopedContextFacet.seedKey.call(', 'ScopedContextFacet.handsSelf.call('), [])); - check('a head that moved nothing fails', verifyScopedMembers(tm, input, input, mods, mods, { classes }).failures.some((f) => f.startsWith('nothing moved'))); - check('a body writing another instance\'s private member refuses (foreign-private)', - /foreign-private/.test(refusalOf(() => planScopedMembers(tm, input, mods, ['ScopedContext#derive'], { classes })))); - check('a key R9 does not take refuses (not-identifier-name), as does an unqualified name and a method already a stub', - /not-identifier-name/.test(refusalOf(() => planScopedMembers(tm, input, mods, ['ScopedContext#[lowerKey]'], { classes }))) && - /spell each as Class#member/.test(refusalOf(() => planScopedMembers(tm, input, mods, ['handsSelf'], { classes }))) && - /already moved/.test(refusalOf(() => planScopedMembers(tm, input, mods, ['ScopedContext#sudo'], { classes })))); - const withFacade = scopedMembersFixtureSource({ facadeField: true }); - const fSplit = generateScoped(tm, withFacade, planScoped(tm, withFacade, { classes })); - check('a class that declares a member named `facade` refuses a body handing the instance on (facade-taken)', - /facade-taken/.test(refusalOf(() => planScopedMembers(tm, fSplit.host, fSplit.modules, ['ScopedContext#handsSelf'], { classes })))); - check('a class that is not a scoped class refuses', /is not a scoped class/.test(refusalOf(() => planScopedMembers(tm, input, mods, ['ObjectQL#run'], { classes })))); - } - - const declared = Object.keys(SELF_TEST_BATTERIES); - if (declared.length < SELF_TEST_BATTERY_FLOOR) { - failed += 1; - console.error(`✗ self-test floor: ${declared.length} batteries declared, below the pinned ${SELF_TEST_BATTERY_FLOOR}`); - } - for (const [name, count] of batterySeen) { - if (!declared.includes(name)) { failed += 1; console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s) but is not declared`); } - } - for (const name of declared) { - const count = batterySeen.get(name) ?? 0; - if (count < SELF_TEST_BATTERIES[name]) { - failed += 1; - console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s), below its pinned ${SELF_TEST_BATTERIES[name]}`); - } - } - if (failed > 0) { - console.error(`\n✗ codemod-split-engine self-test: ${failed} failure(s) (cases and floor).`); - process.exitCode = 1; - selfTestReachedVerdict = true; - return; - } - console.log(`\n✓ codemod-split-engine self-test: ${cases} cases in ${declared.length} batteries pass.`); - selfTestReachedVerdict = true; -} - -if (isEntrypoint(import.meta.url)) { - main(process.argv.slice(2)).then( - (code) => process.exit(code), - (error) => { - if (error instanceof CodemodRefusal) { - console.error(`✗ codemod-split-engine: ${error.message}`); - process.exit(2); - } - console.error(error); - process.exit(2); - }, - ); -} diff --git a/scripts/codemod-split-protocol.mjs b/scripts/codemod-split-protocol.mjs deleted file mode 100644 index a6d3aaa447a..00000000000 --- a/scripts/codemod-split-protocol.mjs +++ /dev/null @@ -1,4164 +0,0 @@ -#!/usr/bin/env node -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * codemod-split-protocol — move whole sections of - * `ObjectStackProtocolImplementation`'s method bodies out of - * `packages/metadata-protocol/src/protocol.ts` into section modules, - * deterministically, and prove the move. - * - * node scripts/codemod-split-protocol.mjs # plan: print the section table, write nothing - * node scripts/codemod-split-protocol.mjs --write # apply the split, then verify it - * node scripts/codemod-split-protocol.mjs --verify --base - * # re-prove a split on disk against protocol.ts at - * node scripts/codemod-split-protocol.mjs --hand-host A,B [--write] - * # run the named hand stubs' bodies on the class's host (#30020) - * node scripts/codemod-split-protocol.mjs --hand-host --verify --base - * # re-prove those moves on disk against the tree at - * node scripts/codemod-split-protocol.mjs --self-test - * node scripts/codemod-split-protocol.mjs --help # this usage, on any tree (split or not) - * - * ## Why a script, and what it repeats - * - * The large-file programme's ruling A (`6583399215`) splits each file by a - * deterministic codemod that applies the file's existing cut pattern to whole - * sections, regenerated on the latest `main` at landing instead of rebased. - * `scripts/codemod-split-sql-driver.mjs` is the pilot; this is the same - * programme for `protocol.ts`, and it applies the cut pattern THIS file's hand - * series already settled: ruling E's host split (`6537939895`, item E1), whose - * tool is `packages/metadata-protocol/scripts/host-split.mjs`. This script does - * not re-implement that pattern; it calls the tool, member by member: - * - * - The method stays on the class with its docblock, modifiers and signature - * byte-for-byte, so the published `.d.ts` keeps its names and positions. - * Its body becomes the E1 stub: one marker comment and - * `return (protocolHost(this), );`. - * - The body moves, as `host-split.mjs`'s `planMove` writes it, into an - * exported function of the same name in a section module: the method's body - * with exactly E1's closed rewrite set applied (`this.` → - * `host.`; a private static `ObjectStackProtocolImplementation.(…)` - * → `host.(…)`), re-indented one level, and nothing else changed. - * - The host (`protocol-host.ts`) gains one `ProtocolHost` entry per member a - * moved body reads, and the class's static block the entry that forwards it, - * through `host-split.mjs`'s `insertHostEntries` (sorted by name). - * - * What the tool leaves to its caller, this script writes: the section module's - * imports (each name a body reads, imported from where `protocol.ts` imports - * it; lever (a) of the pilot ruling `6591753301`: a staying `protocol.ts` - * top-level name a body reads is exported for it by one generated - * `export { … }` list, and `index.ts` re-exports by name, so none reaches the - * package), and `protocol.ts`'s imports of the moved functions. - * - * Private statics (private-static-through-host, ruling `6624174693`, kept by - * `6624345766`): a private static whose body reads nothing of the class (no - * `this`, `super`, `arguments` or class name) moves to its section's module the - * same way, with no host parameter. The class keeps the delegation, so a moved - * instance body still reaches it as `host.`, through the host entry - * that forwards to the class. - * - * ## The facade layer (ruling `6624345766`) - * - * The output above is (a)'s module form. The script then lifts it, text for - * text, into the facade form, and only the facade form is written: - * - * - Each section module's functions become the static methods of ONE - * stateless facet class, `Facet` (`protocol-save.ts` -> - * `ProtocolSaveFacet`). A method still takes the host as its first - * parameter, so its body is (a)'s body re-indented back to the class's own - * depth. A facet holds no state: the fields stay on the class (the facade), - * and a body reaches them through the host. - * - Each stub on the class calls `.(…)`. - * - Docblock ownership: a PRIVATE member's docblock moves, verbatim, onto its - * facet method, and the class keeps one line that links to it. A public or - * protected member's docblock stays on the facade: the published `.d.ts` - * prints it, and the ruling keeps consumers' hover docs unchanged. - * - * The proof of the layer is its inverse: `--verify` unlifts the head (from the - * head texts alone) back to (a)'s form, refusing anything the lift would not - * have written, then proves (a) against the base exactly as below. The plan - * prints the facade reading: every class member with a body, as a delegation - * (to a facet, or in one of the hand series' forms) or a named exception with - * the reason it stayed (the #30019 gate's starting allow-list). - * - * Lever (b) of the same ruling (top-level declarations ahead of the class move - * whole to a leaf) has nothing to move here: ruling E's step E0 already moved - * the preamble out of `protocol.ts`, and what stands ahead of the class is - * imports and two re-export statements. The plan prints that reading. - * - * ## The sections - * - * `protocol.ts` has almost no banners inside the class (five, all inside one - * section), so a section is named by its FIRST member, in `SECTION_ANCHORS`: - * the section table of the hand series' card (#25467), read top to bottom. A - * member belongs to the last anchor at or above it. An anchor the class does - * not declare, or anchors out of class order, stop the script (exit 2): a new - * section is a decision someone writes here, never a name the script makes up. - * `null` keeps the section's methods on the class. - * - * ## What stays, and why (each reason is mechanical) - * - * A method stays whole on the class when moving it would change what it does, - * what the published `.d.ts` says, what a gate or test that reads - * `protocol.ts` BY PATH sees, or when the move could not be undone byte for - * byte. `STAY_REASONS` lists every reason; the plan prints every method that - * stayed and why. `PATH_READER_PINS` (a member whose text a reader extracts - * from `protocol.ts` by path) and `PATH_READER_NEEDLES` (literal text a reader - * requires to find there) are the tables rather than rules. - * - * The pilot's rule that a body no longer than its stub stays is NOT carried: - * under the facade rule of `6624258595` the class keeps delegations only, so - * the length of a body is no reason to keep it. - * - * The pilot's rule on inferred return types is carried: a non-private method - * whose return type is inferred stays (`inferred-return-type`). The published - * `.d.ts` prints that type, and once the body moves the compiler infers it - * through the moved function instead: measured on this file, `getDiscovery`'s - * printed type lost the `@deprecated` docblock on one of its keys (the bar - * on the built `.d.ts` refused the split until the rule was back). A private - * method's type is not printed (`private name;`), so it moves. - * - * ## The proof (`--write` runs it on its own output; `--verify` re-runs it) - * - * 1. Byte-identity: undoing the split rebuilds the base `protocol.ts` AND the - * base `protocol-host.ts` byte-for-byte. Undoing is, from the head texts - * alone: put each moved function's body back on its stub with E1's - * rewrites reversed (`host.` → `this.`, `host.` → - * `ObjectStackProtocolImplementation.`) and its re-indentation - * reversed; drop the generated import and export statements; and drop the - * host entries whose names the base host does not carry (the one fact read - * off the base: which entry names existed). Every byte of the result comes - * from the head. A method moves only when that inverse is exact for its own - * body (`indent-irreversible` otherwise), so the proof can pass at all. - * 2. The hand series' own check, per moved member: `host-split.mjs`'s - * `checkMove` (AST identity modulo exactly the closed set, the stub, the - * signature, the `Pick`, and the body's text). Two independent proofs of - * one move. - * 3. The declaration-file bar (ruling `6348891160`, judged by ruling - * `6441032442` B's second normalisation) is a report reading on two built - * dists, never a `scripts/` file (that ruling's item 3); the PR reports it. - * - * ## Determinism - * - * The input is the text of `protocol.ts` and `protocol-host.ts`. Each is - * parsed in memory (no file system, no lib, no build output, no clock), every - * collection is emitted in source order or sorted, and the output is a pure - * function of the input: two runs on one input write byte-identical trees - * (the plan prints the output tree's sha256). - * - * Exit codes: 0 done · 1 a proof failed (stop: the generated split is never - * hand-edited to pass) · 2 the script could not run (unknown anchor, missing - * prerequisite, bad arguments) · 3 an input does not parse (`ts-parse.mjs`'s - * refusal, which names the parse errors). - */ - -import { createHash } from 'node:crypto'; -import { execFileSync } from 'node:child_process'; -import { existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -import { isEntrypoint } from './invoked-as.mjs'; -import { createProgramChecked, parseSourceFile } from './ts-parse.mjs'; - -const ROOT = join(fileURLToPath(new URL('.', import.meta.url)), '..'); -const PKG_REL = 'packages/metadata-protocol'; -const SRC_REL = `${PKG_REL}/src`; -const SRC_DIR = join(ROOT, SRC_REL); -const HOST_BASENAME = 'protocol.ts'; -const HOST_PATH = join(SRC_DIR, HOST_BASENAME); -const HOST_MODULE_BASENAME = 'protocol-host.ts'; -const HOST_MODULE_PATH = join(SRC_DIR, HOST_MODULE_BASENAME); -const HOST_SPLIT_PATH = join(ROOT, PKG_REL, 'scripts', 'host-split.mjs'); -const CLASS_NAME = 'ObjectStackProtocolImplementation'; -const CARD = '#29985'; - -/** The marker every generated file, import and stub carries; `--verify` keys on it. */ -const MARK = `[${CARD} codemod]`; - -/** - * The sections of `ObjectStackProtocolImplementation`, top to bottom, each - * named by its first member (the #25467 section table), mapped to the module - * its movable bodies go to. `null` keeps the section on the class. No module - * shares a file with a hand-written one: the script refuses to write over a - * file it did not generate. - */ -const SECTION_ANCHORS = Object.freeze([ - ['engine', 'Class head: fields, stored-row conversion, resolvers, registration hooks, authoring gates, mutation pub/sub, overlay index', 'protocol-class-head.ts'], - ['getProjectId', 'Discovery, types, diagnostics, packaged bases, credential carry-forward', 'protocol-discovery-and-bases.ts'], - ['readItemFromMetadataService', 'Metadata reads', 'protocol-metadata-reads.ts'], - ['assertObjectRegistered', 'Query validation', 'protocol-query-guards.ts'], - ['findData', 'Data CRUD', 'protocol-data-crud.ts'], - ['searchAll', 'Global search and the metadata cache', 'protocol-search-and-cache.ts'], - ['batchData', 'Batch and *Many data', 'protocol-batch-and-many.ts'], - ['OVERLAY_ALLOWED_TYPES', 'Write gates: overlay, code-only, organization, sealed and packaged-base refusals, locks, version tokens, conflict audit', 'protocol-write-gates.ts'], - ['applyObjectRegistryMutation', 'Registry hydration, view expansion, write-through, object storage', 'protocol-registry-hydration.ts'], - ['refuseUngrammaticalMetaItemName', 'Save refusals, saveMetaItem, saveConflict, migrateStoredMetadata', 'protocol-save.ts'], - ['historyMetaItem', 'History, publish, drafts, publish backfill', 'protocol-history-and-publish.ts'], - ['revertStoredPackage', 'Package revert, duplicate, import, orphans, commits, revertCommit, rollback', 'protocol-package-commits.ts'], - ['diffMetaItem', 'Diff, deleteMetaItem, loadMetaFromDb, load reports, findReferencesToMeta', 'protocol-diff-delete-load.ts'], - ['installPackage', 'Package install and update', 'protocol-package-install-update.ts'], -]); - -/** - * Members whose text a reader takes out of `protocol.ts` BY PATH. Moving one - * would leave that reader reading a stub, or nothing. Each row names the - * reader. A row naming no member of the class stops the script (exit 2), so the - * table cannot rot into names nobody reads. - */ -const PATH_READER_PINS = Object.freeze({ -}); - -/** - * Literal text a reader requires to find in `protocol.ts` BY PATH. A method - * whose text carries one stays, so the reader still finds it where it looks. - * Each row names the reader. A needle the file no longer carries stops the - * script (exit 2). - */ -const PATH_READER_NEEDLES = Object.freeze({ -}); - -/** Every reason a method stays, with the one-line why the plan prints. */ -const STAY_REASONS = Object.freeze({ - 'section-kept': 'its section maps to no module', - 'already-moved': 'its body is already a hand-series stub', - 'overloaded': 'an overloaded method', - 'decorated': 'a decorated method', - 'generator': 'a generator', - 'closed-set': 'its body does something outside E1\'s closed rewrite set (host-split.mjs refuses it)', - 'constructor-rewrite': 'it reads `this.constructor.` (that rewrite and the private-static one both print `host.`, so undoing it would be ambiguous)', - 'parameter-shape': 'a destructured or `this` parameter (the stub forwards parameters by name)', - 'inferred-return-type': 'a non-private method with an inferred return type (the published `.d.ts` prints the type, which the move would re-infer through the moved function)', - 'parameter-shadows': 'a parameter is named `host`, `protocolHost` or the method itself (the stub or the moved function would read it)', - 'path-reader': 'a reader takes its text out of protocol.ts by path (PATH_READER_PINS / PATH_READER_NEEDLES)', - 'non-public-static': 'it reads a protected static of the class through its name (unreachable from a module function)', - 'module-write': 'it assigns a module-scope binding of protocol.ts (an import is read-only)', - 'name-taken': 'its name is already a module-scope binding of protocol.ts, or a free name protocol.ts reads', - 'name-collision': 'its name collides with a name its module imports or reads', - 'host-entry-conflict': 'it needs a host entry that differs from the one protocol-host.ts already carries for that member', - 'host-entry-predicate': 'it reaches a type-predicate method through a host entry not yet written (the forwarding closure would drop the predicate)', - 'indent-irreversible': 'its body\'s re-indentation cannot be undone byte for byte (a whitespace-only or under-indented line)', - 'no-host-read': 'its body reads no member of the class, so the moved function would never read its `host` parameter (`noUnusedParameters`)', - 'static-reads-class': 'a private static whose body reads the class itself (`this`, `super`, `arguments` or the class name), which a module function cannot reach', - 'static-shape': 'a static that is public or protected, overloaded, decorated or a generator (only a private static\'s body moves)', -}); - -// ── Loading the tools ──────────────────────────────────────────────────────── - -let tools = null; - -/** - * `host-split.mjs` and the TypeScript instance it uses. A missing install is - * exit 2 with the remedy, never a stack trace. - */ -async function loadTools() { - if (tools) return tools; - try { - const hs = await import(pathToFileURL(HOST_SPLIT_PATH).href); - const tsModule = await import(pathToFileURL(join(ROOT, PKG_REL, 'node_modules', 'typescript', 'lib', 'typescript.js')).href); - tools = { hs, ts: tsModule.default ?? tsModule }; - return tools; - } catch (error) { - console.error( - `✗ codemod-split-protocol: PREREQUISITE NOT MET — ${HOST_SPLIT_PATH} or its \`typescript\` does not load ` + - `(${error && error.code ? error.code : 'error'}). Run \`pnpm install\` in this worktree.`, - ); - process.exit(2); - } -} - -/** A reason the script cannot run at all (exit 2) — never a verdict on the split. */ -class CodemodRefusal extends Error {} - -function refuse(message) { - throw new CodemodRefusal(message); -} - -/** - * One in-memory program over one file: no lib, no module resolution, no file - * system. The text goes through `ts-parse.mjs`'s checked parse first, which - * refuses a source with parse errors (its exit 3). The checker resolves every - * identifier to its declaration in this file, an import specifier included. - */ -function program(ts, fileName, text) { - const sf = parseSourceFile(fileName, text); - const host = { - getSourceFile: (name) => (name === fileName ? sf : undefined), - writeFile() {}, - getDefaultLibFileName: () => '/lib.d.ts', - useCaseSensitiveFileNames: () => true, - getCanonicalFileName: (f) => f, - getCurrentDirectory: () => '/', - getNewLine: () => '\n', - fileExists: (name) => name === fileName, - readFile: () => undefined, - }; - const prog = createProgramChecked([fileName], { noLib: true, noResolve: true, target: ts.ScriptTarget.ES2022, strict: true }, host); - return { sf, checker: prog.getTypeChecker() }; -} - -// ── Analysis ───────────────────────────────────────────────────────────────── - -const hasModifier = (ts, node, kind) => Boolean(node.modifiers?.some((m) => m.kind === kind)); - -/** The names protocol.ts binds at module scope, which of them it exports, and its import order. */ -function moduleScope(ts, sf) { - const bindings = new Map(); // name -> { kind: 'import' | 'local', specifier?, form?, imported?, typeOnly?, typeDecl? } - const exported = new Set(); - const importOrder = new Map(); - for (const st of sf.statements) { - if (ts.isImportDeclaration(st)) { - const specifier = st.moduleSpecifier.text; - if (!importOrder.has(specifier)) importOrder.set(specifier, importOrder.size); - const clause = st.importClause; - if (!clause) continue; - const declTypeOnly = Boolean(clause.isTypeOnly); - if (clause.name) bindings.set(clause.name.text, { kind: 'import', specifier, form: 'default', typeOnly: declTypeOnly }); - const nb = clause.namedBindings; - if (nb && ts.isNamespaceImport(nb)) bindings.set(nb.name.text, { kind: 'import', specifier, form: 'namespace', typeOnly: declTypeOnly }); - if (nb && ts.isNamedImports(nb)) { - for (const spec of nb.elements) { - bindings.set(spec.name.text, { - kind: 'import', specifier, form: 'named', imported: (spec.propertyName ?? spec.name).text, - typeOnly: declTypeOnly || Boolean(spec.isTypeOnly), - }); - } - } - continue; - } - if (ts.isExportDeclaration(st)) { - if (!st.moduleSpecifier && st.exportClause && ts.isNamedExports(st.exportClause)) { - for (const spec of st.exportClause.elements) exported.add((spec.propertyName ?? spec.name).text); - } - continue; - } - const isExported = hasModifier(ts, st, ts.SyntaxKind.ExportKeyword); - const names = []; - if (ts.isVariableStatement(st)) { - for (const d of st.declarationList.declarations) collectBindingNames(ts, d.name, names); - } else if (st.name && ts.isIdentifier(st.name)) { - names.push(st.name.text); - } - const typeDecl = ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st); - for (const name of names) { - bindings.set(name, { kind: 'local', typeDecl }); - if (isExported) exported.add(name); - } - } - return { bindings, exported, importOrder }; -} - -function collectBindingNames(ts, name, out) { - if (ts.isIdentifier(name)) { out.push(name.text); return; } - for (const el of name.elements) if (!ts.isOmittedExpression(el)) collectBindingNames(ts, el.name, out); -} - -/** Is `node` inside a type node, below `stop`? */ -function inTypePosition(ts, node, stop) { - for (let n = node.parent; n && n !== stop; n = n.parent) if (ts.isTypeNode(n)) return true; - return false; -} - -/** Is `node` inside a JSDoc comment? */ -function inJsDoc(ts, node) { - for (let n = node; n; n = n.parent) if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode) return true; - return false; -} - -function isModuleScopeDecl(ts, decl) { - if (ts.isVariableDeclaration(decl)) { - const statement = decl.parent && decl.parent.parent; - return Boolean(statement && ts.isVariableStatement(statement) && ts.isSourceFile(statement.parent)); - } - if (ts.isBindingElement(decl)) { - let n = decl; - while (n && !ts.isVariableDeclaration(n)) n = n.parent; - return Boolean(n && isModuleScopeDecl(ts, n)); - } - return Boolean(decl.parent && ts.isSourceFile(decl.parent)) && - (ts.isFunctionDeclaration(decl) || ts.isClassDeclaration(decl) || ts.isInterfaceDeclaration(decl) || - ts.isTypeAliasDeclaration(decl) || ts.isEnumDeclaration(decl) || ts.isModuleDeclaration(decl)); -} - -/** Is this identifier a property NAME (`x.name`, `{ name: v }`, a member name), not a reference? */ -function isPropertyNameIdentifier(ts, node) { - const p = node.parent; - if (!p) return false; - if (ts.isPropertyAccessExpression(p) && p.name === node) return true; - if (ts.isQualifiedName(p) && p.right === node) return true; - if ((ts.isPropertyAssignment(p) || ts.isPropertyDeclaration(p) || ts.isMethodDeclaration(p) || ts.isPropertySignature(p) - || ts.isGetAccessorDeclaration(p) || ts.isSetAccessorDeclaration(p) || ts.isMethodSignature(p) - || ts.isEnumMember(p) || ts.isBindingElement(p)) && p.name === node) return true; - if (ts.isBindingElement(p) && p.propertyName === node) return true; - if (ts.isLabeledStatement(p) || ts.isBreakOrContinueStatement(p)) return true; - return false; -} - -function isWrittenIdentifier(ts, node) { - let target = node; - for (let p = target.parent; p && (ts.isParenthesizedExpression(p) || ts.isArrayLiteralExpression(p) || ts.isObjectLiteralExpression(p) - || ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p) || ts.isSpreadElement(p) || ts.isSpreadAssignment(p)); target = p, p = p.parent); - const parent = target.parent; - if (!parent) return false; - if (ts.isBinaryExpression(parent) && parent.left === target) { - const op = parent.operatorToken.kind; - return op >= ts.SyntaxKind.FirstAssignment && op <= ts.SyntaxKind.LastAssignment; - } - if (target === node && (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent))) { - return parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken; - } - if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === target) return true; - return false; -} - -/** - * Every identifier a method's signature and body read, resolved: the imports - * of protocol.ts it uses (value or type), the module-scope names of - * protocol.ts it uses, the free names (no declaration in the file: globals), - * and the refusals a module function cannot carry. - */ -function readNames(ts, ctx, m, siteStarts = new Set()) { - const imports = new Map(); // local -> { value } - const moduleRefs = new Map(); // protocol.ts top-level name -> { value } - const free = new Set(); - const reasons = []; - const add = (tag) => { if (!reasons.includes(tag)) reasons.push(tag); }; - const regions = [...(m.typeParameters ?? []), ...m.parameters, m.type, m.body].filter(Boolean); - const visit = (node, region) => { - // A rewrite site (a private static's class name) becomes `host` in the - // module: it reads nothing from protocol.ts there. - if (ts.isIdentifier(node) && !inJsDoc(ts, node) && !siteStarts.has(node.getStart(ctx.sf))) { - const parent = node.parent; - let symbol; - if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) symbol = ctx.checker.getShorthandAssignmentValueSymbol(parent); - else if (!isPropertyNameIdentifier(ts, node)) symbol = ctx.checker.getSymbolAtLocation(node); - const typePos = inTypePosition(ts, node, m); - if (!isPropertyNameIdentifier(ts, node) && (!symbol || !symbol.declarations || symbol.declarations.length === 0)) { - if (node.text !== 'undefined' && node.text !== 'arguments') free.add(node.text); - } - for (const decl of symbol?.declarations ?? []) { - if (decl.getSourceFile() !== ctx.sf) continue; - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const local = node.text; - const prev = imports.get(local); - imports.set(local, { value: Boolean(prev && prev.value) || !typePos }); - continue; - } - if (!isModuleScopeDecl(ts, decl)) continue; - const declName = decl.name && ts.isIdentifier(decl.name) ? decl.name.text : node.text; - if (ts.isClassDeclaration(decl) && declName === CLASS_NAME && !typePos) { - const access = node.parent; - if (ts.isPropertyAccessExpression(access) && access.expression === node) { - const st = ctx.table.statics.get(access.name.text); - if (st && !st.private && ctx.staticScope.get(access.name.text) === 'protected') add(`non-public-static: ${access.name.text}`); - } - } - if (!typePos && isWrittenIdentifier(ts, node)) add(`module-write: ${declName}`); - const prev = moduleRefs.get(declName); - moduleRefs.set(declName, { value: Boolean(prev && prev.value) || !typePos }); - } - } - ts.forEachChild(node, (c) => visit(c, region)); - }; - for (const region of regions) visit(region, region); - return { imports, moduleRefs, free, reasons }; -} - -/** `[{ line, title }]`-free section lookup: the section each class member falls in. */ -function sectionTable(ts, sf, cls, anchors) { - const starts = []; - for (const [anchor, title, module] of anchors) { - const member = cls.members.find((m) => m.name && (ts.isIdentifier(m.name) || ts.isPrivateIdentifier(m.name)) && m.name.text === anchor); - if (!member) refuse(`SECTION_ANCHORS names \`${anchor}\`, which ${CLASS_NAME} does not declare. Re-read the class and fix the table.`); - starts.push({ anchor, title, module, pos: member.getFullStart() }); - } - for (let i = 1; i < starts.length; i += 1) { - if (starts[i].pos <= starts[i - 1].pos) refuse(`SECTION_ANCHORS is out of class order at \`${starts[i].anchor}\` (it stands above \`${starts[i - 1].anchor}\`)`); - } - const first = cls.members[0]; - if (!first || starts[0].pos !== first.getFullStart()) refuse(`SECTION_ANCHORS must start at the class's first member (\`${first?.name?.getText(sf) ?? '?'}\`)`); - return (member) => { - let hit = null; - for (const s of starts) if (s.pos <= member.getFullStart()) hit = s; - return hit; - }; -} - -/** The line indices (0-based) of `bodyText` that start inside a string or template literal. */ -function literalLineIndices(ts, bodyText) { - const prefix = 'function f() '; - const text = prefix + bodyText; - const sf = parseSourceFile('x.ts', text); - const starts = new Set(); - const visit = (node) => { - if (ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node) || ts.isStringLiteral(node)) { - const start = node.getStart(sf); - const end = node.getEnd(); - for (let i = text.indexOf('\n', start); i !== -1 && i < end - 1; i = text.indexOf('\n', i + 1)) starts.add(i + 1 - prefix.length); - } - ts.forEachChild(node, visit); - }; - visit(sf); - const indices = new Set(); - let at = 0; - bodyText.split('\n').forEach((line, i) => { - if (starts.has(at)) indices.add(i); - at += line.length + 1; - }); - return indices; -} - -/** - * The inverse of E1's move for one body: `host.` back to `this.` (or the - * class name, for a private static), and one level of indentation back on every - * line but the first, except a line that starts inside a literal and an empty - * line. `privateStatics` is the set of private static names of the class. - */ -function undoBody(ts, movedBodyText, privateStatics) { - const prefix = 'function f(host: any) '; - const sf = parseSourceFile('x.ts', prefix + movedBodyText); - const sites = []; - const visit = (node) => { - if (ts.isIdentifier(node) && node.text === 'host' && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node) { - const start = node.getStart(sf) - prefix.length; - if (start >= 0) sites.push({ start, end: node.getEnd() - prefix.length, text: privateStatics.has(node.parent.name.text) ? CLASS_NAME : 'this' }); - } - ts.forEachChild(node, visit); - }; - visit(sf); - let text = movedBodyText; - for (const s of sites.sort((a, b) => b.start - a.start)) text = text.slice(0, s.start) + s.text + text.slice(s.end); - const literal = literalLineIndices(ts, text); - return text.split('\n').map((line, i) => (i === 0 || literal.has(i) || line === '' ? line : ` ${line}`)).join('\n'); -} - -/** - * One level of indentation off every line of a static's body but the first, - * except a line that starts inside a literal and an empty line: the inverse of - * `undoBody`'s re-indentation (a static's body has no host rewrite to undo). - */ -function dedentBody(ts, bodyText) { - const literal = literalLineIndices(ts, bodyText); - return bodyText.split('\n').map((line, i) => (i === 0 || literal.has(i) || !line.startsWith(' ') ? line : line.slice(4))).join('\n'); -} - -/** The one-line docblock a moved private static's function carries in (a)'s module form. */ -const staticOneLiner = (name) => `/** The body of \`${CLASS_NAME}.${name}\` (a private static); the method's docblock there is its contract. */`; - -/** The one-line docblock `host-split.mjs`'s `planMove` writes on a moved instance body. */ -const instanceOneLiner = (name) => `/** The body of \`${CLASS_NAME}#${name}\`; the method's docblock there is its contract. */`; - -/** The body text of the one exported function in `fnText` (what `planMove` writes). */ -function functionBodyOf(ts, fnText) { - const sf = parseSourceFile('x.ts', fnText); - const fn = sf.statements.find((s) => ts.isFunctionDeclaration(s)); - return fn && fn.body ? fnText.slice(fn.body.getStart(sf), fn.body.getEnd()) : null; -} - -/** The keyed groups of a sorted host block (interface or factory), as `insertHostEntries` reads them. */ -function hostBlockKeys(text, openMarker, closeMarker, keyOf) { - const open = text.indexOf(openMarker); - const close = text.indexOf(closeMarker, open); - if (open < 0 || close < 0) return null; - const keys = new Set(); - for (const l of text.slice(open + openMarker.length, close).split('\n')) { - const k = keyOf(l); - if (k !== undefined) keys.add(k); - } - return { open, close, keys }; -} - -const IFACE_OPEN = 'export interface ProtocolHost {'; -const IFACE_CLOSE = '\n}'; -const FACTORY_OPEN = 'installProtocolHost((protocol) => ({'; -const FACTORY_CLOSE = '\n }));'; -const ifaceKey = (l) => /^ {4}(?:readonly )?([A-Za-z_$][\w$]*):/.exec(l)?.[1]; -const factoryKey = (l) => (/^ {12}set /.test(l) ? undefined : /^ {12}(?:get )?([A-Za-z_$][\w$]*)[:(]/.exec(l)?.[1]); - -/** The interface entry lines `protocol-host.ts` carries now, by member name. */ -function hostInterfaceEntries(hostText) { - const block = hostBlockKeys(hostText, IFACE_OPEN, IFACE_CLOSE, ifaceKey); - if (!block) refuse(`${HOST_MODULE_BASENAME} has no \`${IFACE_OPEN}\` block`); - const out = new Map(); - for (const l of hostText.slice(block.open + IFACE_OPEN.length, block.close).split('\n')) { - const k = ifaceKey(l); - if (k !== undefined) out.set(k, l); - } - return out; -} - -// ── The plan ───────────────────────────────────────────────────────────────── - -/** - * Read `text` (a `protocol.ts`) and `hostText` (its `protocol-host.ts`), and - * decide, per instance method, where its body goes. Pure: the same texts give - * the same plan. - */ -function plan(T, text, hostText, { anchors = SECTION_ANCHORS, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES, facade = false } = {}) { - const { ts, hs } = T; - const { sf, checker } = program(ts, HOST_PATH, text); - const cls = hs.classOf(sf, CLASS_NAME); - if (!cls) refuse(`no class ${CLASS_NAME} in ${HOST_BASENAME}`); - const table = hs.memberTable(cls); - const staticScope = new Map(); - for (const m of cls.members) { - if (!hasModifier(ts, m, ts.SyntaxKind.StaticKeyword) || !m.name || !ts.isIdentifier(m.name)) continue; - staticScope.set(m.name.text, hasModifier(ts, m, ts.SyntaxKind.PrivateKeyword) ? 'private' - : hasModifier(ts, m, ts.SyntaxKind.ProtectedKeyword) ? 'protected' : 'public'); - } - const scope = moduleScope(ts, sf); - const ctx = { ts, sf, checker, cls, table, staticScope, scope }; - const sectionOf = sectionTable(ts, sf, cls, anchors); - const memberNames = new Set(cls.members.filter((m) => m.name && ts.isIdentifier(m.name)).map((m) => m.name.text)); - const stalePins = Object.keys(pins).filter((n) => !memberNames.has(n)); - if (stalePins.length > 0) refuse(`PATH_READER_PINS names what ${CLASS_NAME} no longer declares: ${stalePins.join(', ')}`); - const staleNeedles = Object.keys(needles).filter((n) => !text.includes(n)); - if (staleNeedles.length > 0) refuse(`PATH_READER_NEEDLES names text ${HOST_BASENAME} no longer carries: ${staleNeedles.map((n) => JSON.stringify(n)).join(', ')}`); - const existingEntries = hostInterfaceEntries(hostText); - const privateStatics = new Set([...table.statics].filter(([, s]) => s.private).map(([n]) => n)); - // Members whose declared return type is a type predicate (`x is T`, not `asserts`). - const predicateMembers = new Set(); - for (const m of cls.members) { - if (ts.isMethodDeclaration(m) && m.name && ts.isIdentifier(m.name) && m.type && ts.isTypePredicateNode(m.type) && !m.type.assertsModifier) { - predicateMembers.add(m.name.text); - } - } - - // Every free name protocol.ts reads anywhere: a moved function imported - // under one of these names would capture it. - const freeInHost = new Set(); - const scanFree = (node) => { - if (ts.isIdentifier(node) && !inJsDoc(ts, node) && !isPropertyNameIdentifier(ts, node)) { - const s = checker.getSymbolAtLocation(node); - if (!s || !s.declarations || s.declarations.length === 0) freeInHost.add(node.text); - } - ts.forEachChild(node, scanFree); - }; - scanFree(sf); - - const records = []; - for (const m of cls.members) { - if (!ts.isMethodDeclaration(m) || !m.body || hasModifier(ts, m, ts.SyntaxKind.StaticKeyword)) continue; - if (!m.name || !ts.isIdentifier(m.name)) continue; - const name = m.name.text; - const section = sectionOf(m); - const reasons = []; - const add = (tag) => { if (!reasons.includes(tag)) reasons.push(tag); }; - const startLine = sf.getLineAndCharacterOfPosition(m.getStart(sf)).line + 1; - const endLine = sf.getLineAndCharacterOfPosition(m.getEnd()).line + 1; - const bodyLines = sf.getLineAndCharacterOfPosition(m.body.getEnd()).line - sf.getLineAndCharacterOfPosition(m.body.getStart(sf)).line + 1; - const record = { name, node: m, section: section.title, module: section.module, startLine, lineCount: endLine - startLine + 1, bodyLines, reasons }; - records.push(record); - if (!section.module) add('section-kept'); - const stub = hs.stubKindOf(m); - if (stub) { add(`already-moved: ${stub}`); continue; } - if (cls.members.some((o) => o !== m && ts.isMethodDeclaration(o) && !o.body && o.name && ts.isIdentifier(o.name) && o.name.text === name)) add('overloaded'); - if (ts.canHaveDecorators?.(m) && ts.getDecorators?.(m)?.length) add('decorated'); - if (m.asteriskToken) add('generator'); - const isPrivate = (m.modifiers ?? []).some((x) => x.kind === ts.SyntaxKind.PrivateKeyword) || ts.isPrivateIdentifier(m.name); - if (!isPrivate && !m.type) add('inferred-return-type'); - for (const p of m.parameters) { - if (!ts.isIdentifier(p.name) || p.name.text === 'this') add(`parameter-shape: ${p.name.getText(sf)}`); - else if (['host', 'protocolHost', name].includes(p.name.text)) add(`parameter-shadows: ${p.name.text}`); - } - const methodText = m.getText(sf); - for (const needle of Object.keys(needles)) if (methodText.includes(needle)) add(`path-reader: ${JSON.stringify(needle)}`); - if (Object.prototype.hasOwnProperty.call(pins, name)) add(`path-reader: ${name}`); - const sites = hs.rewriteSites(sf, m, table, CLASS_NAME); - for (const r of sites.refusals) add(`closed-set: ${r.reason}`); - if (sites.sites.some((s) => s.kind === 'constructor')) add('constructor-rewrite'); - const names = readNames(ts, ctx, m, new Set(sites.sites.filter((x) => x.kind === 'privateStatic').map((x) => x.start))); - for (const r of names.reasons) add(r); - if (!facade && (scope.bindings.has(name) || freeInHost.has(name))) add('name-taken'); - Object.assign(record, { imports: names.imports, moduleRefs: names.moduleRefs, free: names.free }); - if (reasons.length > 0) continue; - - const moved = hs.planMove(text, name, section.module, CLASS_NAME); - if (moved.refusals.length > 0) { for (const r of moved.refusals) add(`closed-set: ${r.reason}`); continue; } - record.fnText = moved.fnText; - record.stub = moved.stub; - record.hostEntries = moved.hostEntries; - record.hostNames = moved.names; - for (const [member, entry] of moved.hostEntries) { - const have = existingEntries.get(member); - if (have !== undefined && have !== entry.iface) add(`host-entry-conflict: ${member}`); - if (have === undefined && predicateMembers.has(member)) { - // The facade form writes the predicate's entry typed as the predicate (#30147). - if (facade) moved.hostEntries.set(member, predicateEntry(ts, sf, cls, table, member)); - else add(`host-entry-predicate: ${member}`); - } - } - if (moved.sites.length === 0) add('no-host-read'); - const movedBody = functionBodyOf(ts, moved.fnText); - const baseBody = text.slice(m.body.getStart(sf), m.body.getEnd()); - if (movedBody === null || undoBody(ts, movedBody, privateStatics) !== baseBody) add('indent-irreversible'); - record.stubLines = stubBody(name, section.module, m).split('\n').length; - } - - // Private statics (private-static-through-host, ruling 6624174693, kept by - // 6624345766): a private static whose body reads nothing of the class moves - // to its section's module like an instance body, with no host parameter; the - // class keeps the delegation, so the moved instance bodies keep reaching it - // through the host entry that forwards to the class. - for (const m of cls.members) { - if (!ts.isMethodDeclaration(m) || !m.body || !hasModifier(ts, m, ts.SyntaxKind.StaticKeyword)) continue; - if (!m.name || !ts.isIdentifier(m.name)) continue; - const name = m.name.text; - const section = sectionOf(m); - const reasons = []; - const add = (tag) => { if (!reasons.includes(tag)) reasons.push(tag); }; - const startLine = sf.getLineAndCharacterOfPosition(m.getStart(sf)).line + 1; - const endLine = sf.getLineAndCharacterOfPosition(m.getEnd()).line + 1; - const bodyLines = sf.getLineAndCharacterOfPosition(m.body.getEnd()).line - sf.getLineAndCharacterOfPosition(m.body.getStart(sf)).line + 1; - const record = { name, node: m, isStatic: true, section: section.title, module: section.module, startLine, lineCount: endLine - startLine + 1, bodyLines, reasons }; - records.push(record); - if (!section.module) add('section-kept'); - const isPrivate = hasModifier(ts, m, ts.SyntaxKind.PrivateKeyword); - const overloaded = cls.members.some((o) => o !== m && ts.isMethodDeclaration(o) && !o.body && o.name && ts.isIdentifier(o.name) && o.name.text === name); - if (!isPrivate || overloaded || m.asteriskToken || (ts.canHaveDecorators?.(m) && ts.getDecorators?.(m)?.length)) { add('static-shape'); continue; } - if (hs.stubKindOf(m)) { add('already-moved: static'); continue; } - for (const p of m.parameters) { - if (!ts.isIdentifier(p.name) || p.name.text === 'this') add(`parameter-shape: ${p.name.getText(sf)}`); - else if (['host', 'protocolHost', name].includes(p.name.text)) add(`parameter-shadows: ${p.name.text}`); - } - const classReads = new Set(); - const scanClass = (node) => { - if (node.kind === ts.SyntaxKind.ThisKeyword) classReads.add('this'); - else if (node.kind === ts.SyntaxKind.SuperKeyword) classReads.add('super'); - else if (ts.isIdentifier(node) && !inJsDoc(ts, node) && ['arguments', CLASS_NAME, 'host', 'protocolHost'].includes(node.text) - && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)) classReads.add(node.text); - ts.forEachChild(node, scanClass); - }; - for (const p of m.parameters) scanClass(p); - if (m.type) scanClass(m.type); - if (m.typeParameters) for (const tp of m.typeParameters) scanClass(tp); - scanClass(m.body); - for (const c of [...classReads].sort()) add(`static-reads-class: ${c}`); - const methodText = m.getText(sf); - for (const needle of Object.keys(needles)) if (methodText.includes(needle)) add(`path-reader: ${JSON.stringify(needle)}`); - if (Object.prototype.hasOwnProperty.call(pins, name)) add(`path-reader: ${name}`); - const names = readNames(ts, ctx, m, new Set()); - for (const r of names.reasons) add(r); - if (!facade && (scope.bindings.has(name) || freeInHost.has(name))) add('name-taken'); - Object.assign(record, { imports: names.imports, moduleRefs: names.moduleRefs, free: names.free }); - if (reasons.length > 0) continue; - const baseBody = text.slice(m.body.getStart(sf), m.body.getEnd()); - const movedBody = dedentBody(ts, baseBody); - if (undoBody(ts, movedBody, privateStatics) !== baseBody) { add('indent-irreversible'); continue; } - const paramsText = m.parameters.length ? text.slice(m.parameters[0].getStart(sf), m.parameters.end).trim() : ''; - const typeParams = m.typeParameters ? `<${text.slice(m.typeParameters.pos, m.typeParameters.end).trim()}>` : ''; - const async = hasModifier(ts, m, ts.SyntaxKind.AsyncKeyword); - record.fnText = `${staticOneLiner(name)}\n` - + `export ${async ? 'async ' : ''}function ${name}${typeParams}(${paramsText})${m.type ? `: ${m.type.getText(sf)}` : ''} ${movedBody}\n`; - record.stub = { start: m.body.getStart(sf), end: m.body.getEnd() }; - record.hostEntries = new Map(); - record.hostNames = []; - record.stubLines = stubBody(name, section.module, m, true).split('\n').length; - } - - // Two moved bodies that need different entries for one member (a field one - // reads and one writes) make every body that needs the writable one stay - // only when protocol-host.ts already carries the readonly one — handled per - // record above; between movers, the writable entry is the one written. - // The facade form (`facade`, the members pass) binds no moved name at module - // scope (a member is `.`), so neither name rule applies to it. - for (let changed = !facade; changed;) { - changed = false; - const byModule = groupMovers(records); - // protocol.ts imports every mover by its name: two movers of one name (an - // instance method and a static) would import one binding twice. - const seen = new Set(); - for (const [, movers] of byModule) { - for (const r of movers) { - if (seen.has(r.name)) { r.reasons.push('name-collision'); changed = true; } - seen.add(r.name); - } - } - if (changed) continue; - for (const [, movers] of byModule) { - const taken = new Set(['ProtocolHost', 'Pick', 'host', CLASS_NAME]); - for (const r of movers) { - for (const local of r.imports.keys()) taken.add(local); - for (const local of r.moduleRefs.keys()) taken.add(local); - for (const local of r.free) taken.add(local); - } - for (const r of movers) if (taken.has(r.name)) { r.reasons.push('name-collision'); changed = true; } - } - } - const modules = groupMovers(records); - - const hostExportsForSections = new Map(); - for (const movers of modules.values()) { - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - if (n === CLASS_NAME || scope.exported.has(n)) continue; - const prev = hostExportsForSections.get(n); - hostExportsForSections.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - } - const before = []; - for (const st of sf.statements) { - if (st === cls) break; - if (!ts.isImportDeclaration(st)) before.push(ts.SyntaxKind[st.kind]); - } - return { sf, cls, ctx, records, modules, hostExportsForSections, before, privateStatics }; -} - -/** Movers grouped by module, modules in section order. */ -function groupMovers(records) { - const byModule = new Map(); - for (const r of records) { - if (r.reasons.length > 0 || !r.module) continue; - if (!byModule.has(r.module)) byModule.set(r.module, []); - byModule.get(r.module).push(r); - } - return byModule; -} - -// ── Generation ─────────────────────────────────────────────────────────────── - -const byName = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0); - -/** - * One `import` / `export` statement over `names`: on one line when it fits in - * 120 columns, else one name per line, four-space indented (this package's - * style). - */ -function namedStatement(head, names, tail) { - const one = `${head} { ${names.join(', ')} }${tail}`; - if (one.length <= 120) return one; - return [`${head} {`, ...names.map((n) => ` ${n},`), `}${tail}`].join('\n'); -} - -function importPair(specifier, uses) { - const out = []; - const entries = [...uses.entries()].sort(byName); - const values = entries.filter(([, u]) => u.value).map(([n]) => n); - const types = entries.filter(([, u]) => !u.value).map(([n]) => n); - if (values.length > 0) out.push(namedStatement('import', values, ` from '${specifier}';`)); - if (types.length > 0) out.push(namedStatement('import type', types, ` from '${specifier}';`)); - return out; -} - -/** - * The import lines a module needs: protocol.ts's own imports its bodies use, - * in protocol.ts's import order; then `ProtocolHost`; then what stayed in - * protocol.ts (lever (a)), the class included. - */ -function importLines(scope, movers) { - const bySpecifier = new Map(); - const note = (specifier, local, entry) => { - if (!bySpecifier.has(specifier)) bySpecifier.set(specifier, new Map()); - const slot = bySpecifier.get(specifier); - const prev = slot.get(local); - slot.set(local, { ...entry, value: Boolean(prev && prev.value) || entry.value }); - }; - for (const r of movers) { - for (const [local, use] of r.imports) { - const b = scope.bindings.get(local); - if (!b || b.kind !== 'import') refuse(`import binding ${local} not found`); - note(b.specifier, local, { ...b, value: use.value && !b.typeOnly }); - } - } - if (movers.some((r) => !r.isStatic)) note('./protocol-host.js', 'ProtocolHost', { form: 'named', imported: 'ProtocolHost', value: false }); - const order = (s) => (scope.importOrder.has(s) ? scope.importOrder.get(s) : Number.MAX_SAFE_INTEGER); - const out = []; - const specifiers = [...bySpecifier.keys()].sort((a, b) => order(a) - order(b) || (a < b ? -1 : a > b ? 1 : 0)); - for (const specifier of specifiers) { - const entries = [...bySpecifier.get(specifier).entries()].sort(byName); - const named = (value) => entries - .filter(([, e]) => e.form === 'named' && e.value === value) - .map(([local, e]) => (e.imported === local ? local : `${e.imported} as ${local}`)); - const def = entries.find(([, e]) => e.form === 'default'); - const ns = entries.find(([, e]) => e.form === 'namespace'); - const valueNamed = named(true); - const defValue = def && def[1].value ? def[0] : null; - if (defValue && valueNamed.length > 0) out.push(`import ${defValue}, { ${valueNamed.join(', ')} } from '${specifier}';`); - else if (defValue) out.push(`import ${defValue} from '${specifier}';`); - else if (valueNamed.length > 0) out.push(namedStatement('import', valueNamed, ` from '${specifier}';`)); - if (def && !def[1].value) out.push(`import type ${def[0]} from '${specifier}';`); - if (ns) out.push(`import ${ns[1].value ? '' : 'type '}* as ${ns[0]} from '${specifier}';`); - const typeNamed = named(false); - if (typeNamed.length > 0) out.push(namedStatement('import type', typeNamed, ` from '${specifier}';`)); - } - const fromHost = new Map(); - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - const prev = fromHost.get(n); - fromHost.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - out.push(...importPair('./protocol.js', fromHost)); - return out; -} - -/** `words` wrapped into ` * ` comment lines no wider than `width`. */ -function wrapComment(words, width = 80) { - const lines = []; - let line = ' *'; - for (const w of words) { - if (line.length + 1 + w.length > width && line !== ' *') { lines.push(line); line = ' *'; } - line += ` ${w}`; - } - if (line !== ' *') lines.push(line); - return lines; -} - -function moduleText(moduleFile, title, movers, scope) { - const names = movers.map((r, i) => `\`${r.name}\`${i === movers.length - 1 ? '' : ','}`); - const readsHostValues = movers.some((r) => [...r.moduleRefs.values()].some((u) => u.value)); - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push('/**'); - out.push(...wrapComment([MARK, 'The', ...`"${title}"`.split(' '), 'section', 'of', `\`${CLASS_NAME}\`:`, 'the', 'bodies', 'of', - ...names, 'moved', 'out', 'of', '`protocol.ts`', 'whole', 'by', '`scripts/codemod-split-protocol.mjs`.'])); - out.push(' *'); - out.push(' * A MOVE, not a redesign. Each function below is the body of the class method'); - out.push(' * of the same name as `packages/metadata-protocol/scripts/host-split.mjs` moves'); - out.push(' * one (ruling E, item E1): re-indented one level, with `this.` read as'); - out.push(' * `host.` and nothing else changed. Each method stays on the class'); - out.push(' * with its docblock and signature, which the published `.d.ts` prints, and'); - out.push(' * hands its body the host (`protocol-host.ts`); the docblock there is the'); - out.push(' * contract.'); - out.push(' *'); - if (readsHostValues) { - out.push(' * Values that stayed in `protocol.ts` are imported from it (lever (a) of'); - out.push(' * ruling 6591753301); every use is inside a function body, so the import'); - out.push(' * cycle is never read at evaluation time. Nothing re-exports this module,'); - out.push(' * so the published surface does not move.'); - } else { - out.push(' * What a body reads from elsewhere, it imports from where `protocol.ts`'); - out.push(' * imports it. Nothing re-exports this module, so the published surface does'); - out.push(' * not move.'); - } - out.push(' */'); - out.push(''); - out.push(...importLines(scope, movers)); - for (const r of movers) { - out.push(''); - out.push(r.fnText.replace(/\n$/, '')); - } - out.push(''); - return out.join('\n'); -} - -/** - * The E1 stub body, carrying this script's marker. A private static's stub - * hands its body no host: the body reads nothing of the class. - */ -function stubBody(name, moduleFile, m, isStatic = false) { - const args = m.parameters.map((p) => (p.dotDotDotToken ? '...' : '') + p.name.getText()); - return '{\n' - + (isStatic - ? ` // ${MARK} The body moved to \`${moduleFile}\`; it reads nothing of this class.\n` - : ` // ${MARK} The body moved to \`${moduleFile}\`; it reaches this class through \`${HOST_MODULE_BASENAME}\`.\n`) - + ` return ${name}(${[...(isStatic ? [] : ['protocolHost(this)']), ...args].join(', ')});\n` - + ' }'; -} - -/** - * Apply a plan. Returns `{ host, hostModule, modules }`: the new `protocol.ts`, - * the new `protocol-host.ts` and a Map of module basename -> text. Pure. - */ -function generate(T, text, hostText, planned) { - const { hs } = T; - const { sf, ctx, modules, hostExportsForSections } = planned; - const { ts } = ctx; - const edits = []; - const importBlock = []; - const entries = new Map(); - for (const [moduleFile, movers] of modules) { - const title = movers[0].section; - importBlock.push(`\n// ${MARK} ${title}: the methods of the same names below hand the bodies the host (\`${HOST_MODULE_BASENAME}\`).`); - importBlock.push(`\n${namedStatement('import', movers.map((r) => r.name).sort(), ` from './${moduleFile.replace(/\.ts$/, '.js')}';`)}`); - for (const r of movers) { - edits.push({ start: r.stub.start, end: r.stub.end, text: stubBody(r.name, moduleFile, r.node, r.isStatic === true) }); - for (const [member, entry] of r.hostEntries) { - const prev = entries.get(member); - // A writable entry (a getter and a setter) wins over a readonly one. - if (!prev || (entry.factory.includes('\n') && !prev.factory.includes('\n'))) entries.set(member, entry); - } - } - } - if (hostExportsForSections.size > 0) { - const spelled = [...hostExportsForSections.keys()].sort().map((n) => (ctx.scope.bindings.get(n)?.typeDecl ? `type ${n}` : n)); - importBlock.push(`\n// ${MARK} Exported for the section modules above, which import them (lever (a)); \`index.ts\` re-exports by name, so none reaches the package.`); - importBlock.push(`\n${namedStatement('export', spelled, ';')}`); - } - const imports = sf.statements.filter((s) => ts.isImportDeclaration(s)); - const lastImport = imports[imports.length - 1]; - if (!lastImport) refuse('protocol.ts has no import declaration to place the generated imports after'); - if (importBlock.length > 0) edits.push({ start: lastImport.getEnd(), end: lastImport.getEnd(), text: importBlock.join('') }); - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let out = text; - let floor = Infinity; - for (const e of edits) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - const sortedEntries = new Map([...entries].sort(byName)); - const inserted = hs.insertHostEntries(hostText, out, sortedEntries); - // The imports only the moved bodies read are dropped (the package compiles - // with `noUnusedLocals`); `verify` recomputes the same prune from the head. - const pruned = pruneImports(ts, inserted.protocol, usedImportNames(ts, inserted.protocol)); - const moduleTexts = new Map(); - for (const [moduleFile, movers] of modules) moduleTexts.set(moduleFile, moduleText(moduleFile, movers[0].section, movers, ctx.scope)); - return { host: pruned.text, hostModule: inserted.host, modules: moduleTexts, pruned: pruned.removed }; -} - -// ── The facade layer (ruling 6624345766) ──────────────────────────────────── -// -// (a)'s module form is lifted, text for text, into the facade form: each -// section module's functions become the static methods of one stateless facet -// class over the host (`export class `; a method still takes the host -// as its first parameter, so the body is (a)'s body, re-indented back to the -// class's own depth); each stub on the class calls `.(…)`; and a -// PRIVATE member's docblock moves with its body (docblock ownership), the -// class keeping one line that links to it. A public member's docblock stays on -// the facade: consumers read it in the published `.d.ts`. State stays on the -// facade: a facet holds nothing, and reads the class's fields through the host. -// -// `unlift` is the exact inverse, read off the head alone: `verify` unlifts the -// head to (a)'s form, then proves (a) against the base as before, so the -// facade layer adds a proof of its own (the unlift must parse and match) and -// keeps every proof of (a), `host-split.mjs`'s `checkMove` included. - -/** The facet class a section module declares, named by its file: `protocol-save.ts` -> `ProtocolSaveFacet`. */ -function facetNameOf(moduleFile) { - return `${moduleFile.replace(/\.ts$/, '').split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join('')}Facet`; -} - -/** The one line a private member keeps on the class once its docblock moved to its facet. */ -const docStubOf = (facet, name, moduleFile) => `/** Docblock and body: {@link ${facet}.${name}} in \`${moduleFile}\` ${MARK}. */`; - -/** Is this class member private (a `private` modifier or a `#name`)? */ -const isPrivateMember = (ts, m) => hasModifier(ts, m, ts.SyntaxKind.PrivateKeyword) || Boolean(m.name && ts.isPrivateIdentifier(m.name)); - -/** - * The docblock span `[start, end)` of a class member that docblock ownership - * may move verbatim: its JSDoc blocks, contiguous (only whitespace between - * them), starting at the member's own four-space depth, which is the depth a - * facet's member has too. `null` when there is none, or it is not that shape. - */ -function movableDocSpan(ts, sf, m) { - const docs = m.jsDoc ?? []; - if (docs.length === 0) return null; - const start = docs[0].getStart(sf); - const end = docs[docs.length - 1].getEnd(); - const lineStart = sf.text.lastIndexOf('\n', start - 1) + 1; - if (sf.text.slice(lineStart, start) !== ' ') return null; - for (let i = 1; i < docs.length; i += 1) { - if (sf.text.slice(docs[i - 1].getEnd(), docs[i].getStart(sf)).trim() !== '') return null; - } - return { start, end, text: sf.text.slice(start, end) }; -} - -/** The 0-based line indices of `text` (parsed as `prefix + text + suffix`) that start inside a string or template literal. */ -function literalLinesOf(ts, text, prefix, suffix) { - const whole = prefix + text + suffix; - const sf = parseSourceFile('x.ts', whole); - const starts = new Set(); - const visit = (node) => { - if (ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node) || ts.isStringLiteral(node)) { - for (let i = whole.indexOf('\n', node.getStart(sf)); i !== -1 && i < node.getEnd() - 1; i = whole.indexOf('\n', i + 1)) starts.add(i + 1 - prefix.length); - } - ts.forEachChild(node, visit); - }; - visit(sf); - const out = new Set(); - let at = 0; - text.split('\n').forEach((line, i) => { - if (starts.has(at)) out.add(i); - at += line.length + 1; - }); - return out; -} - -/** (a)'s exported function text (`export [async] function …`) as a facet's static method, at the class's depth. */ -function liftFunction(ts, fnText) { - if (!/^export (async )?function /.test(fnText)) refuse(`not a moved function: ${fnText.slice(0, 60)}`); - const literal = literalLinesOf(ts, fnText, '', ''); - return fnText.split('\n').map((line, i) => { - if (i === 0) return line.replace(/^export (async )?function /, (_, a) => ` static ${a ?? ''}`); - return literal.has(i) || line === '' ? line : ` ${line}`; - }).join('\n'); -} - -/** The inverse of `liftFunction`: a facet's static method text (from `static`) back to (a)'s function, or `null`. */ -function unliftMethod(ts, methodText) { - if (!/^static (async )?/.test(methodText)) return null; - const literal = literalLinesOf(ts, methodText, 'class F {\n ', '\n}'); - const lines = methodText.split('\n'); - const out = []; - for (let i = 0; i < lines.length; i += 1) { - const line = lines[i]; - if (i === 0) out.push(line.replace(/^static (async )?/, (_, a) => `export ${a ?? ''}function `)); - else if (literal.has(i) || line === '') out.push(line); - else if (line.startsWith(' ')) out.push(line.slice(4)); - else return null; - } - return out.join('\n'); -} - -/** A facet module's text: the header, (a)'s imports, and one class whose static methods are (a)'s functions. */ -function facetModuleText(moduleFile, title, movers, scope, ownedDocs) { - const facet = facetNameOf(moduleFile); - const names = movers.map((r, i) => `\`${r.name}\`${i === movers.length - 1 ? '' : ','}`); - const readsHostValues = movers.some((r) => [...r.moduleRefs.values()].some((u) => u.value)); - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push('/**'); - out.push(...wrapComment([MARK, 'The', ...`"${title}"`.split(' '), 'facet', 'of', `\`${CLASS_NAME}\`:`, 'the', 'bodies', 'of', - ...names, 'moved', 'out', 'of', '`protocol.ts`', 'whole', 'by', '`scripts/codemod-split-protocol.mjs`.'])); - out.push(' *'); - out.push(` * A MOVE, not a redesign. \`${facet}\` is a stateless facet over the host`); - out.push(' * (ruling 6624345766): each static method below is the body of the class'); - out.push(' * member of the same name as `packages/metadata-protocol/scripts/host-split.mjs`'); - out.push(' * moves one (ruling E, item E1), with `this.` read as `host.`'); - out.push(' * and nothing else changed. The facet holds no state: the fields stay on the'); - out.push(' * class, and a body reaches them through the host (`protocol-host.ts`).'); - out.push(' *'); - out.push(' * The class keeps every member as a one-line delegation. A public member'); - out.push(' * keeps its docblock there, which the published `.d.ts` prints; a private'); - out.push(' * member\'s docblock moved here with its body (docblock ownership).'); - out.push(' *'); - if (readsHostValues) { - out.push(' * Values that stayed in `protocol.ts` are imported from it (lever (a) of'); - out.push(' * ruling 6591753301); every use is inside a method body, so the import'); - out.push(' * cycle is never read at evaluation time. Nothing re-exports this module,'); - out.push(' * so the published surface does not move.'); - } else { - out.push(' * What a body reads from elsewhere, it imports from where `protocol.ts`'); - out.push(' * imports it. Nothing re-exports this module, so the published surface does'); - out.push(' * not move.'); - } - out.push(' */'); - out.push(''); - out.push(...importLines(scope, movers)); - out.push(''); - out.push(`export class ${facet} {`); - movers.forEach((r, i) => { - if (i > 0) out.push(''); - const nl = r.fnText.indexOf('\n'); - const fn = r.fnText.slice(nl + 1).replace(/\n$/, ''); - const owned = ownedDocs.get(r.name); - out.push(` ${owned ?? r.fnText.slice(0, nl)}`); - out.push(liftFunction(globalTs, fn)); - }); - out.push('}'); - out.push(''); - return out.join('\n'); -} - -let globalTs = null; - -/** - * Lift (a)'s output (`generate`'s) to the facade form. Pure. Returns the same - * shape as `generate`, plus `owned` (module -> member -> docblock moved) and the - * further import bindings the class dropped once docblocks left it. - */ -function lift(T, a, planned) { - const { ts } = T; - globalTs = ts; - const sf = parseSourceFile(HOST_PATH, a.host); - const cls = T.hs.classOf(sf, CLASS_NAME); - const marker = new RegExp(`^\\{\\s*// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(protocol-[a-z0-9-]+\\.ts)\``); - const edits = []; - const owned = new Map(); - for (const m of cls.members) { - if (!ts.isMethodDeclaration(m) || !m.body || !m.name || !ts.isIdentifier(m.name)) continue; - const hit = marker.exec(m.body.getText(sf)); - if (!hit) continue; - const file = hit[1]; - const facet = facetNameOf(file); - const name = m.name.text; - const ret = m.body.statements[m.body.statements.length - 1]; - if (!ret || !ts.isReturnStatement(ret) || !ret.expression || !ts.isCallExpression(ret.expression) || !ts.isIdentifier(ret.expression.expression) || ret.expression.expression.text !== name) { - refuse(`${name}: its stub does not end in \`return ${name}(…)\``); - } - edits.push({ start: ret.expression.expression.getStart(sf), end: ret.expression.expression.getStart(sf), text: `${facet}.` }); - if (!isPrivateMember(ts, m)) continue; - const span = movableDocSpan(ts, sf, m); - if (!span) continue; - if (!owned.has(file)) owned.set(file, new Map()); - owned.get(file).set(name, span.text); - edits.push({ start: span.start, end: span.end, text: docStubOf(facet, name, file) }); - } - // The generated import of each module's functions becomes the import of its facet. - for (const st of sf.statements) { - if (!ts.isImportDeclaration(st)) continue; - const hit = /^\.\/(protocol-[a-z0-9-]+)\.js$/.exec(st.moduleSpecifier.text); - if (!hit || !a.modules.has(`${hit[1]}.ts`)) continue; - const file = `${hit[1]}.ts`; - const lead = sf.text.slice(st.getFullStart(), st.getStart(sf)); - const title = new RegExp(`// ${MARK.replace(/[[\]]/g, '\\$&')} (.*): the methods of the same names below`).exec(lead)?.[1]; - if (!title) refuse(`the generated import of ${file} carries no section comment`); - edits.push({ - start: st.getFullStart(), end: st.getEnd(), - text: `\n// ${MARK} ${title}: the members below delegate to its facet, \`${facetNameOf(file)}\`.\nimport { ${facetNameOf(file)} } from './${hit[1]}.js';`, - }); - } - edits.sort((x, y) => y.start - x.start || y.end - x.end); - let host = a.host; - for (const e of edits) host = host.slice(0, e.start) + e.text + host.slice(e.end); - const pruned = pruneImports(ts, host, usedImportNames(ts, host)); - const modules = new Map(); - for (const [moduleFile, movers] of planned.modules) { - modules.set(moduleFile, facetModuleText(moduleFile, movers[0].section, movers, planned.ctx.scope, owned.get(moduleFile) ?? new Map())); - } - return { host: pruned.text, hostModule: a.hostModule, modules, owned, prunedByLift: pruned.removed }; -} - -/** - * The inverse of `lift`, from the head texts alone: (a)'s `protocol.ts` and - * modules, the docblocks to put back, and the failures met on the way. - */ -function unlift(T, headText, moduleTexts) { - const { ts } = T; - const failures = []; - const modulesA = new Map(); - const facetDocs = new Map(); // file -> name -> { doc, owned } - for (const [file, text] of moduleTexts) { - if (!text.includes(MARK)) continue; - const sf = parseSourceFile(join(SRC_DIR, file), text); - const facet = facetNameOf(file); - const imports = []; - let cls = null; - for (const st of sf.statements) { - if (ts.isImportDeclaration(st)) imports.push(text.slice(st.getStart(sf), st.getEnd())); - else if (ts.isClassDeclaration(st) && st.name?.text === facet && hasModifier(ts, st, ts.SyntaxKind.ExportKeyword) && !cls) cls = st; - else failures.push(`${file}: a top-level statement that is neither an import nor the facet class ${facet}: ${st.getText(sf).slice(0, 60)}`); - } - if (!cls) { failures.push(`${file}: no exported class ${facet}`); continue; } - if (cls.heritageClauses?.length || cls.typeParameters?.length || (ts.getModifiers(cls) ?? []).length !== 1) failures.push(`${file}: ${facet} is not a plain exported class`); - const docs = new Map(); - const fns = []; - for (const m of cls.members) { - const name = m.name && ts.isIdentifier(m.name) ? m.name.text : '?'; - if (!ts.isMethodDeclaration(m) || !m.body || !hasModifier(ts, m, ts.SyntaxKind.StaticKeyword) || name === '?') { - failures.push(`${file}: ${facet} has a member that is not a static method with a body (${name})`); - continue; - } - const span = movableDocSpan(ts, sf, m); - if (!span) { failures.push(`${file}: ${facet}.${name} carries no docblock at the class's depth`); continue; } - const methodText = text.slice(m.getStart(sf), m.getEnd()); - const fnText = unliftMethod(ts, methodText); - if (fnText === null) { failures.push(`${file}: ${facet}.${name} does not unlift (its indentation is not the lift's)`); continue; } - const oneLiner = [instanceOneLiner(name), staticOneLiner(name)].find((l) => l === span.text); - docs.set(name, { doc: span.text, owned: !oneLiner }); - fns.push({ name, fnText, oneLiner }); - } - facetDocs.set(file, docs); - modulesA.set(file, { imports, fns }); - } - - const sf = parseSourceFile(HOST_PATH, headText); - const cls = T.hs.classOf(sf, CLASS_NAME); - const edits = []; - const restoredDocs = []; - const marker = new RegExp(`^\\{\\s*// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(protocol-[a-z0-9-]+\\.ts)\``); - const staticNames = new Set(); - for (const m of cls?.members ?? []) { - if (!ts.isMethodDeclaration(m) || !m.body || !m.name || !ts.isIdentifier(m.name)) continue; - const hit = marker.exec(m.body.getText(sf)); - if (!hit) continue; - const file = hit[1]; - const facet = facetNameOf(file); - const name = m.name.text; - if (hasModifier(ts, m, ts.SyntaxKind.StaticKeyword)) staticNames.add(`${file}:${name}`); - const ret = m.body.statements[m.body.statements.length - 1]; - const callee = ret && ts.isReturnStatement(ret) && ret.expression && ts.isCallExpression(ret.expression) ? ret.expression.expression : null; - if (!callee || !ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression) || callee.expression.text !== facet || callee.name.text !== name) { - failures.push(`${name}: its stub does not call \`${facet}.${name}(…)\``); - continue; - } - edits.push({ start: callee.getStart(sf), end: callee.name.getStart(sf), text: '' }); - const fd = facetDocs.get(file)?.get(name); - const span = movableDocSpan(ts, sf, m); - const carriesStub = Boolean(span && span.text === docStubOf(facet, name, file)); - if (!fd) continue; // `verify` names the stub whose function is missing - if (fd.owned && !carriesStub) failures.push(`${name}: ${facet}.${name} carries a docblock, but the class does not keep the one-line link in its place`); - if (!fd.owned && carriesStub) failures.push(`${name}: the class links to a docblock ${facet}.${name} does not carry`); - if (fd.owned && !isPrivateMember(ts, m)) failures.push(`${name}: a public member's docblock moved off the class (it must stay on the facade)`); - if (fd.owned && carriesStub) { - edits.push({ start: span.start, end: span.end, text: fd.doc }); - restoredDocs.push(fd.doc); - } - } - edits.sort((x, y) => y.start - x.start || y.end - x.end); - let headA = headText; - for (const e of edits) headA = headA.slice(0, e.start) + e.text + headA.slice(e.end); - - const out = new Map(); - for (const [file, { imports, fns }] of modulesA) { - const parts = [`// ${MARK} (unlifted)`, ...imports]; - for (const f of fns) { - const oneLiner = staticNames.has(`${file}:${f.name}`) ? staticOneLiner(f.name) : instanceOneLiner(f.name); - if (f.oneLiner && f.oneLiner !== oneLiner) failures.push(`${file}: ${f.name}'s one-line docblock does not match its member's kind`); - parts.push('', `${oneLiner}\n${f.fnText}`); - } - out.set(file, `${parts.join('\n')}\n`); - } - return { headA, modulesA: out, restoredDocs, failures }; -} - -/** The facade proof: unlift the head, then prove (a) against the base as before. */ -function verifyFacade(T, baseText, headText, baseHostText, headHostText, moduleTexts) { - const u = unlift(T, headText, moduleTexts); - const v = verify(T, baseText, u.headA, baseHostText, headHostText, u.modulesA, { usedFrom: headText, alsoRead: u.restoredDocs.join('\n') }); - return { ...v, failures: [...u.failures, ...v.failures], linesAfter: lineCount(headText), docsMoved: u.restoredDocs.length }; -} - -/** - * The import bindings of a `protocol.ts` that something outside its import - * declarations reads: a reference in code or a type, a local `export { … }`, - * or a JSDoc `{@link X}` / `@see X` name. Those JSDoc names count because the - * compiler's `noUnusedLocals` counts them; other JSDoc text and `//` comments - * do not. - */ -function usedImportNames(ts, text, { docs = true } = {}) { - const { sf, checker } = program(ts, HOST_PATH, text); - const used = new Set(); - const isImportDecl = (d) => d.getSourceFile() === sf && (ts.isImportSpecifier(d) || ts.isImportClause(d) || ts.isNamespaceImport(d)); - const leftmost = (name) => { - let n = name; - while (n && (ts.isQualifiedName(n) || ts.isPropertyAccessExpression(n))) n = ts.isQualifiedName(n) ? n.left : n.expression; - return n && ts.isIdentifier(n) ? n : undefined; - }; - const visitDoc = (node) => { - const linkish = node.kind === ts.SyntaxKind.JSDocLink || node.kind === ts.SyntaxKind.JSDocLinkCode || - node.kind === ts.SyntaxKind.JSDocLinkPlain || node.kind === ts.SyntaxKind.JSDocNameReference; - if (linkish && node.name) { - const id = leftmost(node.name); - const symbol = id && checker.getSymbolAtLocation(id); - if (id && (symbol?.declarations ?? []).some(isImportDecl)) used.add(id.text); - } - if (Array.isArray(node.comment)) node.comment.forEach(visitDoc); - ts.forEachChild(node, visitDoc); - }; - const visit = (node) => { - if (ts.isImportDeclaration(node)) return; - if (docs) for (const doc of node.jsDoc ?? []) visitDoc(doc); - if (ts.isExportDeclaration(node) && node.moduleSpecifier) return; - if (ts.isIdentifier(node) && !inJsDoc(ts, node)) { - const parent = node.parent; - let symbol; - if (ts.isExportSpecifier(parent)) symbol = checker.getExportSpecifierLocalTargetSymbol(parent); - else if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) symbol = checker.getShorthandAssignmentValueSymbol(parent); - else if (!isPropertyNameIdentifier(ts, node)) symbol = checker.getSymbolAtLocation(node); - if ((symbol?.declarations ?? []).some(isImportDecl)) used.add(node.text); - } - ts.forEachChild(node, visit); - }; - visit(sf); - return used; -} - -/** - * Drop every import binding `used` lacks. A declaration left with no binding - * goes whole (its own text and the line break after it; the comments above it - * stay); one left with some keeps them, a one-line `{ … }` on one line, a - * multi-line one as one binding per line. Pure. Returns `{ text, removed }`. - */ -function pruneImports(ts, text, used) { - const sf = parseSourceFile(HOST_PATH, text); - const edits = []; - const removed = []; - for (const st of sf.statements) { - if (!ts.isImportDeclaration(st) || !st.importClause) continue; - const clause = st.importClause; - const nb = clause.namedBindings; - const named = nb && ts.isNamedImports(nb) ? [...nb.elements] : []; - const dropDefault = Boolean(clause.name && !used.has(clause.name.text)); - const dropNs = Boolean(nb && ts.isNamespaceImport(nb) && !used.has(nb.name.text)); - const dropNamed = named.filter((e) => !used.has(e.name.text)); - if (!dropDefault && !dropNs && dropNamed.length === 0) continue; - if (dropDefault) removed.push(clause.name.text); - if (dropNs) removed.push(nb.name.text); - for (const e of dropNamed) removed.push(e.name.text); - const keepDefault = Boolean(clause.name && !dropDefault); - const keepNs = Boolean(nb && ts.isNamespaceImport(nb) && !dropNs); - const keepNamed = named.filter((e) => used.has(e.name.text)); - if (!keepDefault && !keepNs && keepNamed.length === 0) { - const end = text[st.getEnd()] === '\n' ? st.getEnd() + 1 : st.getEnd(); - edits.push({ start: st.getStart(sf), end, text: '' }); - continue; - } - if (nb && ts.isNamedImports(nb) && dropNamed.length > 0) { - if (keepNamed.length === 0) { - edits.push({ start: clause.name.getEnd(), end: nb.getEnd(), text: '' }); - } else { - const one = !nb.getText(sf).includes('\n'); - const parts = keepNamed.map((e) => e.getText(sf)); - edits.push({ start: nb.getStart(sf), end: nb.getEnd(), text: one ? `{ ${parts.join(', ')} }` : `{\n${parts.map((x) => ` ${x},`).join('\n')}\n}` }); - } - } - if (dropNs) edits.push({ start: clause.name.getEnd(), end: nb.getEnd(), text: '' }); - if (dropDefault) edits.push({ start: clause.name.getStart(sf), end: nb.getStart(sf), text: '' }); - } - edits.sort((a, b) => b.start - a.start); - let out = text; - for (const e of edits) out = out.slice(0, e.start) + e.text + out.slice(e.end); - return { text: out, removed: removed.sort() }; -} - -// ── The proof ──────────────────────────────────────────────────────────────── - -const sha256 = (text) => createHash('sha256').update(text).digest('hex'); - -/** Drop the keyed groups whose key `keep` lacks from a host block; every other byte stays. */ -function dropHostGroups(text, openMarker, closeMarker, keyOf, keep, isContinuation) { - const open = text.indexOf(openMarker); - const close = text.indexOf(closeMarker, open); - if (open < 0 || close < 0) return { text, dropped: [], missing: true }; - const block = text.slice(open + openMarker.length, close); - const lines = block.split('\n'); - const outLines = []; - const dropped = []; - let dropping = false; - for (const l of lines) { - const k = keyOf(l); - if (k !== undefined) { - dropping = !keep.has(k); - if (dropping) dropped.push(k); - } else if (!(dropping && isContinuation(l))) { - dropping = false; - } - if (!dropping) outLines.push(l); - } - return { text: text.slice(0, open + openMarker.length) + outLines.join('\n') + text.slice(close), dropped, missing: false }; -} - -/** - * Prove a split against its base, from the texts alone (it shares no state with - * `generate`). Returns `{ failures, moved, checks, linesBefore, linesAfter }`; - * no failure = proved. - */ -function verify(T, baseText, headText, baseHostText, headHostText, moduleTexts, { usedFrom = headText, alsoRead = '' } = {}) { - const { ts, hs } = T; - const failures = []; - const moved = []; - const checks = []; - const baseSf = parseSourceFile(HOST_PATH, baseText); - const headSf = parseSourceFile(HOST_PATH, headText); - const baseCls = hs.classOf(baseSf, CLASS_NAME); - const headCls = hs.classOf(headSf, CLASS_NAME); - if (!baseCls || !headCls) return { failures: [`no class ${CLASS_NAME} at base or head`], moved, checks, linesBefore: 0, linesAfter: 0 }; - const table = hs.memberTable(headCls); - const privateStatics = new Set([...table.statics].filter(([, s]) => s.private).map(([n]) => n)); - - const modules = new Map(); - for (const [file, text] of moduleTexts) { - if (!text.includes(MARK)) continue; - const sf = parseSourceFile(join(SRC_DIR, file), text); - const fns = new Map(); - for (const st of sf.statements) { - if (ts.isFunctionDeclaration(st) && st.name && st.body && hasModifier(ts, st, ts.SyntaxKind.ExportKeyword)) fns.set(st.name.text, st); - else if (!ts.isImportDeclaration(st)) failures.push(`${file}: a top-level statement that is neither an import nor a moved function: ${st.getText(sf).slice(0, 60)}`); - } - modules.set(file, { sf, text, fns, claimed: new Set() }); - } - - const marker = new RegExp(`^\\{\\s*// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(protocol-[a-z0-9-]+\\.ts)\``); - const edits = []; - for (const m of headCls.members) { - if (!ts.isMethodDeclaration(m) || !m.body || !m.name || !ts.isIdentifier(m.name)) continue; - const hit = marker.exec(m.body.getText(headSf)); - if (!hit) continue; - const name = m.name.text; - const mod = modules.get(hit[1]); - const fn = mod && mod.fns.get(name); - if (!fn) { failures.push(`${name}: its stub names ${hit[1]}, which has no exported function ${name}`); continue; } - mod.claimed.add(name); - const isStatic = hasModifier(ts, m, ts.SyntaxKind.StaticKeyword); - const base = isStatic - ? baseCls.members.find((b) => ts.isMethodDeclaration(b) && b.body && hasModifier(ts, b, ts.SyntaxKind.StaticKeyword) && b.name && ts.isIdentifier(b.name) && b.name.text === name) - : hs.methodOf(baseCls, name); - if (!base) { failures.push(`${name}: no ${isStatic ? 'static ' : ''}method of that name with a body at base`); continue; } - if (isStatic) { - // `host-split.mjs`'s check reads instance methods only; a static's - // docblock, modifiers, signature and stub are compared here. - const sig = (sf, x) => sf.text.slice(x.getFullStart(), x.body.getStart(sf)); - if (sig(baseSf, base) !== sig(headSf, m)) failures.push(`${name}: the static's docblock, modifiers or signature changed`); - if (m.body.getText(headSf) !== stubBody(name, hit[1], base, true)) failures.push(`${name}: the static's body is not its stub`); - if (fn.parameters.map((p) => p.getText(mod.sf)).join(', ') !== base.parameters.map((p) => p.getText(baseSf)).join(', ')) failures.push(`${name}: the moved static's parameters are not the method's own`); - } - const movedBody = mod.text.slice(fn.body.getStart(mod.sf), fn.body.getEnd()); - const restored = undoBody(ts, movedBody, privateStatics); - const baseBody = baseText.slice(base.body.getStart(baseSf), base.body.getEnd()); - const identical = restored === baseBody; - if (!identical) failures.push(`${name}: its moved body, rewrites and re-indentation undone, is not the base body`); - moved.push({ name, module: hit[1], isStatic, bodySha: sha256(restored), baseBodySha: sha256(baseBody), lines: baseBody.split('\n').length, identical, restored }); - edits.push({ start: m.body.getStart(headSf), end: m.body.getEnd(), text: restored }); - } - for (const [file, mod] of modules) { - for (const name of mod.fns.keys()) if (!mod.claimed.has(name)) failures.push(`${file}: function ${name} has no stub on the class`); - } - const generatedSpecifier = (spec) => { - const hit = /^\.\/(protocol-[a-z0-9-]+)\.js$/.exec(spec ?? ''); - return Boolean(hit && modules.has(`${hit[1]}.ts`)); - }; - for (const st of headSf.statements) { - const drop = (ts.isImportDeclaration(st) && generatedSpecifier(st.moduleSpecifier.text)) - || (ts.isExportDeclaration(st) && !st.moduleSpecifier && st.getFullText(headSf).includes(MARK)); - if (drop) edits.push({ start: st.getFullStart(), end: st.getEnd(), text: '' }); - } - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let rebuilt = headText; - for (const e of edits) rebuilt = rebuilt.slice(0, e.start) + e.text + rebuilt.slice(e.end); - - // The host entries the base did not carry: the one fact read off the base. - const baseFactory = hostBlockKeys(baseText, FACTORY_OPEN, FACTORY_CLOSE, factoryKey); - const baseIface = hostBlockKeys(baseHostText, IFACE_OPEN, IFACE_CLOSE, ifaceKey); - if (!baseFactory || !baseIface) failures.push('the base carries no host factory or no ProtocolHost interface'); - else { - const factoryContinuation = (l) => /^ {12}set /.test(l); - const f = dropHostGroups(rebuilt, FACTORY_OPEN, FACTORY_CLOSE, factoryKey, baseFactory.keys, factoryContinuation); - if (f.missing) failures.push('protocol.ts at head carries no host factory'); - rebuilt = f.text; - const i = dropHostGroups(headHostText, IFACE_OPEN, IFACE_CLOSE, ifaceKey, baseIface.keys, () => false); - if (i.missing) failures.push(`${HOST_MODULE_BASENAME} at head carries no ProtocolHost interface`); - if (i.text !== baseHostText) failures.push(`undoing the split does not rebuild the base ${HOST_MODULE_BASENAME}: first difference at line ${firstDiff(i.text, baseHostText)}`); - if (JSON.stringify([...f.dropped].sort()) !== JSON.stringify([...i.dropped].sort())) { - failures.push(`the factory and the interface gained different entries: factory ${f.dropped.length}, interface ${i.dropped.length}`); - } - } - // The one edit the undo does not reverse by reading the head: the imports - // only the moved bodies read. It is recomputed from the head (what does the - // head still read?) and applied to the base; the rest must then be equal. - const prune = pruneImports(ts, baseText, usedImportNames(ts, usedFrom)); - const restoredBodies = `${moved.map((r) => r.restored).join('\n')}\n${alsoRead}`; - for (const n of prune.removed) { - if (!new RegExp(`\\b${n.replace(/\$/g, '\\$')}\\b`).test(restoredBodies)) failures.push(`the head dropped the import \`${n}\`, which no moved body reads`); - } - if (rebuilt !== prune.text) { - const at = firstDiff(rebuilt, prune.text); - failures.push(`undoing the split does not rebuild the base protocol.ts (its unread imports pruned): first difference at line ${at}` + - `\n rebuilt: ${JSON.stringify(rebuilt.split('\n')[at - 1] ?? '')}\n base: ${JSON.stringify(prune.text.split('\n')[at - 1] ?? '')}`); - } - - // The hand series' own check, member by member. - for (const r of moved) { - if (r.isStatic) continue; - const c = hs.checkMove({ baseSource: baseText, headSource: headText, moduleSource: modules.get(r.module).text, moduleFile: r.module, member: r.name, className: CLASS_NAME }); - checks.push({ name: r.name, ok: c.ok, counts: c.counts, textIdentical: c.textIdentical }); - for (const p of c.problems) failures.push(`host-split check ${r.name}: ${p}`); - } - if (moved.length === 0) failures.push('no moved method found: a proof over nothing is not a proof'); - return { failures, moved, checks, pruned: prune.removed, linesBefore: lineCount(baseText), linesAfter: lineCount(headText) }; -} - -function firstDiff(a, b) { - const x = a.split('\n'); - const y = b.split('\n'); - let i = 0; - while (i < Math.max(x.length, y.length) && x[i] === y[i]) i += 1; - return i + 1; -} - -/** Lines as `wc -l` counts them: newline characters. */ -function lineCount(text) { - return text.split('\n').length - 1; -} - -// ── Reports ────────────────────────────────────────────────────────────────── - -/** - * The facade reading the #30019 gate starts from: every member of the class - * with a body, as a delegation (to a facet, or the hand series' own form) or a - * named exception with the reason it stayed. - */ -function facadeReport(T, out, planned) { - const { ts, hs } = T; - const sf = parseSourceFile(HOST_PATH, out.host); - const cls = hs.classOf(sf, CLASS_NAME); - const why = new Map(planned.records.map((r) => [`${r.isStatic ? 'static ' : ''}${r.name}`, r.reasons])); - const counts = { facet: 0, hand: new Map(), exceptions: [] }; - for (const m of cls.members) { - const isStatic = hasModifier(ts, m, ts.SyntaxKind.StaticKeyword); - const label = m.name ? `${isStatic ? 'static ' : ''}${m.name.getText(sf)}` : ts.isConstructorDeclaration(m) ? 'constructor' : ts.isClassStaticBlockDeclaration(m) ? 'static block' : ts.SyntaxKind[m.kind]; - const lines = sf.getLineAndCharacterOfPosition(m.getEnd()).line - sf.getLineAndCharacterOfPosition(m.getStart(sf)).line + 1; - if (ts.isMethodDeclaration(m) && m.body) { - if (m.body.getText(sf).includes(MARK)) { counts.facet += 1; continue; } - const kind = hs.stubKindOf(m); - if (kind) { counts.hand.set(kind, (counts.hand.get(kind) ?? 0) + 1); continue; } - counts.exceptions.push(`${label} (${lines} lines): ${(why.get(label) ?? ['?']).map((r) => r.split(':')[0]).filter((r, i, a) => a.indexOf(r) === i).join(', ')}`); - } else if (ts.isConstructorDeclaration(m) || ts.isClassStaticBlockDeclaration(m) || ts.isGetAccessorDeclaration(m) || ts.isSetAccessorDeclaration(m)) { - counts.exceptions.push(`${label} (${lines} lines): ${ts.isClassStaticBlockDeclaration(m) ? 'the host factory (protocol-host.ts reads it)' : 'not a method'}`); - } - } - const facets = [...out.modules.keys()].map((f) => `${facetNameOf(f)} (${f}, ${planned.modules.get(f).length} members, ${[...(out.owned.get(f)?.keys() ?? [])].length} docblocks moved)`); - return [ - `facade: ${lineCount(out.host)} lines; ${counts.facet} member(s) delegate to ${facets.length} facet(s); ` + - `${[...counts.hand.values()].reduce((a, b) => a + b, 0)} hand-series delegation(s) (${[...counts.hand].map(([k, n]) => `${k} ${n}`).join(', ')}); ` + - `${counts.exceptions.length} member(s) with a body stay as named exceptions`, - ...facets.map((f) => ` facet ${f}`), - ...counts.exceptions.map((e) => ` stays ${e}`), - `further import binding(s) the class dropped once docblocks left it: ${out.prunedByLift.length} (${out.prunedByLift.join(', ') || 'none'})`, - ].join('\n'); -} - -function planReport(planned) { - const out = []; - const bySection = new Map(); - for (const r of planned.records) { - if (!bySection.has(r.section)) bySection.set(r.section, []); - bySection.get(r.section).push(r); - } - let movedMethods = 0; - let movedLines = 0; - let stubLinesIn = 0; - const reasonCounts = new Map(); - for (const [section, rs] of bySection) { - const movers = rs.filter((r) => r.reasons.length === 0); - const lines = movers.reduce((n, r) => n + r.bodyLines, 0); - const stubs = movers.reduce((n, r) => n + r.stubLines, 0); - movedMethods += movers.length; - movedLines += lines; - stubLinesIn += stubs; - out.push(`§ ${section} -> ${rs[0].module ?? '(stays)'}: ${movers.length}/${rs.length} methods move (${lines} body lines out, ${stubs} stub lines in)`); - for (const r of rs) { - if (r.reasons.length === 0) out.push(` move ${r.name} (body ${r.bodyLines} -> stub ${r.stubLines})`); - else if (!r.reasons.every((x) => x.startsWith('already-moved') || x === 'section-kept')) out.push(` stay ${r.name} (${r.lineCount}) — ${r.reasons.join('; ')}`); - for (const reason of r.reasons) { - const code = reason.split(':')[0]; - reasonCounts.set(code, (reasonCounts.get(code) ?? 0) + 1); - } - } - } - out.push(''); - out.push(`total: ${movedMethods}/${planned.records.length} instance methods with a body move into ${planned.modules.size} module(s): ` + - `${movedLines} body lines out, ${stubLinesIn} stub lines in`); - out.push(`stay reasons (a method may carry several): ${[...reasonCounts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([c, n]) => `${c} ${n}`).join(', ')}`); - out.push(`lever (a): ${planned.hostExportsForSections.size} staying name(s) exported for the section modules` + - `${planned.hostExportsForSections.size ? ` (${[...planned.hostExportsForSections.keys()].sort().join(', ')})` : ''}`); - out.push(`lever (b): the statements ahead of the class, imports aside: ${planned.before.length} (${planned.before.join(', ') || 'none'}); no top-level declaration to move`); - return out.join('\n'); -} - -function treeHash(files) { - const h = createHash('sha256'); - for (const [name, text] of [...files].sort(([a], [b]) => (a < b ? -1 : 1))) h.update(`${name}\0${sha256(text)}\n`); - return h.digest('hex'); -} - -function printVerify(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - const identical = v.moved.filter((m) => m.identical).length; - const checked = v.checks.filter((c) => c.ok).length; - const rewrites = v.checks.reduce((a, c) => ({ - member: a.member + (c.counts?.member ?? 0), privateStatic: a.privateStatic + (c.counts?.privateStatic ?? 0), constructor: a.constructor + (c.counts?.constructor ?? 0), - }), { member: 0, privateStatic: 0, constructor: 0 }); - const undone = !v.failures.some((f) => f.startsWith('undoing')); - console.log(`byte-identity: ${identical}/${v.moved.length} moved bodies restore to the base body exactly; ` + - `host-split check: ${checked}/${v.checks.length} pass (rewrites: ${rewrites.member} member, ${rewrites.privateStatic} private static, ${rewrites.constructor} constructor); ` + - `protocol.ts ${v.linesBefore} -> ${v.linesAfter} lines; undoing the split ${undone ? 'does' : 'does NOT'} rebuild the base protocol.ts and ${HOST_MODULE_BASENAME} byte-for-byte, ` + - `once the ${v.pruned?.length ?? 0} import binding(s) only moved bodies read are pruned from the base (${(v.pruned ?? []).join(', ') || 'none'})`); -} - -function gitShow(ref, path) { - return execFileSync('git', ['show', `${ref}:${path}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28 }); -} - -function generatedModulesOnDisk() { - const out = new Map(); - for (const [, , section] of SECTION_ANCHORS) { - if (!section) continue; - // A section's tables leaf (#30147) is read with it, so the members pass sees it. - for (const file of [section, tablesModuleOf(section)]) { - const p = join(SRC_DIR, file); - if (existsSync(p)) out.set(file, readFileSync(p, 'utf8')); - } - } - return out; -} - -// ── The members pass: one member of the landed facade (#30518) ────────────── -// -// The first pass runs on an unsplit `protocol.ts` only, and `main` has been -// split since #29985 (48914fdc), so it refuses its own output; and since the -// facet modules have been edited by hand after the split, `--verify` against -// the split's base no longer re-proves. A method a stay rule held when `main` -// was split (a return type since spelled, #30054) is moved by THIS pass -// instead, on the split file: `--members a,b` names the methods, and each goes -// exactly as the first pass would have taken it (`plan`'s stay rules, which -// read the split file as they read an unsplit one; the pass names what it -// moves, never decides it). The stub, the host entries, the facet member and -// the docblock rule are the first pass's (`planMove`, `insertHostEntries`, -// `liftFunction`, docblock ownership), and the member goes into the facet of -// its section, in class order. A method a stay rule holds moves only by one of -// the receiver forms (#30147, below), and only for the reasons those forms -// answer (`RECEIVER_SOLVES`); any other reason refuses. A private static moves -// by those forms, and a private static readonly table to its section's leaf. -// -// What it grows, and the hand edits it accepts (the rule #30572 sets for the -// `engine.ts` pass's `--members`): the receiving module's header gains the -// name in its generated first paragraph, re-wrapped, and every paragraph a -// hand wrote after it is left as it stands; the module's import block gains -// the bindings the moved body reads, each from where `protocol.ts` imports it, -// by element (into a declaration of that specifier and kind, keeping its own -// layout) or as a new declaration, and every import a hand wrote stays where it -// is. Hand-written facet members and top-level declarations stay too. It -// refuses (exit 2) a module whose first paragraph is not the generated one, a -// facet `protocol.ts` does not already import (it never starts a facet), a -// body that reads a top-level name of `protocol.ts` the generated export list -// does not already export (it never widens it), and a binding the module -// already holds under another source or kind. -// -// The proof (`--members --verify --base REF` re-runs it) is the undo against -// the pre-move tree, not the split's base: from the head alone each moved body -// (rewrites and re-indentation undone) and owned docblock goes back onto its -// stub; each receiving module loses the moved members (with the one blank line -// the move wrote), their names in its header, and the import bindings nothing -// in it reads any more, element by element; the factory and the interface lose -// the entries the base host did not carry (the one fact read off the base, as -// the first pass's proof reads it). The result must be the base `protocol.ts` -// (its import bindings only moved bodies read pruned, as the first pass prunes -// them), `protocol-host.ts` and receiving modules byte for byte, every other -// section module unchanged, each facet member its base method's text as the -// first pass would lift it, and `host-split.mjs`'s `checkMove` must pass on the -// unlifted pair: two independent proofs of each move. - -const MEMBERS_CARD = '#30518'; - -const lineStartOf = (text, pos) => text.lastIndexOf('\n', pos - 1) + 1; - -/** Apply non-overlapping `{ start, end, text }` edits; insertions at one offset land in the order given. */ -function applyEdits(text, edits) { - const sorted = edits.map((e, i) => ({ ...e, i })).sort((a, b) => b.start - a.start || b.end - a.end || b.i - a.i); - let out = text; - let floor = Infinity; - for (const e of sorted) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - return out; -} - -/** The lifted stub: the E1 stub, calling the member's facet. */ -const facetStubBody = (name, moduleFile, m) => stubBody(name, moduleFile, m) - .replace(` return ${name}(`, ` return ${facetNameOf(moduleFile)}.${name}(`); - -/** A facet member's text, from its line start: its docblock (owned, or the one-liner) and the lifted body. */ -function facetMemberText(ts, fnText, ownedDoc) { - const nl = fnText.indexOf('\n'); - return ` ${ownedDoc ?? fnText.slice(0, nl)}\n${liftFunction(ts, fnText.slice(nl + 1).replace(/\n$/, ''))}`; -} - -const FILE_LEAD = '// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n'; - -/** The words of a facet module's generated first paragraph (`facetModuleText`). */ -const headerWords = (title, names) => [MARK, 'The', ...`"${title}"`.split(' '), 'facet', 'of', `\`${CLASS_NAME}\`:`, 'the', 'bodies', 'of', - ...names.map((n, i) => `\`${n}\`${i === names.length - 1 ? '' : ','}`), 'moved', 'out', 'of', '`protocol.ts`', 'whole', 'by', '`scripts/codemod-split-protocol.mjs`.']; - -/** - * The names a facet module's generated first paragraph lists, read back, and - * the paragraph's region; null unless that paragraph is exactly the one the - * first pass writes for them. The paragraphs after it are not read. - */ -function headerNamesOf(text, title) { - if (!text.startsWith(FILE_LEAD)) return null; - const start = FILE_LEAD.length; - const end = text.indexOf('\n *\n', start); - if (end < 0) return null; - const prose = text.slice(start, end).split('\n').map((l) => l.replace(/^ \*( |$)/, '')).join(' '); - const i = prose.indexOf(' the bodies of '); - const j = prose.lastIndexOf(' moved out of '); - if (i < 0 || j < i) return null; - const names = [...prose.slice(i, j).matchAll(/`([^`]+)`/g)].map((m) => m[1]); - return wrapComment(headerWords(title, names)).join('\n') === text.slice(start, end) ? { start, end, names } : null; -} - -/** A facet module's facet class and its members, each `{ name, node, start (its docblock's line start), end, staticMethod }`. */ -function facetOf(ts, file, text) { - const sf = parseSourceFile(join(SRC_DIR, file), text); - const facet = facetNameOf(file); - const cls = sf.statements.find((st) => ts.isClassDeclaration(st) && st.name?.text === facet && hasModifier(ts, st, ts.SyntaxKind.ExportKeyword)); - if (!cls) return null; - const members = cls.members.map((m) => { - const docs = m.jsDoc ?? []; - return { - name: m.name && ts.isIdentifier(m.name) ? m.name.text : null, - node: m, - start: lineStartOf(text, docs.length ? docs[0].getStart(sf) : m.getStart(sf)), - end: m.getEnd(), - staticMethod: ts.isMethodDeclaration(m) && hasModifier(ts, m, ts.SyntaxKind.StaticKeyword) && Boolean(m.body), - }; - }); - return { sf, cls, members }; -} - -/** The keys a facet member's host parameter `Pick`s, or null when it is not `host: Pick`. */ -function picksOf(text, member) { - const p = member.node.parameters?.[0]; - if (!p) return null; - const m = /^host: Pick$/s.exec(text.slice(p.getStart(member.node.getSourceFile()), p.getEnd())); - return m ? m[1].split('|').map((q) => q.trim().slice(1, -1)) : null; -} - -/** A module's import declarations, each with its named elements and the names it binds. */ -function importDeclsOf(ts, file, text) { - const sf = parseSourceFile(join(SRC_DIR, file), text); - const decls = []; - const locals = new Set(); - for (const st of sf.statements) { - if (!ts.isImportDeclaration(st)) { - const names = []; - if (ts.isVariableStatement(st)) for (const d of st.declarationList.declarations) collectBindingNames(ts, d.name, names); - else if (st.name && ts.isIdentifier(st.name)) names.push(st.name.text); - for (const n of names) locals.add(n); - continue; - } - const clause = st.importClause; - const nb = clause?.namedBindings; - decls.push({ - st, sf, - specifier: st.moduleSpecifier.text, - start: st.getStart(sf), - end: st.getEnd(), - typeOnly: Boolean(clause?.isTypeOnly), - defaultName: clause?.name?.text ?? null, - nsName: nb && ts.isNamespaceImport(nb) ? nb.name.text : null, - nb: nb && ts.isNamedImports(nb) ? nb : null, - named: nb && ts.isNamedImports(nb) ? nb.elements.map((e) => ({ - local: e.name.text, imported: (e.propertyName ?? e.name).text, typeOnly: Boolean(e.isTypeOnly), start: e.getStart(sf), end: e.getEnd(), text: e.getText(sf), - })) : [], - }); - } - return { decls, locals }; -} - -/** - * Give a facet module the import bindings `wanted` (local -> `{ specifier, - * form, imported, value }`) it does not hold. A binding it already holds from - * that specifier, under that name and of a kind that serves the use, is left - * as it is; any other holder of the name refuses. A named binding goes into - * the first declaration of its specifier and kind, as one more element in that - * declaration's own layout (sorted in when its elements are sorted, last - * otherwise; one line stays one line within 120 columns), else into a new - * declaration: before `ProtocolHost`'s import, or, for `./protocol.js`, after - * the last import. New declarations go in `order` (`protocol.ts`'s import - * order), a specifier's values before its types, as the first pass writes - * them. Pure. - */ -function addModuleImports(ts, file, text, wanted, order = () => 0) { - const { decls, locals } = importDeclsOf(ts, file, text); - const edits = []; - const fresh = new Map(); // `${specifier}\0${value}` -> [local] - for (const [local, w] of [...wanted].sort(byName)) { - const held = decls.flatMap((d) => [ - ...(d.defaultName === local ? [{ form: 'default', imported: 'default', value: !d.typeOnly, d }] : []), - ...(d.nsName === local ? [{ form: 'namespace', imported: '*', value: !d.typeOnly, d }] : []), - ...d.named.filter((e) => e.local === local).map((e) => ({ form: 'named', imported: e.imported, value: !d.typeOnly && !e.typeOnly, d })), - ]); - if (locals.has(local)) refuse(`${file}: ${local}, which the moved body imports, is declared in the module itself`); - if (held.length > 1) refuse(`${file}: binds ${local} more than once`); - if (held.length === 1) { - const h = held[0]; - if (h.d.specifier !== w.specifier || h.form !== w.form || (w.form === 'named' && h.imported !== w.imported)) { - refuse(`${file}: binds ${local} from ${h.d.specifier}, and the moved body reads it from ${w.specifier}`); - } - if (w.value && !h.value) refuse(`${file}: imports ${local} as a type only, and the moved body reads it as a value`); - continue; - } - if (w.form !== 'named') refuse(`${file}: ${local} would be a ${w.form} import, which this pass does not write`); - const key = `${w.specifier}\0${w.value}`; - fresh.set(key, [...(fresh.get(key) ?? []), { local, imported: w.imported }]); - } - const host = decls.find((d) => d.specifier === './protocol-host.js'); - const last = decls.at(-1); - if (!last) refuse(`${file}: has no import declaration`); - const ranked = [...fresh].map(([key, adds]) => { const [specifier, v] = key.split('\0'); return { specifier, value: v === 'true', adds }; }) - .sort((a, b) => order(a.specifier) - order(b.specifier) || Number(b.value) - Number(a.value) || (a.specifier < b.specifier ? -1 : a.specifier > b.specifier ? 1 : 0)); - for (const { specifier, value, adds } of ranked) { - const spell = (a) => (a.imported === a.local ? a.local : `${a.imported} as ${a.local}`); - const d = decls.find((x) => x.specifier === specifier && x.nb && !x.defaultName && x.typeOnly === !value && x.named.every((e) => !e.typeOnly)); - if (d) { - const els = d.named; - const sorted = els.map((e) => e.local).join() === els.map((e) => e.local).sort().join(); - const multi = d.nb.getText(d.sf).includes('\n'); - const lineOf = (e) => text.slice(lineStartOf(text, e.start), text.indexOf('\n', e.end)); - const canonicalMulti = multi && els.every((e) => lineOf(e) === ` ${e.text},`); - const at = (a) => (sorted ? els.findIndex((e) => e.local > a.local) : -1); - if (multi && canonicalMulti) { - for (const a of adds) { - const k = at(a); - const pos = k < 0 ? text.indexOf('\n', els.at(-1).end) + 1 : lineStartOf(text, els[k].start); - edits.push({ start: pos, end: pos, text: ` ${spell(a)},\n` }); - } - continue; - } - if (!multi) { - const grown = d.st.getText(d.sf).length + adds.reduce((n, a) => n + spell(a).length + 2, 0); - if (grown <= 120) { - for (const a of adds) { - const k = at(a); - if (k < 0) edits.push({ start: els.at(-1).end, end: els.at(-1).end, text: `, ${spell(a)}` }); - else edits.push({ start: els[k].start, end: els[k].start, text: `${spell(a)}, ` }); - } - continue; - } - } - } - const statement = namedStatement(value ? 'import' : 'import type', adds.map(spell).sort(), ` from '${specifier}';`); - if (specifier !== './protocol.js' && host) edits.push({ start: host.start, end: host.start, text: `${statement}\n` }); - else edits.push({ start: last.end, end: last.end, text: `\n${statement}` }); - } - return applyEdits(text, edits); -} - -/** - * Drop the import bindings nothing in a module reads, each by itself: a - * declaration left with none goes whole (with its line break), a named - * element goes with its separator (its own line, in a one-per-line list), and - * every other byte stays. The inverse of `addModuleImports` on a module whose - * own imports are all read. Pure. - */ -function pruneModuleImports(ts, file, text, used = usedImportNames(ts, text)) { - const { decls } = importDeclsOf(ts, file, text); - const edits = []; - for (const d of decls) { - const names = [d.defaultName, d.nsName, ...d.named.map((e) => e.local)].filter(Boolean); - const unread = names.filter((n) => !used.has(n)); - if (unread.length === 0) continue; - if (unread.length === names.length) { - edits.push({ start: d.start, end: text[d.end] === '\n' ? d.end + 1 : d.end, text: '' }); - continue; - } - if (d.defaultName && unread.includes(d.defaultName)) refuse(`${file}: a default import binding would be pruned alone`); - const multi = d.nb.getText(d.sf).includes('\n'); - d.named.forEach((e, i) => { - if (used.has(e.local)) return; - const ls = lineStartOf(text, e.start); - const le = text.indexOf('\n', e.end); - if (multi && text.slice(ls, le) === ` ${e.text},`) edits.push({ start: ls, end: le + 1, text: '' }); - else if (i < d.named.length - 1) edits.push({ start: e.start, end: d.named[i + 1].start, text: '' }); - else edits.push({ start: d.named[i - 1].end, end: e.end, text: '' }); - }); - } - return applyEdits(text, edits); -} - -/** Each named method's class position (instance or static), for ordering facet members and header names. */ -function classPositions(ts, cls) { - const pos = new Map(); - for (const m of cls.members) if (ts.isMethodDeclaration(m) && m.name && ts.isIdentifier(m.name) && !pos.has(m.name.text)) pos.set(m.name.text, m.getStart()); - return pos; -} - -// ── The receiver forms (#30147) ───────────────────────────────────────────── -// -// E1 rewrites a body (`this.` → `host.`), so it refuses what -// that rewrite cannot carry: a local already named `host`, a private static -// FIELD read through the class name, a body that reads no member (its `host` -// parameter would go unread), and every private static that reads the class -// itself. The two other facade codemods move those bodies UNEDITED, and this -// pass ports their two mechanisms (#30147), for the members E1 refuses only: -// -// - The `.call(host)` receiver. The body moves byte for byte to a facet -// static method whose `this` parameter is the `Pick` of what it reads -// (`this: Pick`), and the stub runs it on the class's host: -// `return .x.call(protocolHost(this), …)`. A member a body reads goes -// through the host as under E1 (a method as a forwarding closure, so it is -// called, never read as a value; a field as a getter, and a setter when the -// body assigns it); nothing in the body is rewritten. -// - The statics forwarder. `ObjectStackProtocolImplementationStatics`, -// declared ahead of the class and filled by a static block at its end, holds -// a forwarder to each static the moved bodies read (a method called on the -// class at call time, a field read when it is read). A facet module imports -// it AS `ObjectStackProtocolImplementation`, so a body that names the class -// reads `ObjectStackProtocolImplementation.x` unedited; a private static that -// reads `this` (the class) runs on it: `.x.call(, …)`. -// -// A body that reads nothing of the class (no `this`, no class name) moves as a -// plain facet member with no host at all, its stub `return .x(…)`, the -// form the first pass gives a private static of that shape. A static table, a -// private static readonly field whose initializer reads only imports, moves its -// initializer to a leaf (`
-tables.ts`): an initializer runs while the -// class is evaluated, so its module must not import `protocol.ts` or a module -// that does (the facet module would, through the forwarder), and the field -// reads its table back by name. A predicate a moved body reaches through the -// host gets an entry typed as the predicate (`(err: unknown): err is Error => -// …`), so the narrowing survives the hop. -// -// The proof is the undo, as for E1, and the texts are equal by construction: -// every stub, facet member, forwarder text, host entry and leaf is exactly what -// this pass writes for the base member, and undoing them (each body and owned -// docblock back, the forwarder and the leaf gone, the facet modules' imports -// pruned) rebuilds the base tree byte for byte. A body moves unedited, so -// `host-split.mjs`'s `checkMove` (identity modulo E1's rewrites) has nothing to -// judge in these forms; the byte equality is that check's strict case. -// -// What a forwarder changes is named here, because it is the one difference a -// body could tell apart: a static reached through it runs with the class as -// `this` (a moved static of a subclass's call would see the class, not the -// subclass); the class's statics are all private, so no subclass reaches one. -// -// The identity port (#30020 R1, the `engine.ts` codemod's R1 ported to this -// pass, design ruling A 6687865760: the facade stays the sole state owner and -// each host gains a `facade` port). In the `.call(host)` receiver form a bare -// `this` would hand the HOST on where the method handed the instance, so it -// refused. Now each bare `this` an instance body hands on (`f(this)`, -// `(this as any).x`, `return this`) reads `this.facade`, a host entry the -// factory fills with the instance itself (`facade: protocol`), typed as the -// class; it is the one edit the receiver form makes to a body. Its undo is the -// one inverse rewrite, every `this.facade` back to a bare `this`, unambiguous -// because a base body that reads `this.facade` refuses (no declared member) -// and so does a class that declares `facade`. An indexed `this`, a `typeof -// this` and a static's bare `this` (the class) still refuse. - -const RECEIVER_CARD = '#30147'; -const FACADE_MEMBER = 'facade'; -/** The identity port's host entry: the interface line (its note on the line, so the sorted block keeps it whole) and the factory line. */ -const FACADE_ENTRY = Object.freeze({ - iface: ` readonly ${FACADE_MEMBER}: ${CLASS_NAME}; // the instance itself: a moved body's bare \`this\` reads \`this.${FACADE_MEMBER}\` (#30020 R1)`, - factory: ` ${FACADE_MEMBER}: protocol,`, -}); - -/** - * The identity port's undo (#30020 R1): a receiver facet member's body with - * each `this.facade` its own `this` reads put back to a bare `this`. Pure. - */ -function undoIdentity(ts, sf, member) { - const edits = []; - const visit = (node) => { - if (ts.isPropertyAccessExpression(node) && node.expression.kind === ts.SyntaxKind.ThisKeyword - && ts.isIdentifier(node.name) && node.name.text === FACADE_MEMBER && T_isMethodThis(ts, node.expression, member)) { - edits.push({ start: node.expression.getEnd(), end: node.getEnd(), text: '' }); - } - ts.forEachChild(node, visit); - }; - ts.forEachChild(member.body, visit); - const start = member.body.getStart(sf); - return applyEdits(sf.text.slice(start, member.body.getEnd()), edits.map((e) => ({ ...e, start: e.start - start, end: e.end - start }))); -} -const STATICS_NAME = `${CLASS_NAME}Statics`; -const STATICS_HOST_NAME = `${CLASS_NAME}StaticsHost`; - -/** The leaf a section's static tables move to, and its holder class: `protocol-write-gates.ts` -> `protocol-write-gates-tables.ts`, `ProtocolWriteGatesTables`. */ -const tablesModuleOf = (moduleFile) => moduleFile.replace(/\.ts$/, '-tables.ts'); -const tablesClassOf = (moduleFile) => facetNameOf(moduleFile).replace(/Facet$/, 'Tables'); - -/** The note a facet module carries above its import of the forwarder AS the class. */ -const ROUTE_NOTE = `// ${MARK} \`${CLASS_NAME}\` here is \`${STATICS_NAME}\` (imported AS the class): forwarders to its statics (${RECEIVER_CARD}).`; - -/** The one-line docblock on a moved table's initializer: the field keeps its own. */ -const tableOneLiner = (name) => `/** The initializer of \`${CLASS_NAME}.${name}\`; the field's declaration there is its contract. */`; - -/** - * A host entry typed as the type predicate it forwards (`x is T`), for a - * member `insertHostEntries` would forward through an untyped closure, which - * drops the predicate: the interface line is the one E1 writes, the factory - * line spells the member's own parameters and predicate. - */ -function predicateEntry(ts, sf, cls, table, member) { - const isStatic = table.statics.has(member); - const m = cls.members.find((x) => ts.isMethodDeclaration(x) && x.body && x.name && ts.isIdentifier(x.name) && x.name.text === member - && hasModifier(ts, x, ts.SyntaxKind.StaticKeyword) === isStatic); - if (!m || !m.type || m.parameters.some((p) => !ts.isIdentifier(p.name) || p.dotDotDotToken || p.initializer || p.getText(sf).includes('\n'))) { - refuse(`${member}: a predicate host entry needs one-line identifier parameters and a spelled predicate`); - } - const params = m.parameters.map((p) => p.getText(sf)).join(', '); - const args = m.parameters.map((p) => p.name.text).join(', '); - return { - iface: isStatic ? ` readonly ${member}: (typeof ${CLASS_NAME})['${member}'];` : ` readonly ${member}: ${CLASS_NAME}['${member}'];`, - factory: ` ${member}: (${params}): ${m.type.getText(sf)} => ${isStatic ? CLASS_NAME : 'protocol'}.${member}(${args}),`, - }; -} - -/** - * What a body reads of the class, for the receiver forms: `self` maps each - * member read through `this` (an instance member for an instance method, a - * static for a static) to `{ read, write, call }`; `statics` maps each static - * read through the class name (and, for a static, through `this`) to `method` - * or `getter`, its forwarder's kind; `identity` lists the span of each bare - * `this` an instance body hands on (`(this as any).x`, `f(this)`), which the - * facet member reads as `this.facade` (#30020 R1). `refusals` names what - * neither form carries: an indexed `this`, a `typeof this`, a static's bare - * `this`, a bare `this` in a class that declares `facade`, `this.constructor`, - * `super`, the method's `arguments`, a method read as a value, a static - * written or a static field called (the forwarder is read-only and is another - * receiver), a member the class does not declare (`this.facade` included, so - * the undo's inverse rewrite is unambiguous), and the class named other than - * as `.`. - */ -function receiverReads(ts, sf, m, table, isStatic) { - const self = new Map(); - const statics = new Map(); - const refusals = []; - // The identity port (#30020 R1): the `{ start, end }` of each bare `this` an - // instance body hands on, which its facet member reads as `this.facade`. - const identity = []; - const no = (why) => { if (!refusals.includes(why)) refusals.push(why); }; - const isCallee = (n) => ts.isCallExpression(n.parent) && n.parent.expression === n; - const written = (n) => { - const p = n.parent; - if (ts.isBinaryExpression(p) && p.left === n) return p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && p.operatorToken.kind <= ts.SyntaxKind.LastAssignment; - if ((ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(p.operator)) return true; - return ts.isDeleteExpression(p); - }; - const routeStatic = (access, how) => { - const name = access.name.text; - const st = table.statics.get(name); - if (!st) { no(`${how}.${name} names no declared static`); return; } - if (written(access)) { no(`it writes the static ${name} (the forwarder is read-only)`); return; } - if (st.kind === 'method' && !isCallee(access)) { no(`it reads the static method ${name} as a value (a forwarder is another function)`); return; } - if (st.kind !== 'method' && isCallee(access)) { no(`it calls the static ${st.kind} ${name} (the receiver would change)`); return; } - statics.set(name, st.kind === 'method' ? 'method' : 'getter'); - }; - const visit = (node) => { - if (node.kind === ts.SyntaxKind.ThisKeyword && T_isMethodThis(ts, node, m)) { - const p = node.parent; - if (!ts.isPropertyAccessExpression(p) || p.expression !== node || !ts.isIdentifier(p.name)) { - // R1 (#30020): an instance body's bare `this` hands the instance on, and - // reads the host's identity port. An indexed `this`, a `typeof this` and - // a static's `this` (the class) still refuse. - if (isStatic || ts.isElementAccessExpression(p)) { no('a bare `this` in a static, or an indexed `this`'); return; } - if (ts.isTypeQueryNode(p)) { no('`typeof this` (the type would name the host)'); return; } - if (table.instance.has(FACADE_MEMBER) || table.statics.has(FACADE_MEMBER)) { no(`facade-taken: the class declares a member named \`${FACADE_MEMBER}\` (the identity port would shadow it)`); return; } - identity.push({ start: node.getStart(sf), end: node.getEnd() }); - return; - } - const name = p.name.text; - if (name === 'constructor') { no('`this.constructor`'); return; } - if (isStatic) { - routeStatic(p, 'this'); - if (statics.has(name)) { - const u = self.get(name) ?? { read: false, write: false, call: false }; - u[isCallee(p) ? 'call' : 'read'] = true; - self.set(name, u); - } - } else { - const member = table.instance.get(name); - if (!member) { no(`\`this.${name}\` names no declared instance member`); return; } - if (table.statics.has(name)) { no(`\`${name}\` is both an instance and a static member`); return; } - if (member.kind === 'method' && !isCallee(p)) { no(`instance method \`${name}\` read as a value`); return; } - const u = self.get(name) ?? { read: false, write: false, call: false }; - u[written(p) ? 'write' : isCallee(p) ? 'call' : 'read'] = true; - self.set(name, u); - } - ts.forEachChild(p, (c) => { if (c !== node) visit(c); }); - return; - } - if (node.kind === ts.SyntaxKind.SuperKeyword) { no('`super`'); return; } - if (ts.isIdentifier(node) && node.text === 'this' && ts.isTypeQueryNode(node.parent)) { no('`typeof this` (the type would name the host)'); return; } - if (ts.isIdentifier(node) && !inJsDoc(ts, node) && !isPropertyNameIdentifier(ts, node)) { - if (node.text === 'arguments') { - let p = node.parent; - while (p && p !== m && (ts.isArrowFunction(p) || !ts.isFunctionLike(p))) p = p.parent; - if (p === m) no('the method\'s `arguments`'); - } - if (node.text === CLASS_NAME) { - const p = node.parent; - if (ts.isPropertyAccessExpression(p) && p.expression === node && ts.isIdentifier(p.name)) routeStatic(p, CLASS_NAME); - else no(`it names ${CLASS_NAME} other than as \`${CLASS_NAME}.\``); - } - } - ts.forEachChild(node, visit); - }; - for (const region of [...(m.typeParameters ?? []), ...m.parameters, m.type].filter(Boolean)) { - const scan = (n) => { - if (n.kind === ts.SyntaxKind.ThisKeyword || (ts.isIdentifier(n) && n.text === CLASS_NAME && !inJsDoc(ts, n))) no('its signature reads the class'); - ts.forEachChild(n, scan); - }; - scan(region); - } - if (m.body) ts.forEachChild(m.body, visit); - return { self, statics, refusals, identity }; -} - -/** host-split's `isMethodThis`, on this script's TypeScript instance: `this` reached from `m` through arrows only. */ -function T_isMethodThis(ts, node, m) { - for (let p = node.parent; p; p = p.parent) { - if (p === m) return true; - if (ts.isArrowFunction(p)) continue; - if (ts.isFunctionLike(p) || ts.isClassLike(p)) return false; - } - return false; -} - -/** The plan's stay reasons a receiver form answers: what E1's rewrite, or a host parameter, could not carry. */ -const RECEIVER_SOLVES = Object.freeze(['closed-set', 'no-host-read', 'static-reads-class', 'indent-irreversible']); - -/** The `{ start, end }` of a member's parameter list text, as the first pass spells it (from the first parameter to the list's end, trimmed). */ -const paramsTextOf = (sf, m) => (m.parameters.length ? sf.text.slice(m.parameters[0].getStart(sf), m.parameters.end).trim() : ''); -const argsOf = (m) => m.parameters.map((p) => (p.dotDotDotToken ? '...' : '') + p.name.getText()).join(', '); -const pickTypeOf = (type, names) => `Pick<${type}, ${names.map((n) => `'${n}'`).join(' | ')}>`; - -/** - * The receiver-form move of one base member (an instance method E1 refuses, or - * a private static that reads the class), or the reasons it cannot move. - * Returns `{ form, name, module, stub, member, ownedDoc, hostEntries, routed, - * imports, moduleRefs, picks, body }`: `form` is `receiver` (an instance body - * run on the host), `statics` (a static body run on the forwarder), or `plain` - * (no receiver); `member` is the facet member's text from its line start; - * `routed` the statics the body reads through the forwarder. Pure. - */ -function receiverMove(T, planned, r) { - const { ts } = T; - const { sf, cls, ctx } = planned; - const m = r.node; - const isStatic = r.isStatic === true; - const held = r.reasons.filter((x) => !RECEIVER_SOLVES.includes(x.split(':')[0])); - if (held.length > 0) return { refusals: held }; - const reads = receiverReads(ts, sf, m, ctx.table, isStatic); - if (reads.refusals.length > 0) return { refusals: reads.refusals.map((x) => `receiver: ${x}`) }; - if (!r.module) return { refusals: ['section-kept'] }; - const facet = facetNameOf(r.module); - const names = [...reads.self.keys(), ...(reads.identity.length > 0 ? [FACADE_MEMBER] : [])].sort(); - const form = names.length === 0 ? 'plain' : isStatic ? 'statics' : 'receiver'; - const routed = new Map(reads.statics); - const isPrivate = isPrivateMember(ts, m); - const span = isPrivate ? movableDocSpan(ts, sf, m) : null; - const ownedDoc = span ? span.text : null; - // R1 (#30020): each bare `this` reads the identity port; no other byte changes. - const bodyStart = m.body.getStart(sf); - const body = applyEdits(sf.text.slice(bodyStart, m.body.getEnd()), - reads.identity.map((at) => ({ start: at.end - bodyStart, end: at.end - bodyStart, text: `.${FACADE_MEMBER}` }))); - const thisParam = form === 'receiver' ? `this: ${pickTypeOf('ProtocolHost', names)}` - : form === 'statics' ? `this: ${pickTypeOf(STATICS_HOST_NAME, names)}` : null; - const params = [thisParam, paramsTextOf(sf, m)].filter(Boolean).join(', '); - const typeParams = m.typeParameters ? `<${sf.text.slice(m.typeParameters.pos, m.typeParameters.end).trim()}>` : ''; - const async = hasModifier(ts, m, ts.SyntaxKind.AsyncKeyword) ? 'async ' : ''; - const doc = ownedDoc ?? (isStatic ? staticOneLiner(r.name) : instanceOneLiner(r.name)); - const member = ` ${doc}\n static ${async}${r.name}${typeParams}(${params})${m.type ? `: ${m.type.getText(sf)}` : ''} ${body}`; - const args = argsOf(m); - const lead = ` // ${MARK} The body moved to \`${r.module}\``; - const stub = '{\n' + (form === 'receiver' - ? `${lead}; it runs on this class's host (\`${HOST_MODULE_BASENAME}\`) as \`this\`.\n return ${facet}.${r.name}.call(protocolHost(this)${args ? `, ${args}` : ''});\n` - : form === 'statics' - ? `${lead}; it runs on \`${STATICS_NAME}\` as \`this\`.\n return ${facet}.${r.name}.call(${STATICS_NAME}${args ? `, ${args}` : ''});\n` - : routed.size > 0 - ? `${lead}; it reads this class's statics through \`${STATICS_NAME}\`.\n return ${facet}.${r.name}(${args});\n` - : `${lead}; it reads nothing of this class.\n return ${facet}.${r.name}(${args});\n`) + ' }'; - const hostEntries = form === 'receiver' ? T.hs.hostEntriesFor({ instance: reads.self, statics: new Set() }, ctx.table, CLASS_NAME) : new Map(); - if (reads.identity.length > 0) hostEntries.set(FACADE_MEMBER, FACADE_ENTRY); - const predicates = new Set(cls.members.filter((x) => ts.isMethodDeclaration(x) && x.type && ts.isTypePredicateNode(x.type) && !x.type.assertsModifier && x.name && ts.isIdentifier(x.name)).map((x) => x.name.text)); - for (const k of [...hostEntries.keys()]) if (predicates.has(k)) hostEntries.set(k, predicateEntry(ts, sf, cls, ctx.table, k)); - return { - refusals: [], form, name: r.name, module: r.module, isStatic, stub, member, ownedDoc, hostEntries, routed, picks: names, body, identity: reads.identity.length, - imports: r.imports ?? new Map(), moduleRefs: new Map([...(r.moduleRefs ?? new Map())].filter(([n]) => n !== CLASS_NAME)), - }; -} - -/** The class member `name` the members pass may move: one instance method with a body, one static method with a body, or one static field. */ -function memberNamed(ts, cls, name) { - const found = cls.members.filter((m) => m.name && ts.isIdentifier(m.name) && m.name.text === name - && ((ts.isMethodDeclaration(m) && m.body) || (ts.isPropertyDeclaration(m) && hasModifier(ts, m, ts.SyntaxKind.StaticKeyword)))); - if (found.length !== 1) refuse(`--members names ${name}, which ${CLASS_NAME} declares as ${found.length === 0 ? 'no method with a body and no static field' : 'more than one member'}`); - return found[0]; -} - -/** - * The table move of one private static readonly field: its initializer to the - * section's leaf. Returns `{ name, module, leaf, field (the head field text), - * member (the leaf member text), imports, init }`, or `{ refusals }`. The - * initializer may read the imports of `protocol.ts` and globals only: never - * `this`, the class, a top-level name of `protocol.ts` or a relative import - * (the leaf imports nothing that could import `protocol.ts`). - */ -function tableMove(T, planned, f, sectionOf) { - const { ts } = T; - const { sf, ctx } = planned; - const name = f.name.text; - const refusals = []; - if (!hasModifier(ts, f, ts.SyntaxKind.PrivateKeyword) || !hasModifier(ts, f, ts.SyntaxKind.ReadonlyKeyword) || !f.initializer) refusals.push('table: only a private static readonly field with an initializer moves'); - const section = sectionOf(f); - if (!section.module) refusals.push('section-kept'); - if (refusals.length > 0) return { refusals }; - const scan = (n) => { - if (n.kind === ts.SyntaxKind.ThisKeyword || n.kind === ts.SyntaxKind.SuperKeyword) refusals.push('table: its initializer reads `this` or `super`'); - ts.forEachChild(n, scan); - }; - scan(f.initializer); - const names = readNames(ts, ctx, { typeParameters: undefined, parameters: [], type: f.type, body: f.initializer }); - for (const r of names.reasons) refusals.push(r); - for (const [n] of names.moduleRefs) refusals.push(`table: its initializer reads ${n}, a top-level name of ${HOST_BASENAME} (the leaf never imports it)`); - for (const [local] of names.imports) { - const b = ctx.scope.bindings.get(local); - if (b && b.kind === 'import' && b.specifier.startsWith('.')) refusals.push(`table: its initializer reads ${local}, a relative import (the leaf imports packages only)`); - } - if (refusals.length > 0) return { refusals: [...new Set(refusals)] }; - const init = sf.text.slice(f.initializer.getStart(sf), f.initializer.getEnd()); - const head = sf.text.slice(f.getStart(sf), f.initializer.getStart(sf)); - const tail = sf.text.slice(f.initializer.getEnd(), f.getEnd()); - const holder = tablesClassOf(section.module); - return { - refusals: [], name, module: section.module, title: section.title, leaf: tablesModuleOf(section.module), init, imports: names.imports, - field: `${head}${holder}.${name}${tail}`, - member: ` ${tableOneLiner(name)}\n static readonly ${name}${f.type ? `: ${f.type.getText(sf)}` : ''} = ${init};`, - start: f.initializer.getStart(sf), end: f.initializer.getEnd(), - }; -} - -/** The union of name -> `{ value }` maps, a name read as a value in any one read as a value. */ -function mergeUses(maps) { - const out = new Map(); - for (const m of maps) for (const [n, u] of m) out.set(n, { value: Boolean(out.get(n)?.value) || u.value }); - return new Map([...out].sort(byName)); -} - -/** The leaf a section's tables move to: the header, the initializers' imports, and one holder class. Pure. */ -function tablesModuleText(T, scope, moves) { - const { title, leaf } = moves[0]; - const holder = tablesClassOf(moves[0].module); - const names = moves.map((t, i) => `\`${t.name}\`${i === moves.length - 1 ? '' : ','}`); - const out = [ - '// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.', - '', - '/**', - ...wrapComment([MARK, 'The', 'static', 'tables', 'of', 'the', ...`"${title}"`.split(' '), 'section', 'of', `\`${CLASS_NAME}\`:`, - 'the', 'initializers', 'of', ...names, 'moved', 'out', 'of', '`protocol.ts`', 'whole', 'by', '`scripts/codemod-split-protocol.mjs', '--members`', `(${RECEIVER_CARD}).`]), - ' *', - ' * A MOVE, not a redesign. Each initializer below is the one the class field of', - ' * the same name carried, byte for byte; the field keeps its docblock,', - ' * modifiers and type, and reads its table from here. An initializer runs', - ' * while its class is evaluated, so this module imports neither `protocol.ts`', - ' * nor any module that does: only what the initializers read, from where', - ' * `protocol.ts` imports it. Nothing re-exports this module, so the published', - ' * surface does not move.', - ' */', - '', - ...importLines(scope, [{ isStatic: true, imports: mergeUses(moves.map((t) => t.imports)), moduleRefs: new Map() }]), - '', - `export class ${holder} {`, - moves.map((t) => t.member).join('\n\n'), - '}', - '', - ]; - return out.join('\n'); -} - -/** The forwarder `protocol.ts` carries for `kinds` (static -> `method` | `getter`): the text ahead of the class, and the static block at its end. Pure. */ -function staticsTexts(kinds) { - const members = [...kinds.keys()].sort(); - const ahead = [ - `// ${MARK} The statics of \`${CLASS_NAME}\` its facet modules read (${RECEIVER_CARD}), private ones`, - '// included, typed as the class declares them (an indexed access on the class). The static', - `// block at the end of the class fills \`${STATICS_NAME}\` with forwarders: a method is`, - '// called on the class at call time, a field is read when the body reads it. A facet module', - `// imports it AS \`${CLASS_NAME}\`, so a moved body reads \`${CLASS_NAME}.x\``, - '// unedited, and a moved static that reads `this` runs on it. `index.ts` re-exports neither, so', - '// neither reaches the package.', - `export interface ${STATICS_HOST_NAME} {`, - ...members.map((n) => ` readonly ${n}: (typeof ${CLASS_NAME})['${n}'];`), - '}', - `export const ${STATICS_NAME} = {} as ${STATICS_HOST_NAME};`, - ].join('\n'); - const block = [ - ` // ${MARK} Fills \`${STATICS_NAME}\` (declared above the class) for the facet modules.`, - ' static {', - ` Object.defineProperties(${STATICS_NAME}, {`, - ...members.map((n) => (kinds.get(n) === 'method' - ? ` ${n}: { value: (...args: Parameters) => ${CLASS_NAME}.${n}(...args) },` - : ` ${n}: { get: () => ${CLASS_NAME}.${n} },`)), - ' });', - ' }', - ].join('\n'); - return { ahead, block }; -} - -/** - * Where the forwarder stands in a `protocol.ts`: the statics it carries (static - * -> kind, read off its static block) and the spans of its two texts, or null - * when it carries none. Refuses half of one. - */ -function staticsOf(ts, sf) { - const text = sf.text; - const cls = sf.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === CLASS_NAME); - const iface = sf.statements.find((s) => ts.isInterfaceDeclaration(s) && s.name.text === STATICS_HOST_NAME); - const blockOpen = ` // ${MARK} Fills \`${STATICS_NAME}\``; - const at = cls ? text.indexOf(blockOpen, cls.getStart(sf)) : -1; - if (!iface && at < 0) return null; - if (!iface || at < 0 || !cls) refuse(`${HOST_BASENAME} carries half of the ${STATICS_NAME} forwarder`); - const kinds = new Map(); - const blockEnd = text.indexOf('\n });\n }', at); - if (blockEnd < 0) refuse(`${HOST_BASENAME}: the ${STATICS_NAME} static block does not close as written`); - for (const l of text.slice(at, blockEnd).split('\n')) { - const hit = /^ {12}([A-Za-z_$][\w$]*): \{ (value|get)/.exec(l); - if (hit) kinds.set(hit[1], hit[2] === 'value' ? 'method' : 'getter'); - } - const aheadStart = text.indexOf(`// ${MARK} The statics of \`${CLASS_NAME}\``); - const constDecl = `export const ${STATICS_NAME} = {} as ${STATICS_HOST_NAME};`; - const aheadEnd = text.indexOf(constDecl, aheadStart) + constDecl.length; - if (aheadStart < 0 || aheadEnd < constDecl.length) refuse(`${HOST_BASENAME}: the ${STATICS_NAME} declarations are not as written`); - // The block was written as `\n\n` after the class's last member. - return { kinds, ahead: { start: aheadStart, end: aheadEnd }, block: { start: at - 2, end: blockEnd + '\n });\n }'.length } }; -} - -/** Where the forwarder's two texts go in a `protocol.ts` that carries none: ahead of the class's leading comments, and after its last member. */ -function staticsSlots(ts, sf, cls) { - const ranges = ts.getLeadingCommentRanges(sf.text, cls.getFullStart()) ?? []; - const ahead = ranges.length > 0 ? lineStartOf(sf.text, ranges[0].pos) : lineStartOf(sf.text, cls.getStart(sf)); - return { ahead, block: cls.members.at(-1).getEnd() }; -} - -/** `protocol.ts`'s import of a section's tables leaf, written after the facet's own import. */ -const tablesImportText = (moduleFile) => `\n// ${MARK} The static tables of the facet above: the class's fields read them (${RECEIVER_CARD}).\n` - + `import { ${tablesClassOf(moduleFile)} } from './${tablesModuleOf(moduleFile).replace(/\.ts$/, '.js')}';`; - -/** - * Plan and apply the moves `names` asks for on a split `protocol.ts`. - * Returns `{ host, hostModule, modules, records, pruned }` (`modules`: the - * receiving modules' new texts, a tables leaf included). Refuses (exit 2) on a - * name the class does not declare as one method with a body or one static - * field, one already moved, one a stay rule holds that no receiver form - * carries (#30147), and every shape the section above says this pass does not - * grow. Pure. - */ -function generateMembers(T, text, hostText, moduleTexts, names, { anchors = SECTION_ANCHORS, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES } = {}) { - const { ts } = T; - globalTs = ts; - if (!names || names.length === 0) refuse(`--members needs a comma-separated list of ${CLASS_NAME} member names`); - if (new Set(names).size !== names.length) refuse(`--members names a member twice: ${names.join(', ')}`); - if (!text.includes(MARK)) refuse(`${HOST_BASENAME} carries no ${MARK} stub: run the first pass on an unsplit file`); - const planned = plan(T, text, hostText, { anchors, pins, needles, facade: true }); - const { sf, cls, ctx } = planned; - const sectionOf = sectionTable(ts, sf, cls, anchors); - const existingEntries = hostInterfaceEntries(hostText); - const records = []; - const tables = []; - for (const name of names) { - const node = memberNamed(ts, cls, name); - if (ts.isPropertyDeclaration(node)) { - const t = tableMove(T, planned, node, sectionOf); - if (t.refusals.length > 0) refuse(`${name} stays on the class: ${t.refusals.join('; ')}`); - tables.push({ ...t, node }); - continue; - } - const r = planned.records.find((x) => x.node === node); - if (!r) refuse(`--members names ${name}, which the plan does not read as a method with a body`); - if (r.reasons.some((x) => x.startsWith('already-moved')) || node.body.getText(sf).includes(MARK)) refuse(`${name} is already moved: its body is a stub`); - if (!r.isStatic && r.reasons.length === 0) { records.push(r); r.form = 'e1'; continue; } - const mv = receiverMove(T, planned, r); - if (mv.refusals.length > 0) { - refuse(`${name} stays on the class, as the first pass would keep it: ${r.reasons.map((x) => `${x} (${STAY_REASONS[x.split(':')[0]] ?? x})`).join('; ')}; ` - + `and no receiver form (${RECEIVER_CARD}) carries it: ${mv.refusals.join('; ')}`); - } - Object.assign(r, { form: mv.form, mv }); - records.push(r); - } - records.sort((a, b) => a.node.getStart(sf) - b.node.getStart(sf)); - tables.sort((a, b) => a.node.getStart(sf) - b.node.getStart(sf)); - const pos = classPositions(ts, cls); - - // protocol.ts: each body becomes its stub, a private docblock its link. - const edits = []; - const entries = new Map(); - const modules = new Map(); - const routed = new Map(); - for (const r of records) { - const facet = facetNameOf(r.module); - const b = ctx.scope.bindings.get(facet); - if (!b || b.kind !== 'import' || b.specifier !== `./${r.module.replace(/\.ts$/, '.js')}`) refuse(`${r.module}: ${HOST_BASENAME} does not import its facet ${facet} (this pass never starts a facet)`); - const refs = r.form === 'e1' ? r.moduleRefs : r.mv.moduleRefs; - for (const [n] of refs) { - if (n !== CLASS_NAME && !ctx.scope.exported.has(n)) refuse(`${r.name} reads ${n}, a top-level name of ${HOST_BASENAME} it does not export: this pass does not widen the generated export list`); - } - edits.push({ start: r.stub?.start ?? r.node.body.getStart(sf), end: r.stub?.end ?? r.node.body.getEnd(), text: r.form === 'e1' ? facetStubBody(r.name, r.module, r.node) : r.mv.stub }); - r.ownedDoc = null; - if (r.form !== 'e1') r.ownedDoc = r.mv.ownedDoc; - else if (isPrivateMember(ts, r.node)) r.ownedDoc = movableDocSpan(ts, sf, r.node)?.text ?? null; - if (r.ownedDoc) { - const span = movableDocSpan(ts, sf, r.node); - edits.push({ start: span.start, end: span.end, text: docStubOf(facet, r.name, r.module) }); - } - for (const [member, entry] of (r.form === 'e1' ? r.hostEntries : r.mv.hostEntries)) { - const have = existingEntries.get(member); - if (have !== undefined && have !== entry.iface) refuse(`${r.name} needs the host entry ${entry.iface.trim()}, and ${HOST_MODULE_BASENAME} carries ${have.trim()}`); - const prev = entries.get(member); - if (!prev || (entry.factory.includes('\n') && !prev.factory.includes('\n'))) entries.set(member, entry); - } - if (r.form !== 'e1') { - for (const [n, kind] of r.mv.routed) { - if (routed.has(n) && routed.get(n) !== kind) refuse(`${n}: two moved bodies read it as different kinds`); - routed.set(n, kind); - } - } - modules.set(r.module, [...(modules.get(r.module) ?? []), r]); - } - - // The forwarder: what the class already forwards, and what the moved bodies read. - const have = staticsOf(ts, sf); - const kinds = new Map(have?.kinds ?? []); - for (const [n, kind] of routed) { - if (kinds.has(n) && kinds.get(n) !== kind) refuse(`${STATICS_NAME} forwards ${n} as a ${kinds.get(n)}, and a moved body reads it as a ${kind}`); - kinds.set(n, kind); - } - if (kinds.size > (have?.kinds.size ?? 0)) { - const t = staticsTexts(new Map([...kinds].sort(byName))); - if (have) { - edits.push({ start: have.ahead.start, end: have.ahead.end, text: t.ahead }); - edits.push({ start: have.block.start, end: have.block.end, text: `\n\n${t.block}` }); - } else { - const slots = staticsSlots(ts, sf, cls); - edits.push({ start: slots.ahead, end: slots.ahead, text: `${t.ahead}\n\n` }); - edits.push({ start: slots.block, end: slots.block, text: `\n\n${t.block}` }); - } - } - - // The tables: each initializer to its section's leaf, the leaf imported once after its facet. - const leaves = new Map(); - for (const t of tables) leaves.set(t.leaf, [...(leaves.get(t.leaf) ?? []), t]); - const moduleOut = new Map(); - for (const [leaf, moves] of leaves) { - if (moduleTexts.has(leaf)) refuse(`${leaf} exists: this pass writes a section's tables leaf whole, once`); - for (const t of moves) edits.push({ start: t.start, end: t.end, text: `${tablesClassOf(t.module)}.${t.name}` }); - const facetImport = sf.statements.find((s) => ts.isImportDeclaration(s) && s.moduleSpecifier.text === `./${moves[0].module.replace(/\.ts$/, '.js')}`); - if (!facetImport) refuse(`${moves[0].module}: ${HOST_BASENAME} does not import its facet (this pass never starts a facet)`); - edits.push({ start: facetImport.getEnd(), end: facetImport.getEnd(), text: tablesImportText(moves[0].module) }); - moduleOut.set(leaf, tablesModuleText(T, ctx.scope, moves)); - } - - const inserted = T.hs.insertHostEntries(hostText, applyEdits(text, edits), new Map([...entries].sort(byName))); - const pruned = pruneImports(ts, inserted.protocol, usedImportNames(ts, inserted.protocol)); - - // The receiving modules: the members in class order, the header's names, the imports. - for (const [file, movers] of modules) { - const mod = moduleTexts.get(file); - if (mod == null || !mod.includes(MARK)) refuse(`${file} is not on disk as a facet module the first pass wrote: this pass adds to a written facet, never starts one`); - const facet = facetOf(ts, file, mod); - if (!facet || facet.members.length === 0) refuse(`${file}: no exported facet class ${facetNameOf(file)} with members`); - const header = headerNamesOf(mod, movers[0].section); - if (!header) refuse(`${file}: its header's first paragraph is not the one the first pass writes`); - const modEdits = []; - for (const r of movers) { - const at = r.node.getStart(sf); - const next = facet.members.find((m) => m.name && pos.has(m.name) && pos.get(m.name) > at); - const t = r.form === 'e1' ? facetMemberText(ts, r.fnText, r.ownedDoc) : r.mv.member; - if (next) modEdits.push({ start: next.start, end: next.start, text: `${t}\n\n` }); - else modEdits.push({ start: facet.members.at(-1).end, end: facet.members.at(-1).end, text: `\n\n${t}` }); - } - const listed = [...header.names]; - for (const r of movers) { - const k = listed.findIndex((n) => (pos.get(n) ?? Infinity) > r.node.getStart(sf)); - listed.splice(k < 0 ? listed.length : k, 0, r.name); - } - modEdits.push({ start: header.start, end: header.end, text: wrapComment(headerWords(movers[0].section, listed)).join('\n') }); - const wanted = new Map(); - const want = (local, w) => { - const prev = wanted.get(local); - wanted.set(local, { ...w, value: Boolean(prev && prev.value) || w.value }); - }; - for (const r of movers) { - const imports = r.form === 'e1' ? r.imports : r.mv.imports; - for (const [local, use] of imports) { - const b = ctx.scope.bindings.get(local); - if (!b || b.kind !== 'import') refuse(`import binding ${local} not found`); - want(local, { specifier: b.specifier, form: b.form, imported: b.imported, value: use.value && !b.typeOnly }); - } - for (const [n, use] of (r.form === 'e1' ? r.moduleRefs : r.mv.moduleRefs)) want(n, { specifier: './protocol.js', form: 'named', imported: n, value: use.value }); - if (r.form === 'e1' || r.form === 'receiver') want('ProtocolHost', { specifier: './protocol-host.js', form: 'named', imported: 'ProtocolHost', value: false }); - if (r.form !== 'e1' && r.mv.routed.size > 0) want(CLASS_NAME, { specifier: './protocol.js', form: 'named', imported: STATICS_NAME, value: true }); - if (r.form === 'statics') want(STATICS_HOST_NAME, { specifier: './protocol.js', form: 'named', imported: STATICS_HOST_NAME, value: false }); - } - const order = (s) => (ctx.scope.importOrder.has(s) ? ctx.scope.importOrder.get(s) : Number.MAX_SAFE_INTEGER); - moduleOut.set(file, withRouteNote(ts, file, addModuleImports(ts, file, applyEdits(mod, modEdits), wanted, order))); - } - return { host: pruned.text, hostModule: inserted.host, modules: moduleOut, records: [...records, ...tables], pruned: pruned.removed }; -} - -/** A facet module that imports the forwarder AS the class carries `ROUTE_NOTE` on the line above that import; one that does not, carries none. */ -function withRouteNote(ts, file, text) { - const routedImport = importDeclsOf(ts, file, text).decls.find((d) => d.named.some((e) => e.local === CLASS_NAME && e.imported === STATICS_NAME)); - const has = text.includes(`${ROUTE_NOTE}\n`); - if (routedImport && !has) { - const at = lineStartOf(text, routedImport.start); - return `${text.slice(0, at)}${ROUTE_NOTE}\n${text.slice(at)}`; - } - if (!routedImport && has) return text.replace(`${ROUTE_NOTE}\n`, ''); - return text; -} - -/** - * Undo the moves out of one receiving module, from its head text alone: drop - * each moved facet member with the blank line the move wrote, its name from - * the header's first paragraph, and the import bindings nothing reads any - * more. Returns the text, or null (after `fail`) when the head is not a module - * this pass can read. - */ -function undoMembersModule(ts, file, text, names, title, fail, baseBound = null) { - let out = text; - for (const name of names) { - const facet = facetOf(ts, file, out); - const i = facet ? facet.members.findIndex((m) => m.name === name && m.staticMethod) : -1; - if (i < 0) { fail(`${file}: holds no static facet member ${name}`); return null; } - const ms = facet.members; - if (ms.length === 1) { fail(`${file}: ${name} is its only member (this pass never starts a facet)`); return null; } - if (i < ms.length - 1) { - if (out.slice(ms[i].end, ms[i + 1].start) !== '\n\n') { fail(`${file}: ${name} is not followed by exactly one blank line`); return null; } - out = out.slice(0, ms[i].start) + out.slice(ms[i + 1].start); - } else { - if (out.slice(ms[i - 1].end, ms[i].start) !== '\n\n') { fail(`${file}: ${name} is not preceded by exactly one blank line`); return null; } - out = out.slice(0, ms[i - 1].end) + out.slice(ms[i].end); - } - } - const header = headerNamesOf(out, title); - if (!header) { fail(`${file}: its header's first paragraph is not the one the first pass writes`); return null; } - for (const n of names) if (!header.names.includes(n)) fail(`${file}: its header does not list ${n}`); - out = out.slice(0, header.start) + wrapComment(headerWords(title, header.names.filter((n) => !names.includes(n)))).join('\n') + out.slice(header.end); - // A binding only a docblock's link reads is dropped too unless the base binds - // it (#30147): a link elsewhere in the module to a name a moved body imports - // would otherwise keep that import alive. Which names the base binds is the - // one fact this undo reads off the base, as the host entries' undo does. - const code = usedImportNames(ts, out, { docs: false }); - const all = usedImportNames(ts, out); - const used = baseBound ? new Set([...all].filter((n) => code.has(n) || baseBound.has(n))) : all; - return withRouteNote(ts, file, pruneModuleImports(ts, file, out, used)); -} - -/** The local names a module's import declarations bind. */ -function importBoundNames(ts, file, text) { - const out = new Set(); - for (const d of importDeclsOf(ts, file, text).decls) for (const n of [d.defaultName, d.nsName, ...d.named.map((e) => e.local)]) if (n) out.add(n); - return out; -} - -/** A host block's keyed groups, each the text of its lines (a setter is its getter's continuation). */ -function hostGroups(text, openMarker, closeMarker, keyOf, isContinuation) { - const open = text.indexOf(openMarker); - const close = text.indexOf(closeMarker, open); - const out = new Map(); - if (open < 0 || close < 0) return out; - let key; - for (const l of text.slice(open + openMarker.length, close).split('\n')) { - const k = keyOf(l); - if (k !== undefined) { key = k; out.set(k, l); } else if (key !== undefined && isContinuation(l)) out.set(key, `${out.get(key)}\n${l}`); - else key = undefined; - } - return out; -} - -/** - * Prove this pass's moves against the pre-move tree, from the texts alone (it - * shares no state with `generateMembers`). `base` / `head`: `{ text, host, - * modules }` (`protocol.ts`, `protocol-host.ts`, the section modules and the - * tables leaves by file). Returns `{ failures, moved, checks, pruned, - * linesBefore, linesAfter, forms }`. - */ -function verifyMembers(T, base, head, { anchors = SECTION_ANCHORS, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES } = {}) { - const { ts, hs } = T; - globalTs = ts; - const failures = []; - const fail = (msg) => failures.push(msg); - const moved = []; - const checks = []; - const tables = []; - const baseSf = parseSourceFile(HOST_PATH, base.text); - const headSf = parseSourceFile(HOST_PATH, head.text); - const baseCls = hs.classOf(baseSf, CLASS_NAME); - const headCls = hs.classOf(headSf, CLASS_NAME); - const forms = () => { - const n = new Map(); - for (const mv of moved) n.set(mv.form ?? '?', (n.get(mv.form ?? '?') ?? 0) + 1); - if (tables.length) n.set('table', tables.length); - return Object.fromEntries(n); - }; - const done = (pruned = []) => ({ failures, moved: [...moved.map((mv) => mv.name), ...tables.map((t) => t.name)], checks, pruned, linesBefore: lineCount(base.text), linesAfter: lineCount(head.text), forms: forms() }); - if (!baseCls || !headCls) { fail(`no class ${CLASS_NAME} at base or head`); return done(); } - const marker = new RegExp(`^\\{\\s*// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(protocol-[a-z0-9-]+\\.ts)\``); - const key = (m) => `${hasModifier(ts, m, ts.SyntaxKind.StaticKeyword) ? 'static ' : ''}${m.name && ts.isIdentifier(m.name) ? m.name.text : ts.SyntaxKind[m.kind]}`; - const methodsOf = (cls) => new Map(cls.members.filter((m) => ts.isMethodDeclaration(m) && m.body).map((m) => [key(m), m])); - const fieldsOf = (cls) => new Map(cls.members.filter((m) => ts.isPropertyDeclaration(m) && hasModifier(ts, m, ts.SyntaxKind.StaticKeyword) && m.name && ts.isIdentifier(m.name)).map((m) => [m.name.text, m])); - const baseMethods = methodsOf(baseCls); - const headMethods = methodsOf(headCls); - if ([...baseMethods.keys()].join() !== [...headMethods.keys()].join()) fail(`${CLASS_NAME} does not declare the same methods in the same order at base and head`); - for (const [k, hm] of headMethods) { - const bm = baseMethods.get(k); - if (!bm) continue; - const hHit = marker.exec(hm.body.getText(headSf)); - const bHit = marker.exec(bm.body.getText(baseSf)); - if (bHit && !hHit) fail(`${k}: a stub at base is a body at head`); - if (!hHit || bHit) continue; - moved.push({ name: hm.name.text, isStatic: k.startsWith('static '), hm, bm, file: hHit[1] }); - } - const basePlan = plan(T, base.text, base.host, { anchors, pins, needles, facade: true }); - const sectionOf = sectionTable(ts, baseSf, basePlan.cls, anchors); - const baseFields = fieldsOf(basePlan.cls); - const headFields = fieldsOf(headCls); - if ([...baseFields.keys()].join() !== [...headFields.keys()].join()) fail(`${CLASS_NAME} does not declare the same static fields in the same order at base and head`); - for (const [name, hf] of headFields) { - const bf = baseFields.get(name); - if (!bf || hf.getText(headSf) === bf.getText(basePlan.sf)) continue; - const t = tableMove(T, basePlan, bf, sectionOf); - if (t.refusals.length > 0) { fail(`${name}: its field changed, and it is no table this pass moves (${t.refusals.join('; ')})`); continue; } - if (hf.getText(headSf) !== t.field) fail(`${name}: its field is not the base field reading its table from ${t.leaf}`); - tables.push({ ...t, hf }); - } - if (moved.length === 0 && tables.length === 0) fail('nothing moved: the head carries no stub or table its base did not'); - - const headPrivateStatics = new Set([...hs.memberTable(headCls).statics].filter(([, s]) => s.private).map(([n]) => n)); - const expectedEntries = new Map(); - const routed = new Map(); - for (const mv of moved) { - const { name, hm, bm, file } = mv; - const r = basePlan.records.find((x) => x.node.name?.text === name && Boolean(x.isStatic) === mv.isStatic); - if (!r) { fail(`${name}: no record of it at base`); continue; } - if (r.module !== file) { fail(`${name}: its stub names ${file}, and its section's module is ${r.module ?? 'none'}`); continue; } - mv.title = r.section; - const e1 = !mv.isStatic && r.reasons.length === 0; - const rm = e1 ? null : receiverMove(T, basePlan, r); - if (rm && rm.refusals.length > 0) { fail(`${name}: a stay rule holds it at base, and no receiver form carries it (${[...r.reasons, ...rm.refusals].join('; ')})`); continue; } - mv.form = e1 ? 'e1' : rm.form; - const wantStub = e1 ? facetStubBody(name, file, bm) : rm.stub; - if (hm.body.getText(headSf) !== wantStub) fail(`${name}: the stub is not the one this pass writes for its form (${mv.form})`); - const facet = facetNameOf(file); - const span = isPrivateMember(ts, bm) ? movableDocSpan(ts, baseSf, bm) : null; - mv.ownedDoc = span ? span.text : null; - const sig = (sf, m, doc) => { - const s = sf.text.slice(m.getFullStart(), m.body.getStart(sf)); - return doc ? s.replace(doc, docStubOf(facet, name, file)) : s; - }; - if (sig(headSf, hm) !== sig(baseSf, bm, mv.ownedDoc)) fail(`${name}: its docblock, modifiers or signature changed (beyond docblock ownership)`); - const modText = head.modules.get(file); - const fo = modText && modText.includes(MARK) ? facetOf(ts, file, modText) : null; - const fm = fo?.members.find((m) => m.name === name && m.staticMethod); - if (!fm) { fail(`${name}: ${file} at head holds no facet member ${name}`); continue; } - mv.fm = fm; - mv.modText = modText; - const wantMember = e1 ? facetMemberText(ts, r.fnText, mv.ownedDoc) : rm.member; - if (modText.slice(fm.start, fm.end) !== wantMember) { - fail(`${name}: the facet member is not its base method's text as this pass writes it (${mv.form}: docblock, parameters, return type, body)`); - } - for (const [k, e] of (e1 ? r.hostEntries : rm.hostEntries)) if (!expectedEntries.has(k) || e.factory.includes('\n')) expectedEntries.set(k, e); - if (!e1) { - for (const [n, kind] of rm.routed) routed.set(n, kind); - // The body moved unedited but for R1's identity port (#30020): its undo is - // the facet member's body, each `this.facade` back to a bare `this`, byte for byte. - mv.restored = mv.form === 'receiver' ? undoIdentity(ts, fo.sf, fm.node) : modText.slice(fm.node.body.getStart(fo.sf), fm.node.body.getEnd()); - mv.identity = rm.identity; - if (mv.restored !== base.text.slice(bm.body.getStart(baseSf), bm.body.getEnd())) fail(`${name}: its moved body (each \`this.${FACADE_MEMBER}\` back to \`this\`) is not the base body, byte for byte`); - const thisParam = fm.node.parameters[0]; - const pk = thisParam && ts.isIdentifier(thisParam.name) && thisParam.name.text === 'this' - ? /^this: Pick<(\w+), (.+)>$/s.exec(modText.slice(thisParam.getStart(fo.sf), thisParam.getEnd())) : null; - mv.picks = pk && pk[1] === 'ProtocolHost' ? pk[2].split('|').map((q) => q.trim().slice(1, -1)) : []; - checks.push({ name, ok: true, form: mv.form, counts: null }); - continue; - } - const fnText = unliftMethod(ts, modText.slice(fm.node.getStart(fo.sf), fm.end)); - const fnBody = fnText === null ? null : functionBodyOf(ts, fnText); - if (fnBody === null) { fail(`${name}: ${facet}.${name} does not unlift`); continue; } - mv.restored = undoBody(ts, fnBody, headPrivateStatics); - if (mv.restored !== base.text.slice(bm.body.getStart(baseSf), bm.body.getEnd())) fail(`${name}: its moved body, rewrites and re-indentation undone, is not the base body`); - mv.picks = picksOf(modText, fm) ?? []; - // `host-split.mjs`'s own check, on the unlifted pair. - const callee = hm.body.statements.at(-1)?.expression?.expression; - const headDoc = mv.ownedDoc ? movableDocSpan(ts, headSf, hm) : null; - const headA = callee && ts.isPropertyAccessExpression(callee) - ? applyEdits(head.text, [ - { start: callee.getStart(headSf), end: callee.name.getStart(headSf), text: '' }, - ...(headDoc ? [{ start: headDoc.start, end: headDoc.end, text: mv.ownedDoc }] : []), - ]) - : head.text; - const c = hs.checkMove({ baseSource: base.text, headSource: headA, moduleSource: `${fnText}\n`, moduleFile: file, member: name, className: CLASS_NAME }); - checks.push({ name, ok: c.ok, form: 'e1', counts: c.counts }); - for (const p of c.problems) fail(`host-split check ${name}: ${p}`); - } - - // The modules: each receiving one undoes to its base; a tables leaf is its generator's text; every other is its base. - const touched = new Map(); - for (const mv of moved) if (mv.fm) touched.set(mv.file, [...(touched.get(mv.file) ?? []), mv]); - const leaves = new Map(); - for (const t of tables) leaves.set(t.leaf, [...(leaves.get(t.leaf) ?? []), t]); - for (const file of new Set([...base.modules.keys(), ...head.modules.keys()])) { - const b = base.modules.get(file) ?? null; - const h = head.modules.get(file) ?? null; - if (leaves.has(file)) { - if (b !== null) fail(`${file}: a tables leaf at base (this pass writes one whole, once)`); - if (h !== tablesModuleText(T, basePlan.ctx.scope, leaves.get(file))) fail(`${file}: not the leaf this pass writes for the tables it holds`); - continue; - } - if (!touched.has(file)) { - if (b !== h) fail(`${file}: changed, and no member this pass moved is in it`); - continue; - } - if (b === null || !b.includes(MARK)) { fail(`${file}: not a facet module at base (this pass never starts a facet)`); continue; } - const mvs = touched.get(file); - if (h !== null && withRouteNote(ts, file, h) !== h) fail(`${file}: its import of ${STATICS_NAME} AS the class does not carry the note above it, as this pass writes it (or the note stands alone)`); - const u = undoMembersModule(ts, file, h, mvs.map((mv) => mv.name), mvs[0].title, fail, importBoundNames(ts, file, b)); - if (u !== null && u !== b) fail(`undoing the moves out of ${file} does not rebuild its base (first difference at line ${firstDiff(u, b)})`); - } - - // protocol.ts: each body and owned docblock back, each table's initializer back - // (read off its leaf at head), the forwarder and the leaves' imports gone; the - // factory loses the entries the base did not carry. - const edits = []; - for (const mv of moved) { - if (!mv.fm || mv.restored === undefined) continue; - edits.push({ start: mv.hm.body.getStart(headSf), end: mv.hm.body.getEnd(), text: mv.restored }); - if (mv.ownedDoc) { - const span = movableDocSpan(ts, headSf, mv.hm); - if (span) edits.push({ start: span.start, end: span.end, text: mv.ownedDoc }); - } - } - for (const [leaf, ts_] of leaves) { - const leafText = head.modules.get(leaf) ?? ''; - const leafSf = parseSourceFile(join(SRC_DIR, leaf), leafText); - const holder = leafSf.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === tablesClassOf(ts_[0].module)); - for (const t of ts_) { - const lm = holder?.members.find((m) => ts.isPropertyDeclaration(m) && m.name?.getText(leafSf) === t.name && m.initializer); - if (!lm) { fail(`${leaf}: holds no table ${t.name}`); continue; } - edits.push({ start: t.hf.initializer.getStart(headSf), end: t.hf.initializer.getEnd(), text: leafText.slice(lm.initializer.getStart(leafSf), lm.initializer.getEnd()) }); - } - const imp = tablesImportText(ts_[0].module); - const at = head.text.indexOf(imp); - if (at < 0 || head.text.indexOf(imp, at + 1) >= 0) fail(`${HOST_BASENAME} does not import ${leaf} once, as this pass writes it`); - else edits.push({ start: at, end: at + imp.length, text: '' }); - } - const baseStatics = staticsOf(ts, baseSf); - const headStatics = staticsOf(ts, headSf); - const wantKinds = new Map([...(baseStatics?.kinds ?? []), ...routed].sort(byName)); - if (wantKinds.size > 0) { - if (!headStatics) fail(`${HOST_BASENAME} carries no ${STATICS_NAME} forwarder, and the moved bodies read ${[...routed.keys()].join(', ')} through it`); - else { - const t = staticsTexts(wantKinds); - if (head.text.slice(headStatics.ahead.start, headStatics.ahead.end) !== t.ahead || head.text.slice(headStatics.block.start, headStatics.block.end) !== `\n\n${t.block}`) { - fail(`${STATICS_NAME}: not the forwarder this pass writes for the base's statics and the ones the moved bodies read`); - } - if (baseStatics) { - const bt = staticsTexts(baseStatics.kinds); - edits.push({ start: headStatics.ahead.start, end: headStatics.ahead.end, text: bt.ahead }); - edits.push({ start: headStatics.block.start, end: headStatics.block.end, text: `\n\n${bt.block}` }); - } else { - if (head.text.slice(headStatics.ahead.end, headStatics.ahead.end + 2) !== '\n\n') fail(`${STATICS_NAME}: its declarations are not followed by one blank line`); - edits.push({ start: headStatics.ahead.start, end: headStatics.ahead.end + 2, text: '' }); - edits.push({ start: headStatics.block.start, end: headStatics.block.end, text: '' }); - } - } - } else if (headStatics) fail(`${HOST_BASENAME} carries a ${STATICS_NAME} forwarder no moved body reads`); - let rebuilt = applyEdits(head.text, edits); - const baseFactory = hostBlockKeys(base.text, FACTORY_OPEN, FACTORY_CLOSE, factoryKey); - const baseIface = hostBlockKeys(base.host, IFACE_OPEN, IFACE_CLOSE, ifaceKey); - if (!baseFactory || !baseIface) fail('the base carries no host factory or no ProtocolHost interface'); - else { - const setter = (l) => /^ {12}set /.test(l); - const f = dropHostGroups(rebuilt, FACTORY_OPEN, FACTORY_CLOSE, factoryKey, baseFactory.keys, setter); - if (f.missing) fail(`${HOST_BASENAME} at head carries no host factory`); - rebuilt = f.text; - const i = dropHostGroups(head.host, IFACE_OPEN, IFACE_CLOSE, ifaceKey, baseIface.keys, () => false); - if (i.missing) fail(`${HOST_MODULE_BASENAME} at head carries no ProtocolHost interface`); - if (i.text !== base.host) fail(`undoing the moves does not rebuild the base ${HOST_MODULE_BASENAME} (first difference at line ${firstDiff(i.text, base.host)})`); - if (JSON.stringify([...f.dropped].sort()) !== JSON.stringify([...i.dropped].sort())) fail(`the factory and the interface gained different entries: factory ${f.dropped.join(', ')}; interface ${i.dropped.join(', ')}`); - const picked = new Set(moved.flatMap((mv) => mv.picks ?? [])); - const headFactory = hostGroups(head.text, FACTORY_OPEN, FACTORY_CLOSE, factoryKey, setter); - const headIface = hostGroups(head.host, IFACE_OPEN, IFACE_CLOSE, ifaceKey, () => false); - for (const k of i.dropped) { - if (!picked.has(k)) fail(`${HOST_MODULE_BASENAME} gained ${k}, which no moved body's host type names`); - const e = expectedEntries.get(k); - if (e && (headIface.get(k) !== e.iface || headFactory.get(k) !== e.factory)) fail(`the host entry ${k} is not the one this pass writes for it`); - } - } - const prune = pruneImports(ts, base.text, usedImportNames(ts, head.text)); - const movedText = `${moved.map((mv) => mv.restored ?? '').join('\n')}\n${moved.map((mv) => mv.ownedDoc ?? '').join('\n')}\n${tables.map((t) => t.init).join('\n')}`; - for (const n of prune.removed) { - if (!new RegExp(`\\b${n.replace(/\$/g, '\\$')}\\b`).test(movedText)) fail(`${HOST_BASENAME} lost the import binding ${n}, which no moved body reads`); - } - if (rebuilt !== prune.text) { - const at = firstDiff(rebuilt, prune.text); - fail(`undoing the moves does not rebuild the base ${HOST_BASENAME} (its unread imports pruned): first difference at line ${at}` + - `\n rebuilt: ${JSON.stringify(rebuilt.split('\n')[at - 1] ?? '')}\n base: ${JSON.stringify(prune.text.split('\n')[at - 1] ?? '')}`); - } - return done(prune.removed); -} - -function printVerifyMembers(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - const forms = Object.entries(v.forms ?? {}).map(([f, n]) => `${f} ${n}`).join(', ') || 'none'; - const e1 = v.checks.filter((c) => c.form === 'e1'); - console.log(`undo proof (${MEMBERS_CARD}, ${RECEIVER_CARD}): ${v.moved.length} moved member(s) (${v.moved.join(', ') || 'none'}); forms: ${forms}; ` + - `host-split check: ${e1.filter((c) => c.ok).length}/${e1.length} E1 move(s) pass (the receiver forms move bodies unedited but for #30020 R1's \`this.facade\`, proved byte-equal); ${HOST_BASENAME} ${v.linesBefore} -> ${v.linesAfter} lines; ` + - `undoing the moves ${v.failures.length > 0 ? 'does NOT' : 'does'} rebuild the base ${HOST_BASENAME}, ${HOST_MODULE_BASENAME} and section modules byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved bodies read are pruned from the base (${v.pruned.join(', ') || 'none'})`); -} - -function generatedModulesAt(ref) { - const out = new Map(); - for (const [, , section] of SECTION_ANCHORS) { - if (!section) continue; - for (const file of [section, tablesModuleOf(section)]) { - try { - out.set(file, execFileSync('git', ['show', `${ref}:${SRC_REL}/${file}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'ignore'] })); - } catch { /* absent at the ref */ } - } - } - return out; -} - -async function mainMembers(T, argv) { - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--members --verify needs --base '); - const v = verifyMembers(T, - { text: gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), host: gitShow(ref, `${SRC_REL}/${HOST_MODULE_BASENAME}`), modules: generatedModulesAt(ref) }, - { text: readFileSync(HOST_PATH, 'utf8'), host: readFileSync(HOST_MODULE_PATH, 'utf8'), modules: generatedModulesOnDisk() }); - printVerifyMembers(v); - return v.failures.length === 0 ? 0 : 1; - } - const j = argv.indexOf('--members'); - const value = argv[j + 1]; - const names = value && !value.startsWith('--') ? value.split(',').map((s) => s.trim()).filter(Boolean) : []; - const base = { text: readFileSync(HOST_PATH, 'utf8'), host: readFileSync(HOST_MODULE_PATH, 'utf8'), modules: generatedModulesOnDisk() }; - const out = generateMembers(T, base.text, base.host, base.modules, names); - console.log(`# codemod-split-protocol --members (${MEMBERS_CARD}): named methods onto the landed facade`); - for (const r of out.records) { - if (r.leaf) console.log(`- ${r.name} (a static table) -> ${tablesClassOf(r.module)} (${r.leaf}): its initializer`); - else console.log(`- ${r.name} -> ${facetNameOf(r.module)} (${r.module}), ${r.form}: ${r.bodyLines} body lines${r.mv?.identity ? `, ${r.mv.identity} bare \`this\` -> \`this.${FACADE_MEMBER}\` (#30020 R1)` : ''}${r.ownedDoc ? ', its docblock with it' : ''}`); - } - const head = { text: out.host, host: out.hostModule, modules: new Map([...base.modules, ...out.modules]) }; - console.log(`output tree sha256: ${treeHash(new Map([[HOST_BASENAME, out.host], [HOST_MODULE_BASENAME, out.hostModule], ...out.modules]))}`); - const v = verifyMembers(T, base, head); - printVerifyMembers(v); - if (v.failures.length > 0) { - console.error('✗ the moves fail their proof: nothing written. Report the fork; never hand-edit the move.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - writeFileSync(HOST_PATH, out.host); - writeFileSync(HOST_MODULE_PATH, out.hostModule); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME}, ${HOST_MODULE_BASENAME} and ${out.modules.size} facet module(s) under ${SRC_REL}`); - return 0; -} - -// ── The hand-host pass: a hand stub's host, run on the class's host (#30020) ─ -// -// A hand-series stub (#25467) builds its host as an object literal and makes -// one `fn.call(host, …)`; the facade gate reads that as a delegation while -// every slot of the literal forwards. A slot that COMPUTES instead (a service -// lookup, an operator) makes the whole stub a body, so the method stays an -// exception row. Such a slot cannot become a `ProtocolHost` entry: an entry is -// typed AS a class member, and a new member would change the published -// `.d.ts`; and the factory in the class's static block may only forward. -// -// `--hand-host ` (design ruling A, 6687865760: the facade stays the sole -// state owner and a facet reaches it through the per-instance host) moves the -// stub's WHOLE body, its consts, its host literal and its `.call`, byte for -// byte but one indentation level out, into the hand module its marker names, -// as one exported function `OnHost` that runs on the class's host -// (`protocol-host.ts`) as `this`, its `this` the `Pick` of the members the -// body reads. In the receiver form `this.` reads the host entry of -// that member, so no byte of the body changes; the hand function the body -// calls, and its own `this`, do not change either. The stub becomes -// `return OnHost.call(protocolHost(this), )`, one forwarding -// call. The function keeps the method's parameters and return type as they -// are spelled on the class. -// -// What it moves is closed: a body that is the hand series' stub (its marker -// line, consts, ONE host literal, `return fn.call(host, …)`, `fn` imported -// from the module the marker names), whose literal holds at least one slot -// that is not a hand-series forwarder (`get x() { return readX(); }`, -// `set x(value) { writeX(value); }`, `x: (...a) => this.x(...a)`), that reads -// the class only as `this.` with a `ProtocolHost` entry already on -// file (this pass never grows the host), and nothing of `protocol.ts`'s own -// top level. Anything else refuses (exit 2). The module gains the import -// bindings the moved body reads, from where `protocol.ts` imports them (as the -// members pass adds them), and `ProtocolHost`'s type; `protocol.ts` imports -// the new function beside the hand function and drops the bindings only the -// moved body read. -// -// The proof (`--hand-host --verify --base REF` re-runs it) undoes every -// function the head carries under this pass's docblock, from the head alone: -// its body, one level back in, onto its stub; the function, with its docblock -// and the blank line before it, out of the module, and the module's imports -// nothing reads any more with it; the function's binding out of `protocol.ts`'s -// import. The result must be the base `protocol.ts` (its import bindings only -// moved bodies read pruned from it) and every hand module byte for byte, and -// `protocol-host.ts` unchanged. Then the pass, run again on the undone tree, -// must write the head byte for byte: the undo and the move are each other's -// inverse on this tree. - -const HAND_HOST_CARD = '#30020'; -const HAND_HOST_MARK = `[${HAND_HOST_CARD} codemod]`; -/** The first line of a hand-series stub's body: its marker, naming the hand module. */ -const HAND_STUB_LINE = /^ {8}\/\/ \[#25467 cut [0-9a-z]+\] The body moved to `(protocol-[a-z0-9-]+\.ts)`/; -const handHostName = (stub) => `${stub}OnHost`; -const handHostDoc = (stub, fn) => ['/**', ...wrapComment(( - `${HAND_HOST_MARK} The body of \`${CLASS_NAME}#${stub}\`, the host it builds for {@link ${fn}} included: ` + - `moved here whole by \`--hand-host\` of \`scripts/codemod-split-protocol.mjs\`. It runs on the class's host ` + - `(\`${HOST_MODULE_BASENAME}\`) as \`this\`, so the class keeps a one-call stub; the method's docblock there is its contract.`).split(' ')), ' */'].join('\n'); -const handHostStubLead = (file) => ` // ${HAND_HOST_MARK} The body moved to \`${file}\`; it runs on this class's host (\`${HOST_MODULE_BASENAME}\`) as \`this\`.`; -const handHostStub = (file, stub, args) => `{\n${handHostStubLead(file)}\n return ${handHostName(stub)}.call(protocolHost(this)${args ? `, ${args}` : ''});\n }`; - -/** A slot of a hand-series host literal in one of the series' forwarder spellings. */ -function isHandForwarder(ts, sf, p) { - const t = p.getText(sf); - const cap = (n) => n[0].toUpperCase() + n.slice(1); - let m = /^get ([A-Za-z_$][\w$]*)\(\) \{ return (read[\w$]+)\(\); \}$/.exec(t); - if (m) return m[2] === `read${cap(m[1])}`; - m = /^set ([A-Za-z_$][\w$]*)\(value\) \{ (write[\w$]+)\(value\); \}$/.exec(t); - if (m) return m[2] === `write${cap(m[1])}`; - m = /^([A-Za-z_$][\w$]*): \(\.\.\.a\) => this\.([A-Za-z_$][\w$]*)\(\.\.\.a\)$/.exec(t); - return Boolean(m && m[1] === m[2]); -} - -/** The analysis context of one `protocol.ts` text: its program, class, member table and module scope. */ -function handHostContext(T, text) { - const { ts, hs } = T; - globalTs = ts; - const { sf, checker } = program(ts, HOST_PATH, text); - const cls = hs.classOf(sf, CLASS_NAME); - if (!cls) refuse(`no class ${CLASS_NAME} in ${HOST_BASENAME}`); - const table = hs.memberTable(cls); - const staticScope = new Map(); - for (const m of cls.members) { - if (!hasModifier(ts, m, ts.SyntaxKind.StaticKeyword) || !m.name || !ts.isIdentifier(m.name)) continue; - staticScope.set(m.name.text, hasModifier(ts, m, ts.SyntaxKind.PrivateKeyword) ? 'private' - : hasModifier(ts, m, ts.SyntaxKind.ProtectedKeyword) ? 'protected' : 'public'); - } - return { ts, sf, checker, cls, table, staticScope, scope: moduleScope(ts, sf) }; -} - -/** The one instance method with a body named `name`, or a refusal. */ -function handHostMethod(ts, cls, name) { - const found = cls.members.filter((m) => ts.isMethodDeclaration(m) && m.body && m.name && ts.isIdentifier(m.name) && m.name.text === name - && !hasModifier(ts, m, ts.SyntaxKind.StaticKeyword)); - if (found.length !== 1) refuse(`--hand-host names ${name}, which ${CLASS_NAME} declares as ${found.length === 0 ? 'no instance method with a body' : 'more than one method'}`); - return found[0]; -} - -/** `text` with every line after the first moved `by` columns left; null when a later line is not that far in, or holds only spaces. */ -function outdentBy(text, by) { - const pad = ' '.repeat(by); - const lines = text.split('\n'); - const out = [lines[0]]; - for (const line of lines.slice(1)) { - if (line === '') out.push(line); - else if (line.startsWith(pad) && line.trim() !== '') out.push(line.slice(by)); - else return null; - } - return out.join('\n'); -} -const indentBy = (text, by) => text.split('\n').map((line, i) => (i === 0 || line === '' ? line : `${' '.repeat(by)}${line}`)).join('\n'); - -/** - * Decide the moves `names` asks for, on `text` (`protocol.ts`), `hostText` - * (`protocol-host.ts`) and `moduleTexts` (hand module basename -> text, read - * through `readModule` when absent). Refuses (exit 2) on every shape the - * section above closes out. Pure. - */ -function planHandHost(T, text, hostText, moduleTexts, names) { - const ctx = handHostContext(T, text); - const { ts, sf, cls, table, scope } = ctx; - if (!names || names.length === 0) refuse('--hand-host needs a comma-separated list of hand-series stub names'); - if (new Set(names).size !== names.length) refuse(`--hand-host names a stub twice: ${names.join(', ')}`); - const entries = hostInterfaceEntries(hostText); - const records = []; - for (const name of names) { - const m = handHostMethod(ts, cls, name); - const why = (msg) => refuse(`${name}: ${msg}`); - const bodyStart = m.body.getStart(sf); - const line1Start = text.indexOf('\n', bodyStart) + 1; - const hit = HAND_STUB_LINE.exec(text.slice(line1Start, text.indexOf('\n', line1Start))); - if (!hit) why('is not a hand-series stub (its body does not open with the hand series\' marker)'); - const file = hit[1]; - const specifier = `./${file.replace(/\.ts$/, '.js')}`; - const mod = moduleTexts.get(file); - if (mod == null) why(`the hand module its marker names, ${file}, is not on disk`); - const stmts = [...m.body.statements]; - const last = stmts.at(-1); - const call = last && ts.isReturnStatement(last) ? last.expression : null; - const callee = call && ts.isCallExpression(call) ? call.expression : null; - if (!callee || !ts.isPropertyAccessExpression(callee) || callee.name.text !== 'call' || !ts.isIdentifier(callee.expression) - || !call.arguments[0] || !ts.isIdentifier(call.arguments[0])) why('the stub does not end in `return fn.call(host, …)`'); - const fn = callee.expression.text; - const hostName = call.arguments[0].text; - const hosts = []; - for (const st of stmts.slice(0, -1)) { - if (!ts.isVariableStatement(st) || !(st.declarationList.flags & ts.NodeFlags.Const)) why('a statement before the call is not a const'); - for (const d of st.declarationList.declarations) { - if (d.initializer && ts.isObjectLiteralExpression(d.initializer)) hosts.push(d); - } - } - if (hosts.length !== 1 || !ts.isIdentifier(hosts[0].name) || hosts[0].name.text !== hostName) why(`the stub builds ${hosts.length} host literal(s), not the one it hands \`${fn}\``); - const fnBinding = scope.bindings.get(fn); - if (!fnBinding || fnBinding.kind !== 'import' || fnBinding.specifier !== specifier || fnBinding.form !== 'named' || fnBinding.imported !== fn) { - why(`${HOST_BASENAME} does not import ${fn} by name from ${specifier}`); - } - const msf = parseSourceFile(join(SRC_DIR, file), mod); - const fnDecl = msf.statements.find((st) => ts.isFunctionDeclaration(st) && st.name?.text === fn && hasModifier(ts, st, ts.SyntaxKind.ExportKeyword)); - if (!fnDecl) why(`${file} exports no function ${fn}`); - const computing = hosts[0].initializer.properties.filter((p) => !isHandForwarder(ts, sf, p)).map((p) => (p.name ? p.name.getText(sf) : p.getText(sf))); - if (computing.length === 0) why('its host literal holds no computing slot: every slot is a hand-series forwarder, so the stub is a delegation already'); - const reads = receiverReads(ts, sf, m, table, false); - if (reads.refusals.length > 0) why(`the receiver form cannot carry its body: ${reads.refusals.join('; ')}`); - if (reads.identity.length > 0) why('it hands a bare `this` on (this pass moves a body that reads the class as `this.` only)'); - const picks = [...reads.self.keys()].sort(); - if (picks.length === 0) why('it reads no member of the class (nothing for the host to carry)'); - const missing = picks.filter((k) => !entries.has(k)); - if (missing.length > 0) why(`it reads ${missing.join(', ')}, which ${HOST_MODULE_BASENAME} carries no entry for (this pass never grows the host)`); - for (const [k, u] of reads.self) if (u.write) why(`it writes this.${k} (a host field entry is read-only here)`); - const names2 = readNames(ts, ctx, m); - const ownRefs = [...names2.moduleRefs.keys()].filter((n) => n !== CLASS_NAME); - if (ownRefs.length > 0) why(`it reads ${ownRefs.join(', ')}, which ${HOST_BASENAME} declares (this pass never widens its exports)`); - const target = handHostName(name); - if (scope.bindings.has(target)) why(`${target} is already a module-scope binding of ${HOST_BASENAME}`); - if (moduleScope(ts, msf).bindings.has(target)) why(`${target} is already a module-scope binding of ${file}`); - const wanted = new Map(); - for (const [local, use] of names2.imports) { - const b = scope.bindings.get(local); - if (b.specifier === specifier) { - if (!moduleScope(ts, msf).bindings.has(b.imported ?? local) || (b.imported ?? local) !== local) why(`it reads ${local} from ${specifier}, which ${file} does not declare under that name`); - continue; - } - wanted.set(local, { specifier: b.specifier, form: b.form, imported: b.imported, value: use.value && !b.typeOnly }); - } - wanted.set('ProtocolHost', { specifier: `./${HOST_MODULE_BASENAME.replace(/\.ts$/, '.js')}`, form: 'named', imported: 'ProtocolHost', value: false }); - const body = text.slice(bodyStart, m.body.getEnd()); - for (const n of [m.body, ...m.parameters, m.type].filter(Boolean)) { - const scan = (x) => { - if ((ts.isTemplateExpression(x) || ts.isNoSubstitutionTemplateLiteral(x) || ts.isStringLiteral(x)) - && sf.getLineAndCharacterOfPosition(x.getStart(sf)).line !== sf.getLineAndCharacterOfPosition(x.getEnd()).line) { - why('it holds a template or string spanning lines, which a re-indent would edit'); - } - ts.forEachChild(x, scan); - }; - scan(n); - } - const moved = outdentBy(body, 4); - if (moved === null || indentBy(moved, 4) !== body) why('its body\'s re-indentation cannot be undone byte for byte (a line under-indented, or one holding only spaces)'); - const paramLines = m.parameters.map((p) => p.getText(sf)); - if (paramLines.some((x) => x.includes('\n'))) why('a parameter spans lines (the function spells one per line)'); - const typeText = m.type ? outdentBy(m.type.getText(sf), 4) : ''; - if (typeText === null) why('its return type\'s re-indentation cannot be undone (a line under-indented)'); - const ret = m.type ? `: ${typeText}` : ''; - const async = hasModifier(ts, m, ts.SyntaxKind.AsyncKeyword) ? 'async ' : ''; - const fnText = `export ${async}function ${target}(\n this: ${pickTypeOf('ProtocolHost', picks)},\n${paramLines.map((x) => ` ${x},\n`).join('')})${ret} ${moved}`; - records.push({ name, m, file, specifier, fn, target, picks, computing, wanted, fnText, stub: handHostStub(file, name, argsOf(m)), doc: handHostDoc(name, fn) }); - } - return { ctx, records }; -} - -/** Apply a `planHandHost` plan. Returns `{ text, modules }` (`protocol.ts`, the hand modules it writes). Pure. */ -function generateHandHost(T, text, moduleTexts, planned) { - const { ts, sf, scope } = planned.ctx; - const order = (s) => scope.importOrder.get(s) ?? Number.MAX_SAFE_INTEGER; - const modules = new Map(); - for (const r of planned.records) { - let mod = modules.get(r.file) ?? moduleTexts.get(r.file); - if (!mod.endsWith('\n')) refuse(`${r.file}: does not end in a line break`); - mod = addModuleImports(ts, r.file, mod, r.wanted, order); - modules.set(r.file, `${mod}\n${r.doc}\n${r.fnText}\n`); - } - let out = applyEdits(text, planned.records.map((r) => ({ start: r.m.body.getStart(sf), end: r.m.body.getEnd(), text: r.stub }))); - const adds = new Map(); - for (const r of planned.records) adds.set(r.target, { specifier: r.specifier, form: 'named', imported: r.target, value: true }); - out = addModuleImports(ts, HOST_BASENAME, out, adds, order); - out = pruneImports(ts, out, usedImportNames(ts, out)).text; - return { text: out, modules }; -} - -/** - * Undo every function a tree carries under this pass's docblock, from its - * texts alone. Returns the undone `protocol.ts` and hand modules, what it - * undid (`{ name, file, fn, text }`), and every way the tree breaks the - * pass's form. - */ -function undoHandHost(T, text, moduleTexts) { - const { ts, hs } = T; - globalTs = ts; - const failures = []; - const moved = []; - const sf = parseSourceFile(HOST_PATH, text); - const cls = hs.classOf(sf, CLASS_NAME); - if (!cls) return { text, modules: moduleTexts, moved, failures: [`no class ${CLASS_NAME} in ${HOST_BASENAME}`] }; - const edits = []; - const modules = new Map(moduleTexts); - const lead = new RegExp(`^\\{\\n {8}// ${HAND_HOST_MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(protocol-[a-z0-9-]+\\.ts)\``); - for (const m of cls.members) { - if (!ts.isMethodDeclaration(m) || !m.body || !m.name || !ts.isIdentifier(m.name)) continue; - const name = m.name.text; - const bodyText = text.slice(m.body.getStart(sf), m.body.getEnd()); - const hit = lead.exec(bodyText); - if (!hit) continue; - const file = hit[1]; - const target = handHostName(name); - if (bodyText !== handHostStub(file, name, argsOf(m))) { failures.push(`${name}: its stub is not the one this pass writes`); continue; } - const mod = modules.get(file); - if (mod == null) { failures.push(`${name}: its stub names ${file}, which is not on disk`); continue; } - const msf = parseSourceFile(join(SRC_DIR, file), mod); - const f = msf.statements.find((st) => ts.isFunctionDeclaration(st) && st.name?.text === target); - if (!f || !f.body) { failures.push(`${name}: ${file} holds no function ${target}`); continue; } - const last = f.body.statements.at(-1); - const callee = last && ts.isReturnStatement(last) && last.expression && ts.isCallExpression(last.expression) ? last.expression.expression : null; - const fn = callee && ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) ? callee.expression.text : null; - const doc = handHostDoc(name, fn ?? '?'); - const fnStart = f.getStart(msf); - const docStart = fnStart - doc.length - 1; - if (!fn || mod.slice(docStart - 2, fnStart) !== `\n\n${doc}\n` || mod.slice(f.getEnd(), f.getEnd() + 1) !== '\n') { - failures.push(`${name}: ${file} holds ${target}, but not under this pass's docblock, a blank line before it and a line break after it`); - continue; - } - const thisType = f.parameters[0] && ts.isIdentifier(f.parameters[0].name) && f.parameters[0].name.text === 'this' ? f.parameters[0].type?.getText(msf) : null; - if (!thisType || !/^Pick$/.test(thisType)) failures.push(`${name}: ${target}'s \`this\` is not a \`Pick\` of ProtocolHost`); - const fBody = mod.slice(f.body.getStart(msf), f.body.getEnd()); - const restored = indentBy(fBody, 4); - if (outdentBy(restored, 4) !== fBody) failures.push(`${name}: ${target}'s body does not re-indent byte for byte`); - edits.push({ start: m.body.getStart(sf), end: m.body.getEnd(), text: restored }); - let undone = mod.slice(0, docStart - 1) + mod.slice(f.getEnd() + 1); - const usedAtHead = usedImportNames(ts, mod); - const unread = importDeclsOf(ts, file, mod).decls.flatMap((d) => [d.defaultName, d.nsName, ...d.named.map((e) => e.local)].filter(Boolean)).filter((k) => !usedAtHead.has(k)); - if (unread.length > 0) failures.push(`${file}: imports what nothing in it reads: ${unread.join(', ')}`); - undone = pruneModuleImports(ts, file, undone); - modules.set(file, undone); - moved.push({ name, file, fn, target, text: fBody }); - } - let out = text; - try { - out = applyEdits(text, edits); - } catch (e) { - if (!(e instanceof CodemodRefusal)) throw e; - failures.push(`${HOST_BASENAME}: the undo's edits overlap`); - } - if (moved.length > 0) { - const targets = new Set(moved.map((x) => x.target)); - const keep = new Set([...moduleScope(ts, parseSourceFile(HOST_PATH, out)).bindings].filter(([k, b]) => b.kind === 'import' && !targets.has(k)).map(([k]) => k)); - out = pruneImports(ts, out, keep).text; - } - return { text: out, modules, moved, failures }; -} - -/** - * The proof: undoing every function in the head lands on the base, - * `protocol.ts` (its import bindings only moved bodies read pruned) and each - * hand module byte for byte, with `protocol-host.ts` untouched; and the pass, - * run again on the undone tree for the stubs it undid, writes the head byte - * for byte. A base this pass has run on is undone the same way first, so a - * later run proves only its own stubs. `base` / `head`: `{ text, host, - * modules }`. - */ -function verifyHandHost(T, base, head) { - const { ts } = T; - const h = undoHandHost(T, head.text, head.modules); - const b = undoHandHost(T, base.text, base.modules); - const failures = [...h.failures, ...b.failures.map((f) => `base: ${f}`)]; - if (head.host !== base.host) failures.push(`${HOST_MODULE_BASENAME} changed (this pass never grows the host)`); - const { text: prunedBase, removed: pruned } = pruneImports(ts, b.text, usedImportNames(ts, head.text)); - const movedText = h.moved.map((x) => x.text).join('\n'); - for (const n of pruned) if (!new RegExp(`\\b${n.replace(/\$/g, '\\$')}\\b`).test(movedText)) failures.push(`${n}: the head no longer imports it, and no moved body reads it`); - if (h.text !== prunedBase) failures.push(`undoing the moves does NOT rebuild the base ${HOST_BASENAME} (first difference at line ${firstDiffLine(h.text, prunedBase)})`); - for (const file of [...new Set([...base.modules.keys(), ...head.modules.keys()])].sort()) { - const bm = b.modules.get(file); const hm = h.modules.get(file); - if (bm == null || hm == null) { failures.push(`${file}: only in the ${bm == null ? 'head' : 'base'}`); continue; } - if (hm !== bm) failures.push(`undoing the moves does NOT rebuild the base ${file} (first difference at line ${firstDiffLine(hm, bm)})`); - } - const baseMoved = new Set(b.moved.map((x) => x.name)); - const moved = h.moved.filter((x) => !baseMoved.has(x.name)); - if (moved.length === 0) failures.push('nothing moved: the head carries no hand-host function its base did not'); - if (failures.length === 0) { - try { - const again = generateHandHost(T, b.text, b.modules, planHandHost(T, b.text, base.host, b.modules, moved.map((x) => x.name))); - const replayed = new Map([...b.modules, ...again.modules]); - if (again.text !== head.text) failures.push(`the pass, run again on the undone tree, does not write the head ${HOST_BASENAME} (first difference at line ${firstDiffLine(again.text, head.text)})`); - for (const [file, t] of replayed) if (head.modules.get(file) !== t) failures.push(`the pass, run again on the undone tree, does not write the head ${file}`); - } catch (e) { - if (!(e instanceof CodemodRefusal)) throw e; - failures.push(`the pass refuses the undone tree: ${e.message}`); - } - } - return { failures, moved, pruned, linesBefore: lineCount(base.text), linesAfter: lineCount(head.text) }; -} - -const firstDiffLine = (a, b) => { - const x = a.split('\n'); const y = b.split('\n'); - let i = 0; - while (i < x.length && i < y.length && x[i] === y[i]) i += 1; - return i + 1; -}; - -/** Every hand module a `protocol.ts` text's hand-series and hand-host markers name, read through `read` (null when absent). */ -function handHostModuleTexts(text, read) { - const files = new Set(); - for (const m of text.matchAll(/\/\/ \[(?:#25467 cut [0-9a-z]+|#30020 codemod)\] The body moved to `(protocol-[a-z0-9-]+\.ts)`/g)) files.add(m[1]); - const out = new Map(); - for (const f of [...files].sort()) { - const t = read(f); - if (t != null) out.set(f, t); - } - return out; -} - -function printVerifyHandHost(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - console.log(`hand host: ${v.moved.length} moved (${v.moved.map((x) => `${x.name} -> ${x.file}#${x.target}`).join(', ') || 'none'}); ${HOST_BASENAME} ${v.linesBefore} -> ${v.linesAfter} lines; ` + - `undoing the moves ${v.failures.length > 0 ? 'does NOT' : 'does'} rebuild the base ${HOST_BASENAME} and its hand modules byte-for-byte ` + - `once the ${v.pruned.length} import binding(s) only moved bodies read are pruned from the base (${v.pruned.join(', ') || 'none'}), ` + - `and the pass re-run on the undone tree ${v.failures.length > 0 ? 'is not checked or does not' : 'does'} write the head`); -} - -/** `--hand-host`: plan, write or re-prove the pass. */ -async function mainHandHost(T, argv) { - const readDisk = (f) => { const p = join(SRC_DIR, f); return existsSync(p) ? readFileSync(p, 'utf8') : null; }; - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--hand-host --verify needs --base '); - const baseText = gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`); - const readAt = (f) => { try { return gitShow(ref, `${SRC_REL}/${f}`); } catch { return null; } }; - const headText = readFileSync(HOST_PATH, 'utf8'); - const files = new Set([...handHostModuleTexts(baseText, () => '').keys(), ...handHostModuleTexts(headText, () => '').keys()]); - const at = (read) => new Map([...files].sort().map((f) => [f, read(f)]).filter(([, t]) => t != null)); - const v = verifyHandHost(T, - { text: baseText, host: gitShow(ref, `${SRC_REL}/${HOST_MODULE_BASENAME}`), modules: at(readAt) }, - { text: headText, host: readFileSync(HOST_MODULE_PATH, 'utf8'), modules: at(readDisk) }); - printVerifyHandHost(v); - return v.failures.length === 0 ? 0 : 1; - } - const j = argv.indexOf('--hand-host'); - const value = argv[j + 1]; - const names = value && !value.startsWith('--') ? value.split(',').map((s) => s.trim()).filter(Boolean) : []; - const text = readFileSync(HOST_PATH, 'utf8'); - const host = readFileSync(HOST_MODULE_PATH, 'utf8'); - const modules = handHostModuleTexts(text, readDisk); - const planned = planHandHost(T, text, host, modules, names); - console.log(`# codemod-split-protocol --hand-host (${HAND_HOST_CARD}): hand stubs run on the class's host`); - for (const r of planned.records) console.log(`- ${r.name} -> ${r.file}#${r.target}: this = Pick; computing slot(s): ${r.computing.join(', ')}`); - const out = generateHandHost(T, text, modules, planned); - const head = { text: out.text, host, modules: new Map([...modules, ...out.modules]) }; - console.log(`output tree sha256: ${treeHash(new Map([[HOST_BASENAME, out.text], ...out.modules]))} (input sha256 ${sha256(text)})`); - const v = verifyHandHost(T, { text, host, modules }, head); - printVerifyHandHost(v); - if (v.failures.length > 0) { - console.error('✗ the generated moves fail their proof: nothing written. Report the fork; never hand-edit the moves.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - writeFileSync(HOST_PATH, out.text); - for (const [file, t] of out.modules) writeFileSync(join(SRC_DIR, file), t); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} hand module(s) under ${SRC_REL}`); - return 0; -} - -// ── Entry ──────────────────────────────────────────────────────────────────── - -const USAGE = [ - 'usage: node scripts/codemod-split-protocol.mjs [--write] plan (or apply) the split of an UNSPLIT protocol.ts', - ' node scripts/codemod-split-protocol.mjs --verify --base REF re-prove a split on disk against protocol.ts at REF', - ' node scripts/codemod-split-protocol.mjs --members A,B [--write] plan (or apply) moving named methods onto the landed facade (#30518)', - ' node scripts/codemod-split-protocol.mjs --members --verify --base REF re-prove those moves on disk against the tree at REF', - ' node scripts/codemod-split-protocol.mjs --hand-host A,B [--write] plan (or apply) running the named hand stubs\' bodies on the class\'s host (#30020)', - ' node scripts/codemod-split-protocol.mjs --hand-host --verify --base REF re-prove those moves on disk against the tree at REF', - ' node scripts/codemod-split-protocol.mjs --self-test', - ' node scripts/codemod-split-protocol.mjs --help', -].join('\n'); - -async function main(argv) { - // Answered before any guard: `--help` reads no tree. - if (argv.includes('--help') || argv.includes('-h')) { - console.log(USAGE); - return 0; - } - if (argv.includes('--self-test')) { - await selfTest(); - if (process.exitCode === 1) return 1; - if (!selfTestReachedVerdict) { - console.error('\n✗ codemod-split-protocol self-test: selfTest() returned without reaching its verdict,\n' + - 'so no success line was printed. Exiting 0 here would report a self-test that never\n' + - 'finished as a self-test that passed.'); - return 1; - } - return 0; - } - const known = new Set(['--write', '--verify', '--base', '--members', '--hand-host']); - for (let i = 0; i < argv.length; i += 1) { - if (argv[i] === '--base') { i += 1; continue; } - if ((argv[i] === '--members' || argv[i] === '--hand-host') && argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) { i += 1; continue; } - if (!known.has(argv[i])) refuse(`unknown argument ${JSON.stringify(argv[i])}\n${USAGE}`); - } - const T = await loadTools(); - if (argv.includes('--members') && argv.includes('--hand-host')) refuse('--members and --hand-host are two passes: run one at a time'); - if (argv.includes('--members')) return mainMembers(T, argv); - if (argv.includes('--hand-host')) return mainHandHost(T, argv); - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--verify needs --base '); - const v = verifyFacade(T, gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), - gitShow(ref, `${SRC_REL}/${HOST_MODULE_BASENAME}`), readFileSync(HOST_MODULE_PATH, 'utf8'), generatedModulesOnDisk()); - printVerify(v); - return v.failures.length === 0 ? 0 : 1; - } - const input = readFileSync(HOST_PATH, 'utf8'); - const hostInput = readFileSync(HOST_MODULE_PATH, 'utf8'); - if (input.includes(MARK)) refuse(`${HOST_BASENAME} already carries ${MARK} stubs: run the script on an unsplit file (re-run on the latest main, never on its own output)`); - const planned = plan(T, input, hostInput); - console.log(planReport(planned)); - const out = lift(T, generate(T, input, hostInput, planned), planned); - console.log(facadeReport(T, out, planned)); - const files = new Map([[HOST_BASENAME, out.host], [HOST_MODULE_BASENAME, out.hostModule], ...out.modules]); - console.log(`output tree sha256: ${treeHash(files)} (input sha256 ${sha256(input)} + ${HOST_MODULE_BASENAME} ${sha256(hostInput)})`); - const v = verifyFacade(T, input, out.host, hostInput, out.hostModule, out.modules); - printVerify(v); - if (v.failures.length > 0) { - console.error('✗ the generated split fails its proof: nothing written. Report the fork; never hand-edit the split.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - for (const [file] of out.modules) { - const p = join(SRC_DIR, file); - if (existsSync(p) && !readFileSync(p, 'utf8').includes(MARK)) refuse(`${file} exists and was not written by this script`); - } - writeFileSync(HOST_PATH, out.host); - writeFileSync(HOST_MODULE_PATH, out.hostModule); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME}, ${HOST_MODULE_BASENAME} and ${out.modules.size} module(s) under ${SRC_REL}`); - return 0; -} - -// ── Self-test ──────────────────────────────────────────────────────────────── -// -// The proofs above are this script's whole value, and a proof that cannot fail -// proves nothing, so the self-test feeds each one an input it must REFUSE. The -// roster pins battery NAMES with a floor each, the roster's own size is pinned, -// and the verdict sets a flag the dispatch reads (AGENTS.md, "Writing a -// `--self-test`"), so a battery that stops running, or a `return` above the -// verdict, cannot read as a pass. - -let selfTestReachedVerdict = false; - -const SELF_TEST_BATTERIES = Object.freeze({ - 'stay rules': 16, - 'host entries': 4, - 'byte-identity proof': 9, - 'determinism': 2, - 'refusals': 6, - 'import prune': 4, - 'facade layer': 10, - 'members pass': 8, - 'members proof': 12, - 'members refusals': 10, - 'receiver forms': 10, - 'receiver proof': 10, - 'receiver refusals': 7, - 'identity port': 14, - 'hand host': 9, - 'hand host refusals': 4, -}); -const SELF_TEST_BATTERY_FLOOR = 5; - -const FIXTURE_ANCHORS = Object.freeze([ - ['engine', 'First', 'protocol-first.ts'], - ['keptOne', 'Kept', null], -]); -const FIXTURE_PINS = Object.freeze({ pinnedMethod: 'a fixture reader' }); -const FIXTURE_NEEDLES = Object.freeze({ 'NEEDLE_TEXT': 'a fixture reader' }); -const fixturePlan = (T, text, hostText = FIXTURE_HOST) => plan(T, text, hostText, - { anchors: FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES }); - -const FIXTURE_HOST = `// fixture host -import type { ObjectStackProtocolImplementation } from './protocol.js'; - -export interface ProtocolHost { - readonly engine: ObjectStackProtocolImplementation['engine']; - readonly flag: ObjectStackProtocolImplementation['flag']; -} -`; - -function fixtureSource(extraMembers = '') { - const pad = Array.from({ length: 6 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - return `import { helperImported } from './other.js'; -import type { Shape } from './types.js'; -import { installProtocolHost, protocolHost } from './protocol-host.js'; -import { already } from './protocol-already.js'; -import { docLinked, onlyMoved } from './moved-only.js'; - -const LOCAL = 1; -function localHelper(n: number): number { - return n + LOCAL; -} - -export class ObjectStackProtocolImplementation { - private engine: any; - private count = 0; - private flag = false; - private static secret(x: number): number { return x; } - protected static guarded(): number { return 1; } - - static { - installProtocolHost((protocol) => ({ - get engine() { return protocol.engine; }, - get flag() { return protocol.flag; }, - })); - } - - /** Docblock that stays. */ - async movable(a: string, b?: number): Promise { -${pad} - const s = helperImported(onlyMoved(a)) as Shape | string; - // a comment the move carries - const t = \`line one -second line at column 0 \${this.count}\`; - return String(s) + t + this.engine.x + ObjectStackProtocolImplementation.secret(b ?? 0) + localHelper(1); - } - - private tiny(): number { - return this.count; - } - - private bareThis(): unknown { -${pad} - return this; - } - - private viaConstructor(): number { -${pad} - return this.constructor.secret(1); - } - - public inferred() { -${pad} - return this.count; - } - - private inferredPrivate() { -${pad} - return this.count; - } - - private readsNoMember(n: number): number { -${pad} - return n; - } - - private destructured({ a }: { a: number }): number { -${pad} - return a; - } - - private shadows(host: number): number { -${pad} - return host; - } - - private alreadyMoved(x: number): number { - // a hand-series stub - return already(protocolHost(this), x); - } - - private localHelper(): number { -${pad} - return 1; - } - - private pinnedMethod(): number { -${pad} - return 3; - } - - private carriesNeedle(): string { -${pad} - return 'NEEDLE_TEXT'; - } - - private readsGuarded(): number { -${pad} - return ObjectStackProtocolImplementation.guarded(); - } - - private whitespaceLine(): number { -${pad} -${' '} - return 1; - } - - private writesCount(): void { -${pad} - this.count = 2; - } - - private writesFlag(): void { -${pad} - this.flag = true; - } - - private isThing(x: unknown): x is string { - return typeof x === 'string'; - } - - /** - * A private member's docblock: it moves with the body. - */ - private ownedDoc(): number { -${pad} - return this.count; - } - - private static readsClass(): number { -${pad} - return ObjectStackProtocolImplementation.secret(1); - } - - /** Stays, and its {@link docLinked} keeps that import in protocol.ts. */ - private readsPredicate(x: unknown): boolean { -${pad} - return this.isThing(x); - } -${extraMembers} - private keptOne(): number { -${pad} - return 2; - } -} -`; -} - -async function selfTest() { - const T = await loadTools(); - const batterySeen = new Map(); - let battery = null; - let failed = 0; - let cases = 0; - const open = (name) => { battery = name; }; - const check = (label, ok, detail = '') => { - batterySeen.set(battery, (batterySeen.get(battery) ?? 0) + 1); - cases += 1; - if (ok) console.log(` ✓ [${battery}] ${label}`); - else { failed += 1; console.error(` ✗ [${battery}] ${label}${detail ? ` — ${detail}` : ''}`); } - }; - const refused = (fn) => { try { fn(); return false; } catch (e) { return e instanceof CodemodRefusal; } }; - - const input = fixtureSource(); - const planned = fixturePlan(T, input); - const out = generate(T, input, FIXTURE_HOST, planned); - - open('stay rules'); - { - const why = (name) => (planned.records.find((r) => r.name === name)?.reasons ?? ['']).join('; '); - const stays = (name, code) => check(`${name} stays (${code})`, why(name).split('; ').some((r) => r.startsWith(code)), why(name)); - const moves = (name, because) => check(`${name} moves (${because})`, why(name) === '', why(name)); - moves('movable', 'the canonical body: a member, a private static, an import, a module-scope helper, a template literal'); - moves('writesCount', 'a field it writes gains a writable host entry'); - moves('tiny', 'a body shorter than its stub: the facade keeps delegations only'); - moves('secret', 'a private static that reads nothing of the class'); - stays('readsClass', 'static-reads-class'); - stays('guarded', 'static-shape'); - stays('bareThis', 'closed-set'); - stays('viaConstructor', 'constructor-rewrite'); - stays('inferred', 'inferred-return-type'); - moves('inferredPrivate', 'a private method\'s inferred return type is not printed in the `.d.ts`'); - stays('readsNoMember', 'no-host-read'); - stays('destructured', 'parameter-shape'); - stays('shadows', 'parameter-shadows'); - stays('alreadyMoved', 'already-moved'); - stays('localHelper', 'name-taken'); - check('a pinned method and a method carrying a needle stay (path-reader)', - why('pinnedMethod').startsWith('path-reader') && why('carriesNeedle').startsWith('path-reader'), - `${why('pinnedMethod')} | ${why('carriesNeedle')}`); - stays('readsGuarded', 'non-public-static'); - stays('whitespaceLine', 'indent-irreversible'); - stays('keptOne', 'section-kept'); - } - - open('host entries'); - { - const why = (name) => (planned.records.find((r) => r.name === name)?.reasons ?? ['']).join('; '); - check('a write to a field the host carries readonly stays (host-entry-conflict)', why('writesFlag').startsWith('host-entry-conflict'), why('writesFlag')); - check('the interface gains the moved bodies\' members, sorted, the written field writable', - /\n {4}count: [^\n]*\n {4}readonly engine:[^\n]*\n {4}readonly flag:[^\n]*\n {4}readonly secret:/.test(out.hostModule), out.hostModule); - check('the factory gains a getter and a setter for the written field and a closure to the private static', - out.host.includes(' get count() { return protocol.count; },\n set count(value) { protocol.count = value; },') - && out.host.includes(' secret: (...a) => ObjectStackProtocolImplementation.secret(...a),')); - check('a move that reaches a type predicate through a new host entry stays (host-entry-predicate)', why('readsPredicate').startsWith('host-entry-predicate'), why('readsPredicate')); - check('an entry the host already carries is not written twice', out.hostModule.split('readonly engine:').length === 2 && out.host.split('get engine()').length === 2); - } - - open('byte-identity proof'); - { - const v = verify(T, input, out.host, FIXTURE_HOST, out.hostModule, out.modules); - check('the generated split proves against its base', v.failures.length === 0 && v.moved.length === 6 && v.checks.length === 5 && v.checks.every((c) => c.ok), - [...v.failures, `moved: ${v.moved.map((m) => m.name).join()}`].join(' | ')); - const mod = out.modules.get('protocol-first.ts'); - const withModule = (text) => new Map([...out.modules, ['protocol-first.ts', text]]); - check('one edited character in a moved body fails', verify(T, input, out.host, FIXTURE_HOST, out.hostModule, withModule(mod.replace('const p3 = 3;', 'const p3 = 4;'))).failures.length > 0); - check('a rewrite pointed at another member fails', verify(T, input, out.host, FIXTURE_HOST, out.hostModule, withModule(mod.replace('host.engine.x', 'host.count.x'))).failures.length > 0); - check('an edited stub signature fails', - verify(T, input, out.host.replace('b?: number): Promise', 'b?: number): Promise'), FIXTURE_HOST, out.hostModule, out.modules).failures.length > 0); - check('an extra top-level statement in a module fails', verify(T, input, out.host, FIXTURE_HOST, out.hostModule, withModule(`${mod}\nexport const extra = 1;\n`)).failures.length > 0); - check('an edited host interface entry fails', - verify(T, input, out.host, FIXTURE_HOST, out.hostModule.replace("readonly flag: ObjectStackProtocolImplementation['flag']", "flag: ObjectStackProtocolImplementation['flag']"), out.modules).failures.length > 0); - check('an edited factory entry the base carried fails', - verify(T, input, out.host.replace('get flag() { return protocol.flag; }', 'get flag() { return !protocol.flag; }'), FIXTURE_HOST, out.hostModule, out.modules).failures.length > 0); - check('an edit elsewhere in protocol.ts fails', verify(T, input, out.host.replace('const LOCAL = 1;', 'const LOCAL = 2;'), FIXTURE_HOST, out.hostModule, out.modules).failures.length > 0); - check('a proof over no moved method fails', verify(T, input, input, FIXTURE_HOST, FIXTURE_HOST, new Map()).failures.length > 0); - } - - open('facade layer'); - { - const lifted = lift(T, out, planned); - const facet = lifted.modules.get('protocol-first.ts') ?? ''; - const vf = (host, modules = lifted.modules) => verifyFacade(T, input, host, FIXTURE_HOST, lifted.hostModule, modules); - const withFacet = (text) => new Map([...lifted.modules, ['protocol-first.ts', text]]); - const v = vf(lifted.host); - check('the facade proves against its base through the unlift', v.failures.length === 0 && v.moved.length === 6 && v.docsMoved === 1, [...v.failures, `moved ${v.moved.length} docs ${v.docsMoved}`].join(' | ')); - check('each section module is one stateless facet class of static methods', - /\nexport class ProtocolFirstFacet \{\n/.test(facet) && !/\nexport (async )?function /.test(facet) && /\n {4}static async movable\(host: /.test(facet), facet.slice(0, 300)); - check('a private member\'s docblock moves; a public member\'s stays on the facade', - facet.includes(' /**\n * A private member\'s docblock: it moves with the body.\n */\n static ownedDoc(') - && lifted.host.includes(' /** Docblock and body: {@link ProtocolFirstFacet.ownedDoc} in `protocol-first.ts` [#29985 codemod]. */\n private ownedDoc(') - && lifted.host.includes(' /** Docblock that stays. */\n async movable(')); - check('a stub delegates to its facet', lifted.host.includes('return ProtocolFirstFacet.movable(protocolHost(this), a, b);') && lifted.host.includes('return ProtocolFirstFacet.secret(x);')); - check('one edited character in a moved docblock fails', vf(lifted.host, withFacet(facet.replace('it moves with the body.', 'it moves with the body!'))).failures.length > 0); - check('a public docblock moved off the facade fails', - vf(lifted.host.replace(' /** Docblock that stays. */\n async movable(', ' /** Docblock and body: {@link ProtocolFirstFacet.movable} in `protocol-first.ts` [#29985 codemod]. */\n async movable('), - withFacet(facet.replace(/ {4}\/\*\* The body of `ObjectStackProtocolImplementation#movable`[^\n]*/, ' /** Docblock that stays. */'))).failures.length > 0); - check('a stub calling another facet fails', vf(lifted.host.replace('return ProtocolFirstFacet.movable(', 'return OtherFacet.movable(')).failures.length > 0); - check('a member of the facet that is not a static method fails', vf(lifted.host, withFacet(facet.replace('export class ProtocolFirstFacet {\n', 'export class ProtocolFirstFacet {\n extra = 1;\n'))).failures.length > 0); - check('a body line the lift did not indent fails', vf(lifted.host, withFacet(facet.replace(' const p3 = 3;', ' const p3 = 3;'))).failures.length > 0); - const again = lift(T, generate(T, input, FIXTURE_HOST, fixturePlan(T, input)), fixturePlan(T, input)); - check('two lifts of one input write byte-identical trees', - treeHash(new Map([['h', again.host], ...again.modules])) === treeHash(new Map([['h', lifted.host], ...lifted.modules]))); - } - - // The members pass (#30518): the fixture split by the first pass is the - // landed facade; three methods the first pass held for an inferred return - // type get theirs spelled, and its facet module is edited by hand the ways - // `main`'s were (a header paragraph, an import, a top-level declaration and - // a facet member nobody moved). - { - const pad = Array.from({ length: 6 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - const extra = ` - public laterReader(n: number) { -${pad} - return laterOnly(n) + docLinked(n) + this.engine.z; - } - - public readsLocal() { -${pad} - return LOCAL + this.engine.w; - } -`; - const src = fixtureSource(extra) - .replace("import type { Shape } from './types.js';\n", "import type { Shape } from './types.js';\nimport { laterOnly } from './later.js';\n") - .replace(' private tiny(): number {', ` public engineReader() {\n${pad}\n return this.engine.y;\n }\n\n private tiny(): number {`); - const firstPlan = fixturePlan(T, src); - const landed = lift(T, generate(T, src, FIXTURE_HOST, firstPlan), firstPlan); - const spelled = landed.host - .replace(' public engineReader() {', ' public engineReader(): number {') - .replace(' public laterReader(n: number) {', ' public laterReader(n: number): number {') - .replace(' public readsLocal() {', ' public readsLocal(): number {'); - const handFacet = (landed.modules.get('protocol-first.ts') ?? '') - .replace('\n *\n * A MOVE, not a redesign.', '\n *\n * [#1] A paragraph a hand wrote after the split.\n *\n * A MOVE, not a redesign.') - .replace("import type { ProtocolHost } from './protocol-host.js';\n", "import { handHelper } from './hand.js';\nimport type { ProtocolHost } from './protocol-host.js';\n\nconst HAND_LOCAL = 1;\n") - .replace(/\n}\n$/, '\n\n /** A member a hand wrote here. */\n static handWritten(): number {\n return handHelper() + HAND_LOCAL;\n }\n}\n'); - const base = { text: spelled, host: landed.hostModule, modules: new Map([['protocol-first.ts', handFacet]]) }; - const opts = { anchors: FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES }; - const gen = (names, b = base) => generateMembers(T, b.text, b.host, b.modules, names, opts); - const out = gen(['laterReader', 'engineReader']); - const head = { text: out.host, host: out.hostModule, modules: new Map([...base.modules, ...out.modules]) }; - const facetText = head.modules.get('protocol-first.ts'); - const vm = (h) => verifyMembers(T, base, h, opts); - const withHead = (patch) => ({ ...head, ...patch }); - const withFacet = (text) => withHead({ modules: new Map([['protocol-first.ts', text]]) }); - - open('members pass'); - { - const v = vm(head); - check('the moves prove against the landed facade by their undo', v.failures.length === 0 && v.moved.join() === 'engineReader,laterReader' && v.checks.every((c) => c.ok), - [...v.failures, `moved ${v.moved.join()}`].join(' | ')); - check('each stub delegates to its facet, signature and docblock unchanged', - out.host.includes(' public engineReader(): number {\n // [#29985 codemod] The body moved to `protocol-first.ts`; it reaches this class through `protocol-host.ts`.\n return ProtocolFirstFacet.engineReader(protocolHost(this));\n }'), out.host); - check('a member goes in class order among the facet\'s members: before the next one, or last', - facetText.indexOf('static engineReader(') < facetText.indexOf('static tiny(') - && facetText.indexOf('static laterReader(') > facetText.indexOf('static handWritten('), facetText); - check('the header\'s first paragraph lists the names in class order; a hand-written paragraph stays', - /`engineReader`,\s*(\n \*\s*)?`tiny`/.test(facetText) && facetText.includes(' * [#1] A paragraph a hand wrote after the split.'), facetText.slice(0, 900)); - check('an import binding the body reads joins the declaration of its specifier, in that declaration\'s layout', - facetText.includes("import { docLinked, onlyMoved } from './moved-only.js';"), facetText.split('\n').filter((l) => l.startsWith('import')).join(' | ')); - check('an import binding of a new specifier is a new declaration ahead of ProtocolHost\'s; a hand-written import stays', - facetText.includes("import { handHelper } from './hand.js';\nimport { laterOnly } from './later.js';\nimport type { ProtocolHost } from './protocol-host.js';")); - check('protocol.ts drops the import only the moved body read, keeps one a staying docblock links', - !/\blaterOnly\b/.test(out.host) && out.host.includes("import { docLinked } from './moved-only.js';") && out.pruned.join() === 'laterOnly', out.pruned.join()); - const again = gen(['engineReader', 'laterReader']); - check('two runs (names in any order) write byte-identical trees', - treeHash(new Map([['h', again.host], ['p', again.hostModule], ...again.modules])) === treeHash(new Map([['h', out.host], ['p', out.hostModule], ...out.modules]))); - } - - open('members proof'); - { - // A mutation that does not land would make its case vacuous: each must change the head. - const same = (a, b) => a.text === b.text && a.host === b.host && a.modules.size === b.modules.size - && [...a.modules].every(([f, t]) => b.modules.get(f) === t); - const fails = (label, h) => { - const v = vm(h); - check(label, (h === base || !same(h, head)) && v.failures.length > 0, same(h, head) ? 'the mutation did not land' : 'proved'); - }; - fails('one edited character in a moved body fails', withFacet(facetText.replace('return laterOnly(n) + docLinked(n) + host.engine.z;', 'return laterOnly(n) + docLinked(n) - host.engine.z;'))); - fails('one edited character in a hand-written facet member fails', withFacet(facetText.replace('return handHelper() + HAND_LOCAL;', 'return handHelper() - HAND_LOCAL;'))); - fails('a second blank line after a moved member fails', withFacet(facetText.replace(/(\n {4}\/\*\* The body of `ObjectStackProtocolImplementation#engineReader`)/, '\n$1'))); - fails('a header that does not list a moved name fails', withFacet(facetText.replace('`engineReader`, ', ''))); - fails('a changed module no moved member is in fails', withHead({ modules: new Map([...head.modules, ['protocol-other.ts', '// not at base\n']]) })); - fails('an edited host interface entry fails', withHead({ host: out.hostModule.replace("readonly flag: ObjectStackProtocolImplementation['flag']", "flag: ObjectStackProtocolImplementation['flag']") })); - fails('a host entry no moved body\'s Pick names fails', withHead({ - host: out.hostModule.replace(" readonly engine:", " readonly zzz: ObjectStackProtocolImplementation['zzz'];\n readonly engine:"), - text: out.host.replace(' get engine()', ' zzz: (...a) => protocol.zzz(...a),\n get engine()'), - })); - fails('a stub calling another facet fails', withHead({ text: out.host.replace('return ProtocolFirstFacet.engineReader(', 'return OtherFacet.engineReader(') })); - fails('an edited docblock on a moved public member fails', withHead({ text: out.host.replace(' public engineReader(): number {', ' /** Hand. */\n public engineReader(): number {') })); - fails('an edit elsewhere in protocol.ts fails', withHead({ text: out.host.replace('const LOCAL = 1;', 'const LOCAL = 2;') })); - fails('a head that drops an import no moved body reads fails', withHead({ text: out.host.replace("import { already } from './protocol-already.js';\n", '') })); - fails('a proof over no moved method fails', base); - } - - open('members refusals'); - { - const refuses = (label, fn) => check(label, refused(fn)); - refuses('an empty list refuses', () => gen([])); - refuses('a name given twice refuses', () => gen(['engineReader', 'engineReader'])); - refuses('a name the class does not declare refuses', () => gen(['nothingLikeThis'])); - refuses('a member already moved refuses', () => gen(['movable'])); - // A bare `this` moves by R1's identity port (#30020) now; an indexed one stays held. - const indexed = base.text.replace(' return this;\n }\n\n private viaConstructor', " return this['count'];\n }\n\n private viaConstructor"); - check('a member a stay rule holds refuses (closed-set: an indexed `this`)', indexed !== base.text && refused(() => gen(['bareThis'], { ...base, text: indexed }))); - refuses('a static refuses (only instance methods move)', () => gen(['secret'])); - refuses('an unsplit protocol.ts refuses (that is the first pass\'s)', () => generateMembers(T, src, FIXTURE_HOST, new Map(), ['engineReader'], opts)); - refuses('a body that reads an unexported top-level name refuses (the export list is not widened)', () => gen(['readsLocal'])); - const handHeader = handFacet.replace(' facet of', ' facet, edited by hand, of'); - check('a hand-edited first header paragraph refuses', handHeader !== handFacet - && refused(() => gen(['engineReader'], { ...base, modules: new Map([['protocol-first.ts', handHeader]]) }))); - refuses('a module that declares a name the body imports refuses', - () => gen(['laterReader'], { ...base, modules: new Map([['protocol-first.ts', handFacet.replace('const HAND_LOCAL = 1;', 'const HAND_LOCAL = 1;\nconst laterOnly = (n: number): number => n;')]]) })); - } - - // The receiver forms (#30147): members E1 refuses move unedited. The landed - // facade gains, by hand, a method with a local named `host` (E1's rewrite - // set refuses it: `receiver`), a private static that reads the class through - // `this` (`statics`), and a static table; the first pass's `readsNoMember` - // (`plain`), `readsClass` (`plain`, reading a static through the forwarder) - // and `readsPredicate` (E1 through a predicate entry) move with them. - { - const rbase = { ...base, text: base.text - .replace(' private keptOne(): number {', ` private static readonly TABLE: ReadonlySet = new Set(['a', 'b']); - - private hostLocal(n: number): number { -${pad} - const host = n; - return host + this.engine.v + (this.flag ? 1 : 0); - } - - private static readsThis(n: number): number { -${pad} - return this.secret(n) + ObjectStackProtocolImplementation.TABLE.size; - } - - private bareStatic(): unknown { -${pad} - return this; - } - - private keptOne(): number {`) }; - const RNAMES = ['hostLocal', 'readsThis', 'readsNoMember', 'readsClass', 'readsPredicate', 'TABLE']; - const rgen = (names, b = rbase) => generateMembers(T, b.text, b.host, b.modules, names, opts); - let rout = null; - try { rout = rgen(RNAMES); } catch (e) { rout = { error: String(e.message ?? e) }; } - const rhead = rout.error ? rbase : { text: rout.host, host: rout.hostModule, modules: new Map([...rbase.modules, ...rout.modules]) }; - const rvm = (h) => verifyMembers(T, rbase, h, opts); - const rv = rout.error ? { failures: [rout.error], moved: [], checks: [], forms: new Map() } : rvm(rhead); - const rfacet = rhead.modules.get('protocol-first.ts') ?? ''; - const leaf = rhead.modules.get('protocol-first-tables.ts') ?? ''; - const formOf = (n) => { const r = (rout.records ?? []).find((x) => x.name === n); return r ? (r.form ?? (r.leaf ? 'table' : undefined)) : undefined; }; - - open('receiver forms'); - { - check('the receiver forms prove against the landed facade by their undo', rv.failures.length === 0 && rv.moved.length === RNAMES.length, - [...rv.failures, `moved ${rv.moved.join()}`].join(' | ')); - check('each member gets its form: receiver, statics, plain, E1 through a predicate entry, and a table', - formOf('hostLocal') === 'receiver' && formOf('readsThis') === 'statics' && formOf('readsNoMember') === 'plain' - && formOf('readsClass') === 'plain' && formOf('readsPredicate') === 'e1' && formOf('TABLE') === 'table' - && JSON.stringify(rv.forms) === JSON.stringify({ plain: 2, e1: 1, receiver: 1, statics: 1, table: 1 }), - `${RNAMES.map((n) => `${n}=${formOf(n)}`).join(' ')} | proof ${JSON.stringify(rv.forms)}`); - check('a receiver stub runs the unedited body on the host; the facet member takes the Pick of what it reads as `this`', - rhead.text.includes('return ProtocolFirstFacet.hostLocal.call(protocolHost(this), n);') - && rfacet.includes("static hostLocal(this: Pick, n: number): number {") - && rfacet.includes(' const host = n;\n return host + this.engine.v + (this.flag ? 1 : 0);'), rfacet); - check('a statics stub runs the unedited body on the forwarder', - rhead.text.includes(`return ProtocolFirstFacet.readsThis.call(${STATICS_NAME}, n);`) - && rfacet.includes(`static readsThis(this: Pick<${STATICS_HOST_NAME}, 'secret'>, n: number): number {`) - && rfacet.includes(' return this.secret(n) + ObjectStackProtocolImplementation.TABLE.size;'), rfacet); - check('a plain stub calls its facet member with no host', - rhead.text.includes('return ProtocolFirstFacet.readsNoMember(n);') && rhead.text.includes('it reads nothing of this class.') - && rhead.text.includes(`it reads this class's statics through \`${STATICS_NAME}\`.`), rhead.text); - check('the forwarder carries each routed static once, by kind, ahead of the class and in its closing static block', - rhead.text.includes(`export interface ${STATICS_HOST_NAME} {\n readonly TABLE: (typeof ${CLASS_NAME})['TABLE'];\n readonly secret: (typeof ${CLASS_NAME})['secret'];\n}`) - && rhead.text.includes(` TABLE: { get: () => ${CLASS_NAME}.TABLE },\n secret: { value: (...args: Parameters) => ${CLASS_NAME}.secret(...args) },`) - && rhead.text.indexOf(`export const ${STATICS_NAME}`) < rhead.text.indexOf(`export class ${CLASS_NAME}`), rhead.text.slice(0, 1600)); - check('the facet module imports the forwarder AS the class, under its note', - rfacet.includes(`${ROUTE_NOTE}\nimport { ${STATICS_NAME} as ${CLASS_NAME} } from './protocol.js';`) - || new RegExp(`${ROUTE_NOTE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\nimport \\{[^}]*\\b${STATICS_NAME} as ${CLASS_NAME}\\b`).test(rfacet), - rfacet.split('\n').filter((l) => l.startsWith('import') || l.startsWith('//')).join(' | ')); - check('a table\'s initializer moves to a leaf that imports no relative module; the field reads it back', - rhead.text.includes(' private static readonly TABLE: ReadonlySet = ProtocolFirstTables.TABLE;') - && leaf.includes(" static readonly TABLE: ReadonlySet = new Set(['a', 'b']);") && !/from '\.\.?\//.test(leaf), leaf); - check('a predicate reached through the host keeps its predicate in the factory entry', - rhead.text.includes(' isThing: (x: unknown): x is string => protocol.isThing(x),'), rhead.text.split('\n').filter((l) => l.includes('isThing')).join(' | ')); - let again = null; - try { again = rgen([...RNAMES].reverse()); } catch { again = null; } - check('two runs (names in any order) write byte-identical trees', again !== null && !rout.error - && treeHash(new Map([['h', again.host], ['p', again.hostModule], ...again.modules])) === treeHash(new Map([['h', rout.host], ['p', rout.hostModule], ...rout.modules]))); - } - - open('receiver proof'); - { - const same = (a, b) => a.text === b.text && a.host === b.host && a.modules.size === b.modules.size - && [...a.modules].every(([f, t]) => b.modules.get(f) === t); - const fails = (label, h) => { - const v = rvm(h); - check(label, !rout.error && !same(h, rhead) && v.failures.length > 0, same(h, rhead) ? 'the mutation did not land' : 'proved'); - }; - const withR = (patch) => ({ ...rhead, ...patch }); - const withRFacet = (text) => withR({ modules: new Map([...rhead.modules, ['protocol-first.ts', text]]) }); - fails('one edited character in a receiver body fails', withRFacet(rfacet.replace('const host = n;', 'const host = -n;'))); - fails('a receiver stub that calls without the host fails', withR({ text: rhead.text.replace('ProtocolFirstFacet.hostLocal.call(protocolHost(this), n)', 'ProtocolFirstFacet.hostLocal.call(this, n)') })); - fails('a statics stub run on the class instead of the forwarder fails', withR({ text: rhead.text.replace(`ProtocolFirstFacet.readsThis.call(${STATICS_NAME}, n)`, `ProtocolFirstFacet.readsThis.call(${CLASS_NAME}, n)`) })); - fails('a widened `this` Pick fails', withRFacet(rfacet.replace("this: Pick", "this: Pick"))); - fails('a forwarder entry no moved body reads fails', withR({ text: rhead.text.replace(` TABLE: { get: () => ${CLASS_NAME}.TABLE },`, ` TABLE: { get: () => ${CLASS_NAME}.TABLE },\n guarded: { value: (...args: Parameters) => ${CLASS_NAME}.guarded(...args) },`) })); - fails('a forwarder method entry turned into a getter fails', withR({ text: rhead.text.replace(` secret: { value: (...args: Parameters) => ${CLASS_NAME}.secret(...args) },`, ` secret: { get: () => ${CLASS_NAME}.secret },`) })); - fails('one edited character in a moved table fails', withR({ modules: new Map([...rhead.modules, ['protocol-first-tables.ts', leaf.replace("new Set(['a', 'b'])", "new Set(['a', 'c'])")]]) })); - fails('a leaf that imports protocol.ts fails', withR({ modules: new Map([...rhead.modules, ['protocol-first-tables.ts', leaf.replace('\nexport class ProtocolFirstTables {', "\nimport { ObjectStackProtocolImplementation } from './protocol.js';\n\nexport class ProtocolFirstTables {")]]) })); - fails('a predicate entry that drops its predicate fails', withR({ text: rhead.text.replace(' isThing: (x: unknown): x is string => protocol.isThing(x),', ' isThing: (...a) => protocol.isThing(...a),') })); - fails('a facet import of the forwarder without its note fails', withRFacet(rfacet.replace(`${ROUTE_NOTE}\n`, ''))); - } - - open('receiver refusals'); - { - const refuses = (label, fn) => check(label, refused(fn)); - const indexedR = rbase.text.replace(` private bareStatic(): unknown {\n${pad}\n return this;`, ` private bareStatic(): unknown {\n${pad}\n return this['flag'];`); - check('an indexed `this` refuses (no receiver form carries it; R1 takes a bare one only)', indexedR !== rbase.text && refused(() => rgen(['bareStatic'], { ...rbase, text: indexedR }))); - refuses('`this.constructor` refuses (constructor-rewrite is not a receiver reason)', () => rgen(['viaConstructor'])); - refuses('a static written through the class refuses (the forwarder is read-only)', - () => rgen(['readsThis'], { ...rbase, text: rbase.text.replace('return this.secret(n) + ObjectStackProtocolImplementation.TABLE.size;', 'ObjectStackProtocolImplementation.TABLE = new Set();\n return this.secret(n);') })); - refuses('a static method read as a value refuses (a forwarder is another function)', - () => rgen(['readsThis'], { ...rbase, text: rbase.text.replace('return this.secret(n) + ObjectStackProtocolImplementation.TABLE.size;', 'const f = ObjectStackProtocolImplementation.secret;\n return f(n);') })); - refuses('a table whose initializer reads a relative import refuses (the leaf imports packages only)', - () => rgen(['TABLE'], { ...rbase, text: rbase.text.replace("new Set(['a', 'b'])", 'new Set([String(already)])') })); - refuses('a receiver read of a field the host carries writable refuses (the entry would differ)', - () => rgen(['hostLocal'], { ...rbase, text: rbase.text.replace('(this.flag ? 1 : 0)', 'this.count') })); - refuses('a table whose initializer reads a top-level name of protocol.ts refuses', - () => rgen(['TABLE'], { ...rbase, text: rbase.text.replace("new Set(['a', 'b'])", 'new Set([String(LOCAL)])') })); - } - - // The identity port (#30020 R1): a bare `this` an instance body hands on - // reads `this.facade`, the host entry the factory fills with the instance. - open('identity port'); - { - const IBODY = ` private bareStatic(): unknown {\n${pad}\n return this;`; - const ibase = { ...rbase, text: rbase.text.replace(IBODY, ` private bareStatic(): unknown {\n${pad}\n` - + ' const self = (this as any).flag ? this : null;\n' - + ' const read = async () => (this as any).engine;\n' - + ' const own = { m() { return this; } };\n' - + ' return [self ?? this, this.engine.v, read, own];') }; - check('the identity fixture lands', ibase.text !== rbase.text); - const igen = (b = ibase) => generateMembers(T, b.text, b.host, b.modules, ['bareStatic'], opts); - let iout = null; - try { iout = igen(); } catch (e) { iout = { error: String(e.message ?? e) }; } - const ihead = iout.error ? ibase : { text: iout.host, host: iout.hostModule, modules: new Map([...ibase.modules, ...iout.modules]) }; - const ivm = (h) => verifyMembers(T, ibase, h, opts); - const iv = iout.error ? { failures: [iout.error], moved: [], forms: {} } : ivm(ihead); - const ifacet = ihead.modules.get('protocol-first.ts') ?? ''; - check('a body that hands `this` on moves in the receiver form and proves by its undo', - iv.failures.length === 0 && iv.moved.join() === 'bareStatic' && JSON.stringify(iv.forms) === JSON.stringify({ receiver: 1 }), [...iv.failures, JSON.stringify(iv.forms)].join(' | ')); - check('each bare `this` reads `this.facade`; an object-literal method keeps its own `this`; `this.` is unedited', - ifacet.includes(' const self = (this.facade as any).flag ? this.facade : null;\n const read = async () => (this.facade as any).engine;\n' - + ' const own = { m() { return this; } };\n return [self ?? this.facade, this.engine.v, read, own];'), ifacet); - check('the facet member takes the port in its Pick, sorted with what it reads', - ifacet.includes("static bareStatic(this: Pick): unknown {"), ifacet); - check('the stub runs the body on the host, as every receiver stub does', - ihead.text.includes('return ProtocolFirstFacet.bareStatic.call(protocolHost(this));'), ihead.text); - check('the interface gains the port typed as the class, and the factory fills it with the instance', - ihead.host.includes(`${FACADE_ENTRY.iface}\n`) && ihead.text.includes(`\n${FACADE_ENTRY.factory}\n`), `${ihead.host}\n${ihead.text}`); - let again = null; - try { again = igen(); } catch { again = null; } - check('two runs write byte-identical trees', again !== null && !iout.error - && treeHash(new Map([['h', again.host], ['p', again.hostModule], ...again.modules])) === treeHash(new Map([['h', iout.host], ['p', iout.hostModule], ...iout.modules]))); - const same = (a, b) => a.text === b.text && a.host === b.host && [...a.modules].every(([f, t]) => b.modules.get(f) === t); - const fails = (label, h) => { - const v = ivm(h); - check(label, !iout.error && !same(h, ihead) && v.failures.length > 0, same(h, ihead) ? 'the mutation did not land' : 'proved'); - }; - const withIFacet = (text) => ({ ...ihead, modules: new Map([...ihead.modules, ['protocol-first.ts', text]]) }); - fails('a `this.facade` the rewrite did not write fails (the undo alone would take it back)', withIFacet(ifacet.replace('this.engine.v, read', 'this.facade.engine.v, read'))); - fails('a rewritten site put back to a bare `this` fails', withIFacet(ifacet.replace('self ?? this.facade', 'self ?? this'))); - fails('a factory port that hands anything but the instance fails', { ...ihead, text: ihead.text.replace(`\n${FACADE_ENTRY.factory}\n`, '\n facade: protocol.engine,\n') }); - const refusesFor = (label, why, text) => { - let msg = ''; - try { igen({ ...ibase, text }); } catch (e) { msg = String(e.message ?? e); } - check(label, text !== ibase.text && why.test(msg), msg || 'not refused'); - }; - refusesFor('a class that declares `facade` refuses (the port would shadow it)', /facade-taken/, - ibase.text.replace(' private flag = false;\n', ' private flag = false;\n private facade = 0;\n')); - refusesFor('a body that already reads `this.facade` refuses (the undo stays the one inverse)', /`this\.facade` names no declared instance member/, - ibase.text.replace('this.engine.v, read', 'this.facade, read')); - refusesFor('a `typeof this` refuses (the type would name the host)', /`typeof this`/, - ibase.text.replace(' const own = {', ' const t: typeof this = this;\n const own = {')); - refusesFor('an indexed `this` beside a bare one refuses', /an indexed `this`/, - ibase.text.replace('this.engine.v, read', "this['engine'], read")); - } - } - } - - // The hand-host pass (#30020): a hand stub whose host literal computes runs - // on the class's host, its body moved whole into its hand module. - open('hand host'); - const HAND_STUB = ` - private handStub(n: number): number { - // [#25467 cut 9] The body moved to \`protocol-hand.ts\` (see \`HandHost\`). - const readEngine = () => this.engine; - const host: ThisParameterType = { - get engine() { return readEngine(); }, - // a computing slot - computed: () => (this.flag ? LIB_VALUE : 0), - }; - return handBody.call(host, n); - } -`; - const HAND_MODULE = `// fixture hand module -import { LIB_OTHER } from './lib-other.js'; - -export function handBody(this: { engine: unknown; computed: () => number }, n: number): number { - return n + this.computed() + LIB_OTHER; -} -`; - const hbase = { - text: fixtureSource(HAND_STUB).replace("import { already } from './protocol-already.js';\n", - "import { already } from './protocol-already.js';\nimport { handBody } from './protocol-hand.js';\nimport { LIB_VALUE } from './lib.js';\n"), - host: FIXTURE_HOST, - modules: new Map([['protocol-hand.ts', HAND_MODULE]]), - }; - const hgen = (b = hbase, names = ['handStub']) => { - const o = generateHandHost(T, b.text, b.modules, planHandHost(T, b.text, b.host, b.modules, names)); - return { text: o.text, host: b.host, modules: new Map([...b.modules, ...o.modules]) }; - }; - { - let hhead = null; - let herr = ''; - try { hhead = hgen(); } catch (e) { herr = String(e.message ?? e); } - const hv = hhead ? verifyHandHost(T, hbase, hhead) : { failures: [herr], moved: [] }; - check('a hand stub whose host computes moves, and proves by its undo and its replay', - hv.failures.length === 0 && hv.moved.map((x) => x.name).join() === 'handStub', hv.failures.join(' | ')); - const hmod = hhead?.modules.get('protocol-hand.ts') ?? ''; - check('the stub is one forwarding call on the host, and protocol.ts imports it beside the hand function', - Boolean(hhead) && hhead.text.includes(' return handStubOnHost.call(protocolHost(this), n);\n }') - && hhead.text.includes("import { handStubOnHost } from './protocol-hand.js';") && !/\bLIB_VALUE\b|\bhandBody\b/.test(hhead.text), hhead?.text.slice(0, 600)); - check('the function takes the Pick of what the body reads and carries the body one level out, unedited', - hmod.includes("export function handStubOnHost(\n this: Pick,\n n: number,\n): number {\n" - + ' // [#25467 cut 9] The body moved to `protocol-hand.ts` (see `HandHost`).\n const readEngine = () => this.engine;\n') - && hmod.includes(' computed: () => (this.flag ? LIB_VALUE : 0),\n };\n return handBody.call(host, n);\n}\n'), hmod); - check('the hand module imports what the body reads from where protocol.ts imports it, and the host type', - hmod.includes("import { LIB_VALUE } from './lib.js';") && hmod.includes("import type { ProtocolHost } from './protocol-host.js';"), hmod); - let again = null; - try { again = hgen(); } catch { again = null; } - check('two runs write byte-identical trees', Boolean(hhead && again) && again.text === hhead.text - && [...again.modules].every(([f, t]) => hhead.modules.get(f) === t)); - const fails = (label, h) => { - const v = hhead ? verifyHandHost(T, hbase, h) : { failures: [] }; - check(label, Boolean(hhead) && v.failures.length > 0, 'proved'); - }; - if (hhead) { - const withMod = (t) => ({ ...hhead, modules: new Map([...hhead.modules, ['protocol-hand.ts', t]]) }); - fails('a moved body edited after the move fails', withMod(hmod.replace('(this.flag ? LIB_VALUE : 0)', '(this.flag ? LIB_VALUE : 1)'))); - fails('a head that keeps an import only the moved body reads fails', - { ...hhead, text: hhead.text.replace("import { handStubOnHost } from './protocol-hand.js';", "import { handStubOnHost } from './protocol-hand.js';\nimport { LIB_VALUE } from './lib.js';") }); - fails('a stub hand-edited after the move fails', { ...hhead, text: hhead.text.replace('handStubOnHost.call(protocolHost(this), n)', 'handStubOnHost.call(protocolHost(this), n + 0)') }); - fails('a host that changed beside the move fails', { ...hhead, host: `${hhead.host}// drift\n` }); - } else { - for (let i = 0; i < 4; i += 1) check('a tampered head fails (no head to tamper)', false, herr); - } - } - - open('hand host refusals'); - { - const refusesFor = (label, why, text, names = ['handStub']) => { - let msg = ''; - try { hgen({ ...hbase, text }, names); } catch (e) { msg = String(e.message ?? e); } - check(label, (text !== hbase.text || names.join() !== 'handStub') && why.test(msg), msg || 'not refused'); - }; - refusesFor('a stub whose slots all forward refuses (it is a delegation already)', /no computing slot/, - hbase.text.replace(' // a computing slot\n computed: () => (this.flag ? LIB_VALUE : 0),\n', '')); - refusesFor('a slot that reads a member the host carries no entry for refuses (the pass never grows the host)', /carries no entry for/, - hbase.text.replace('(this.flag ? LIB_VALUE : 0)', '(this.count ? LIB_VALUE : 0)')); - refusesFor('a slot that hands a bare `this` on refuses', /bare `this`/, - hbase.text.replace('(this.flag ? LIB_VALUE : 0)', '((this as any).flag ? LIB_VALUE : 0)')); - refusesFor('a method that is not a hand-series stub refuses', /not a hand-series stub/, hbase.text, ['tiny']); - } - - open('determinism'); - { - const again = generate(T, input, FIXTURE_HOST, fixturePlan(T, input)); - const tree = (o) => treeHash(new Map([['h', o.host], ['p', o.hostModule], ...o.modules])); - check('two runs on one input write byte-identical trees', tree(out) === tree(again)); - check('the module imports what its bodies read, from where protocol.ts imports it, and nothing else', - /import \{ helperImported \} from '\.\/other\.js';\nimport type \{ Shape \} from '\.\/types\.js';\nimport type \{ ProtocolHost \} from '\.\/protocol-host\.js';\nimport \{ onlyMoved \} from '\.\/moved-only\.js';\nimport \{ localHelper \} from '\.\/protocol\.js';/.test(out.modules.get('protocol-first.ts') ?? '') - && /export \{ localHelper \};/.test(out.host), (out.modules.get('protocol-first.ts') ?? '').split('\n').filter((l) => l.startsWith('import')).join(' | ')); - } - - open('import prune'); - { - check('protocol.ts drops the import only a moved body reads and keeps one a staying docblock links', - out.host.includes("import { docLinked } from './moved-only.js';\n") && !/\bonlyMoved\b/.test(out.host), out.host.slice(0, 400)); - check('the module carries the import protocol.ts dropped', /import \{ onlyMoved \} from '\.\/moved-only\.js';/.test(out.modules.get('protocol-first.ts') ?? '')); - check('a head that also drops an import it still links fails', - verify(T, input, out.host.replace("import { docLinked } from './moved-only.js';\n", ''), FIXTURE_HOST, out.hostModule, out.modules).failures.length > 0); - check('a head that keeps an import only moved bodies read fails', - verify(T, input, out.host.replace("import { docLinked } from './moved-only.js';", "import { docLinked, onlyMoved } from './moved-only.js';"), FIXTURE_HOST, out.hostModule, out.modules).failures.length > 0); - } - - open('refusals'); - { - check('an anchor the class does not declare refuses', refused(() => plan(T, input, FIXTURE_HOST, { anchors: [['engine', 'a', 'protocol-a.ts'], ['gone', 'b', null]], pins: {}, needles: {} }))); - check('anchors out of class order refuse', refused(() => plan(T, input, FIXTURE_HOST, { anchors: [['engine', 'a', 'protocol-a.ts'], ['keptOne', 'b', null], ['movable', 'c', null]], pins: {}, needles: {} }))); - check('anchors that do not start at the first member refuse', refused(() => plan(T, input, FIXTURE_HOST, { anchors: [['movable', 'a', 'protocol-a.ts']], pins: {}, needles: {} }))); - check('a pin naming what the class lacks refuses', refused(() => plan(T, input, FIXTURE_HOST, { anchors: FIXTURE_ANCHORS, pins: { gone: 'x' }, needles: {} }))); - check('a needle the file no longer carries refuses', refused(() => plan(T, input, FIXTURE_HOST, { anchors: FIXTURE_ANCHORS, pins: {}, needles: { 'gone text': 'x' } }))); - check('--help is answered, never refused, whatever protocol.ts holds', (await main(['--help']).catch(() => 2)) === 0); - } - - const declared = Object.keys(SELF_TEST_BATTERIES); - if (declared.length < SELF_TEST_BATTERY_FLOOR) { - failed += 1; - console.error(`✗ self-test floor: ${declared.length} batteries declared, below the pinned ${SELF_TEST_BATTERY_FLOOR}`); - } - for (const [name, count] of batterySeen) { - if (!declared.includes(name)) { failed += 1; console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s) but is not declared`); } - } - for (const name of declared) { - const count = batterySeen.get(name) ?? 0; - if (count < SELF_TEST_BATTERIES[name]) { - failed += 1; - console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s), below its pinned ${SELF_TEST_BATTERIES[name]}`); - } - } - if (failed > 0) { - console.error(`\n✗ codemod-split-protocol self-test: ${failed} failure(s) (cases and floor).`); - process.exitCode = 1; - selfTestReachedVerdict = true; - return; - } - console.log(`\n✓ codemod-split-protocol self-test: ${cases} cases in ${declared.length} batteries pass.`); - selfTestReachedVerdict = true; -} - -if (isEntrypoint(import.meta.url)) { - main(process.argv.slice(2)).then( - (code) => process.exit(code), - (error) => { - if (error instanceof CodemodRefusal) { - console.error(`✗ codemod-split-protocol: ${error.message}`); - process.exit(2); - } - console.error(error); - process.exit(2); - }, - ); -} diff --git a/scripts/codemod-split-sql-driver.mjs b/scripts/codemod-split-sql-driver.mjs deleted file mode 100644 index 687e8d6b0ca..00000000000 --- a/scripts/codemod-split-sql-driver.mjs +++ /dev/null @@ -1,2950 +0,0 @@ -#!/usr/bin/env node -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * codemod-split-sql-driver — put `SqlDriver` in - * `packages/drivers/driver-sql/src/sql-driver.ts` into facade form: move whole - * sections of its method bodies into stateless facet classes, one per section - * module, move the top-level declarations ahead of the class into one leaf - * module, deterministically, and prove the move. - * - * node scripts/codemod-split-sql-driver.mjs # plan: print the section table, write nothing - * node scripts/codemod-split-sql-driver.mjs --write # apply the split, then verify it - * node scripts/codemod-split-sql-driver.mjs --verify --base - * # re-prove a split on disk against sql-driver.ts at - * node scripts/codemod-split-sql-driver.mjs --self-test - * node scripts/codemod-split-sql-driver.mjs --help # this usage, on any tree (split or not) - * - * The input is always an UNSPLIT `sql-driver.ts`: the last one on `main` is - * the parent of the pilot's landing (`git show 21510bba:`). Copy it over - * the file, then run `--write`; `--verify --base 21510bba` re-proves the tree. - * At landing the script runs again on the unsplit text of the latest `main` - * (ruling A on #29465: regenerate, never rebase); while no commit after the - * pilot touches `sql-driver.ts` or a module it generated, that text is - * 21510bba's, which the pilot's `--verify --base 21510bba` on `main` confirms. - * - * ## Why a script, and what it repeats - * - * The hand series that split this file cut by cut (21 cuts) settled the cut - * pattern, and the pilot (#29520, ruling A `6583399215`) applied it to whole - * sections. The facade form (ruling `6624258595` item 1, extended to this file - * by `6632500982`) is the form `engine.ts` (#29986, #30051) and `protocol.ts` - * (#29985) took; this script is the pilot with that layer added, the way - * `scripts/codemod-split-engine.mjs` adds it: - * - * - The method stays on the class with its modifiers and signature - * byte-for-byte, so the published surface keeps its names and an instance - * spy or a subclass override is still the one callers reach. Only `async` - * is dropped from a stub, as every async stub of the series did. - * - The body moves, unedited, into a static method of the same name on the - * section's facet class (`CrudFacet` in `sql-driver-crud.ts`), at the - * class's own indentation, whose `this` is one named host: the `SqlDriver` - * members the body reads, typed AS the class members (`SqlDriver['x']`). - * A private member is reached the same way as a public one: the indexed - * access type names it, and the host factory, inside the class, reads it. - * - Docblock ownership (ruling `6624345766` item 1): a PRIVATE method's - * docblock moves with its body; a public or protected one stays on the - * facade, its contract, and the facet member carries a one-line - * placeholder pointing back to it. - * - The stub is ONE call, `Facet.x.call(xHost.of(this), …)`: the host is one - * object per facet and driver (`HOSTS_MODULE`, built on first use by a - * factory the class's static block installs), in which a method goes as a - * closure that calls it on the driver at call time (the builder factory as - * a bound reference, `BOUND_HOST_METHODS`), a field or accessor as a GETTER - * read when the body reads it, and a field a body assigns with a SETTER. - * - A static the moved bodies read that is not public goes through the host - * module of the class (private-static-through-host, ruling `6624174693`): - * `SqlDriverStatics`, declared ahead of the class and filled by a second - * static block, which a facet module imports AS `SqlDriver`, so the body - * reads `SqlDriver.x` unedited. A static method whose body reads no `this` - * moves like an instance one, its stub calling the facet directly. - * - The state stays on `SqlDriver`; a body that owns state in a way a host - * cannot forward stays on the class, and the facade gate - * (`scripts/check-facade-delegation-only.mjs`) names it as an exception. - * - * Ruling `6591753301` (option A) widened the pattern two ways, and this script - * applies both, as the pilot did: - * - * - (a) A section module may import VALUES from `sql-driver.ts`. A staying - * top-level name a moved body reads is exported for it by one generated - * `export { … }` list (the declaration's own text is not touched), and - * `index.ts` re-exports by name, so none reaches the package. Every such - * use is inside a function body, so the cycle is never read at evaluation. - * - (b) The top-level declarations ahead of the class (`const` / `function` / - * `interface` / `type`) move WHOLE, with the comments above them, into one - * leaf module, `LEAF_MODULE`, in base order. The leaf never imports - * `sql-driver.ts` or a `sql-driver-*` module: a declaration that names the - * class, a seam import or a declaration that stays, stays itself. - * `sql-driver.ts` imports back what it still reads and re-exports, by name, - * every moved declaration it exported, so every importer of - * `./sql-driver.js` (`index.ts`, the hand-series seams, the tests) reads - * what it read. - * - * Sections are read off the class's banners (`SECTION_MODULES`); the members - * above the first banner are the class head (`CLASS_HEAD_SECTION`). The - * package compiles without `noUnusedLocals`, so, unlike `engine.ts`, no import - * is pruned: an import only a moved body reads stays in `sql-driver.ts`, as - * the pilot left them, and the undo needs no recomputed edit. - * - * `check-tenant-chokepoint` reads every `sql-driver-*.ts` module since the - * pilot's ruling, so a body carrying the builder factory or the tenant scope - * moves like any other; its readings must be equal before and after. - * - * ⛔ The moved text is not re-indented and not formatted: the body is the - * method's `{ … }` exactly as it stood, so byte-identity is equality of text, - * not equality after a transform. - * - * ## What stays, and why (each reason is mechanical) - * - * A method stays whole on the class when moving it would change what it does, - * what the published surface says, or what a gate or test that reads - * `sql-driver.ts` BY PATH sees. `STAY_REASONS` lists every reason for a method - * and `TOP_STAY_REASONS` every reason for a top-level declaration; the plan - * prints every one that stayed and why. The reasons that are tables rather - * than rules are `PATH_READER_PINS` (a name whose text a reader extracts from - * `sql-driver.ts` by path), `PATH_READER_NEEDLES` (literal text a reader - * requires to find there) and `CLASS_PATH_READER_NEEDLES` (the same, for a - * reader that also reads the leaf, so only a method carrying it stays). Ruling - * `6597555122` item 3: a reader that can read the new modules gains them in - * its reading list in the same PR instead, and needs no row here. - * - * ## The proof (`--write` runs it on its own output; `--verify` re-runs it) - * - * 1. Byte-identity: every facet member's body, parameters, type parameters - * and return type are the base method's text, exactly; a moved docblock is - * the base method's docblock, exactly, and only a private method's; every - * stub is exactly the one-call stub the generator writes; the host module, - * the statics forwarders and both static blocks are exactly what the - * generator writes for what they name; every leaf declaration is its base - * statement's text with the comments above it, exactly; and undoing all of - * it rebuilds the base `sql-driver.ts` byte-for-byte, so nothing else in it - * moved. The leaf's relative VALUE imports are followed on disk: none may - * reach `sql-driver.ts` or a `sql-driver-*` module. - * 2. The declaration-file bar for the facade form is ruling `6624345766`'s - * PUBLIC SURFACE EQUAL (exported names, public and protected members and - * their printed types; private members may change), a report reading on - * two built dists, never a `scripts/` file (ruling `6441032442` item 3). - * The pilot's `--dts` judged byte-equality after union sorting (ruling - * `6348891160`), which a facade cannot meet by construction (the bundled - * `.d.ts` prints every private member), so this script no longer carries - * it; the PR reports the public-surface reading. - * - * ## Determinism - * - * The input is the text of `sql-driver.ts`. It is parsed in an in-memory - * project (no `node_modules`, no build output, no clock), every collection is - * emitted in source order or sorted, and the output is a pure function of the - * input: two runs on one input write byte-identical trees (the plan prints the - * output tree's sha256). Only the proof's leaf-reach walk reads sibling files. - * - * ts-morph is a root devDependency (`package.json` declares `ts-morph` - * `^28.0.0`), the way the other root scripts take `typescript`, `yaml` or - * `semver`: it is resolved from the root manifest, so a fresh - * `pnpm install --frozen-lockfile` is all this script needs. - * - * Exit codes: 0 done · 1 a proof failed (stop: the generated split is never - * hand-edited to pass) · 2 the script could not run (unknown banner, missing - * prerequisite, bad arguments) · 3 an input does not parse (`ts-parse.mjs`'s - * refusal, which names the parse errors). - */ - -import { createHash } from 'node:crypto'; -import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { createRequire } from 'node:module'; -import { dirname, join, relative, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -import { isEntrypoint } from './invoked-as.mjs'; -import { readSqlDriverSource } from './sql-driver-split-source.mjs'; -import { parseSourceFile } from './ts-parse.mjs'; - -const ROOT = join(fileURLToPath(new URL('.', import.meta.url)), '..'); -const SRC_REL = 'packages/drivers/driver-sql/src'; -const SRC_DIR = join(ROOT, SRC_REL); -const HOST_BASENAME = 'sql-driver.ts'; -const HOST_PATH = join(SRC_DIR, HOST_BASENAME); -const CLASS_NAME = 'SqlDriver'; -const CARD = '#29520'; -const SCRIPT = 'scripts/codemod-split-sql-driver.mjs'; - -/** The marker every generated file and stub carries; `--verify` keys on it. */ -const MARK = `[${CARD} codemod]`; - -/** A generated or hand-series section module of `sql-driver.ts`, by its import specifier. */ -const SEAM_SPECIFIER = /^\.\/sql-driver-[a-z0-9-]+\.js$/; - -/** - * Every banner inside `SqlDriver`, in the file's two spellings - * (`// ====` / `// Title` / `// ====`, and `// ── Title ───`), mapped to the - * module its section's bodies move to. A banner the table does not name stops - * the script (exit 2): a new section is a decision someone writes here, never a - * name the script makes up. `null` keeps the section's methods on the class. - * - * Three titles name a section whose seam module the hand series already wrote - * (`sql-driver-raw-execution.ts`, `sql-driver-transactions.ts`, - * `sql-driver-schema-sync.ts`); the generated module never shares a file with a - * hand-written one, so those three take a `-section` suffix. - */ -const SECTION_MODULES = Object.freeze({ - 'Lifecycle': 'sql-driver-lifecycle.ts', - 'CRUD — IDataDriver core': 'sql-driver-crud.ts', - 'The sequence semantics a second face shares, stated once': 'sql-driver-sequence-semantics.ts', - 'Bulk & Batch Operations': 'sql-driver-bulk-operations.ts', - 'Raw Execution': 'sql-driver-raw-execution-section.ts', - 'Transactions': 'sql-driver-transactions-section.ts', - 'Aggregation': 'sql-driver-aggregation.ts', - 'Distinct': 'sql-driver-distinct.ts', - 'Window Functions': 'sql-driver-window-functions.ts', - 'Query Plan Analysis': 'sql-driver-query-plan.ts', - 'Schema Sync (syncSchema / init)': 'sql-driver-schema-sync-section.ts', - 'Data-lifecycle rotation (ADR-0057 P2)': 'sql-driver-rotation.ts', - 'Deferred schema DDL (#3917)': 'sql-driver-deferred-ddl.ts', - 'Managed-schema drift & reconcile (#2186)': 'sql-driver-managed-drift.ts', - 'Schema Introspection': 'sql-driver-schema-introspection.ts', - 'Internal helpers': 'sql-driver-internal-helpers.ts', - 'Filter helpers': 'sql-driver-filter-helpers.ts', - 'Field mapping': 'sql-driver-field-mapping.ts', - 'Window function builder': 'sql-driver-window-function-builder.ts', - 'Column creation helper': 'sql-driver-column-creation.ts', - 'Database helpers': 'sql-driver-database-helpers.ts', - 'SQLite serialisation': 'sql-driver-sqlite-serialisation.ts', - 'Introspection internals': 'sql-driver-introspection-internals.ts', -}); - -/** - * The members declared above the class's first banner (its fields, the - * constructor, the dialect probes and the logger plumbing) form one more - * section, the class head, named here rather than by a banner because the - * file carries none for it. `null` would keep it on the class. - */ -const CLASS_HEAD_SECTION = Object.freeze(['Class head: dialect probes, logger, configuration', 'sql-driver-class-head.ts']); - -/** - * The leaf the top-level declarations ahead of the class move to, whole - * (lever (b) of ruling `6591753301`). A leaf: it never imports `sql-driver.ts` - * or any `sql-driver-*` module, so it is evaluated before the class and forms - * no cycle with it. - */ -const LEAF_MODULE = 'sql-driver-top-level.ts'; - -/** - * The module that holds each facet's host, one per driver (#30105, the - * facet-host form `engine.ts` took in #30051): a `FacetHost` per facet module, - * built on first use by the factory the class's static block installs and kept - * for the driver's life. It imports types only, so it is evaluated before the - * class whichever module is loaded first, and the class's static block can - * install into it. - */ -const HOSTS_MODULE = 'sql-driver-facet-hosts.ts'; -const HOSTS_CLASS = 'FacetHost'; - -/** - * Names whose text a reader takes out of `sql-driver.ts` BY PATH. Moving it - * would leave that reader reading a stub, or nothing. A class method or a - * top-level declaration of the name stays. Each row names the reader. A row - * naming nothing the file declares stops the script (exit 2), so the table - * cannot rot into names nobody reads. - * - * Empty since #30147: its two rows were `createColumn` and - * `createAuditTimestampColumn`, sliced by four `packages/cli` generate-* pins - * and `scripts/check-keyed-text-bounds.mjs`. Those readers now read `SqlDriver` - * through `scripts/sql-driver-split-source.mjs`, which follows each stub this - * script writes to the body it moved, so the two members move. The table stays - * for the next reader that takes the file's own text. - */ -const PATH_READER_PINS = Object.freeze({ -}); - -/** - * Literal text a reader requires to find in `sql-driver.ts` BY PATH. A class - * method or a top-level declaration whose text carries one stays, so the - * reader still finds it where it looks. Each row names the reader. - * - * A reader that also reads the leaf (`sql-driver-top-level.ts`) has its rows in - * `CLASS_PATH_READER_NEEDLES` below instead: there a top-level declaration - * carrying the text may move, and only a method carrying it stays. - * - * Empty since #30147: its ten rows were the literals the same readers - * required (the id and audit column builders, the media-id width, the keyed - * text arm, the JSON and file-reference arms). They read the joined source, - * leaf included, so `ensureShardTable`, `initObjects` and `varcharColumnChars` - * move, and so do the two top-level declarations that carried a row. - */ -const PATH_READER_NEEDLES = Object.freeze({ -}); - -/** - * Literal text a reader requires to find in `sql-driver.ts` OR the leaf, but - * reads in no section module. A method whose text carries one stays on the - * class; a top-level declaration carrying one moves as any other, because the - * reader reads the leaf it moves to. The same stale-needle refusal applies. - * - * Empty since #30147: its three rows were `sql-driver-compile-refusal-seam.test.ts`'s - * enumeration of the functions that call `unsupportedFilterError` / - * `withheldFilterError` or write the `INVALID_FILTER` code. That test now reads - * every `sql-driver-*.ts` module and names a facet's static `x` as - * `SqlDriver.x` (ruling 6597555122 item 3: the reader gains the new modules in - * the same PR), so `resolveWithheldFilterRefusal` moves. The table stays for - * the next reader of `sql-driver.ts` and the leaf only. - */ -const CLASS_PATH_READER_NEEDLES = Object.freeze({ -}); - -/** - * The `SqlDriver` methods a host hands its body as a BOUND reference - * (`driver.m.bind(driver)`, through a getter) rather than as a closure that - * calls it. Only the builder factory: `check-tenant-chokepoint` refuses a - * `this.getBuilder(...)` call whose result is never bound to a name, and a - * forwarding closure is exactly that shape. The bound reference calls the - * same method on the same driver (a subclass override included); the real - * call, and the binding the gate counts, stay in the moved body, where the - * widened gate reads them. - */ -const BOUND_HOST_METHODS = new Set(['getBuilder']); - -/** - * Fields a moved body may CALL (#30147). A body that calls a field reaches it - * through the host's getter, so the call's receiver becomes the host, not the - * driver (`field-call`). A field whose value never reads its receiver is - * called the same either way; each row names why. A row naming no field of - * the class stops the script (exit 2). - */ -const RECEIVER_FREE_FIELDS = Object.freeze({ - knex: 'a Knex instance is the `function knex(tableName, options)` closure `makeKnex` returns, which reads `knex.context` and never `this`', -}); - -/** - * Non-private methods whose return type the base leaves inferred, each with - * the type the base's declaration output prints for it (`dist/index.d.ts` of - * `@objectstack/driver-sql` built from the base, copied, never read off the - * source by hand) (#30147). The stub on the class carries it written out - * after its parameter list, so the published declaration does not re-infer - * the type through the facet; the facet member keeps the base text, return - * type absent. The public-surface `.d.ts` reading of the PR proves each one - * prints as it did. A row naming no method, or a method the base already - * annotates, stops the script (exit 2). - */ -const EXPLICIT_RETURN_TYPES = Object.freeze({ - applyFilterCondition: 'void', - applyFilters: 'void', - createColumn: 'void', - createDatabase: 'Promise', - ensureDatabaseExists: 'Promise', - getBuilder: 'knex.Knex.QueryBuilder', -}); - -/** - * Get accessors whose bodies move like methods (#30147): the getter stays on - * the class with its signature, its body becomes the one-call stub, and the - * facet member of the same name is the body. Only getters whose bodies the - * facade gate reads as logic are named; a getter that reads one member or - * forwards one call is a delegation as it stands. A row naming no get - * accessor of the class stops the script (exit 2). - */ -const MOVED_ACCESSORS = Object.freeze({ - dateGranularityCapabilities: 'branches on the dialect', - dialectName: 'branches on the dialect', - insertReturnsStoredRows: 'an operator over two dialect probes', - supportsWalJournal: 'a literal answer a subclass overrides', -}); - -/** - * Instance fields whose initializer moves (#30147): the field stays on the - * class with its declared type, and its initializer becomes one call of the - * facet member of the same name, a function whose body returns the base - * initializer's text exactly, typed as the field (`SqlDriver['x']`). An - * instance initializer runs at construction, after every module has been - * evaluated, so the call never meets a facet in its temporal dead zone; a - * STATIC initializer runs while the class itself is evaluated, so none is - * named here. The initializer must read no `this`. A row naming no such field - * stops the script (exit 2). - */ -const MOVED_FIELD_DEFAULTS = Object.freeze({ - logger: 'the default sink: arrow functions over `console`', -}); - -/** - * A parameter default the facade gate reads as data (`'x'`, `-1`, `CONST.X`, - * `{}`, `[]`, `{ a: 1 }`), the gate's own rule: anything else computes. A - * stub whose parameter computes its default is written with the parameter - * optional instead (`nowMs?: number`), and the default stays where the body - * is, so the value the body sees is the one it saw (#30147). - */ -function isDataDefault(tm, e) { - const { Node, SyntaxKind } = tm; - while (Node.isParenthesizedExpression(e) || Node.isAsExpression(e) || Node.isNonNullExpression(e) || Node.isSatisfiesExpression?.(e)) e = e.getExpression(); - const k = e.getKind(); - if ([SyntaxKind.StringLiteral, SyntaxKind.NumericLiteral, SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TrueKeyword, - SyntaxKind.FalseKeyword, SyntaxKind.NullKeyword, SyntaxKind.BigIntLiteral].includes(k)) return true; - if (Node.isPrefixUnaryExpression(e)) return Node.isNumericLiteral(e.getOperand()); - if (Node.isIdentifier(e)) return true; - if (Node.isPropertyAccessExpression(e)) { - let x = e; - while (Node.isPropertyAccessExpression(x)) x = x.getExpression(); - return Node.isIdentifier(x) || x.getKind() === SyntaxKind.ThisKeyword; - } - if (Node.isArrayLiteralExpression(e)) return e.getElements().every((x) => isDataDefault(tm, x)); - if (Node.isObjectLiteralExpression(e)) { - return e.getProperties().every((p) => (Node.isPropertyAssignment(p) && !Node.isComputedPropertyName(p.getNameNode()) && isDataDefault(tm, p.getInitializerOrThrow())) - || (Node.isShorthandPropertyAssignment(p) && !p.getObjectAssignmentInitializer())); - } - return false; -} - -/** - * The parameters of a stub that the stub writes optional (#30147): each - * parameter whose default computes, carries a type annotation, and is - * followed only by optional or defaulted parameters. Returns - * `[{ param, text }]`, `text` being what the stub writes in its place. - */ -function optionalizedParams(tm, m) { - const params = m.getParameters(); - const out = []; - params.forEach((p, i) => { - const init = p.getInitializer(); - if (!init || isDataDefault(tm, init) || !p.getTypeNode() || p.isRestParameter()) return; - if (!params.slice(i + 1).every((q) => q.hasQuestionToken() || q.getInitializer() || q.isRestParameter())) return; - out.push({ param: p, text: `${p.getName()}?: ${p.getTypeNode().getText()}` }); - }); - return out; -} - -/** Every reason a method stays, with the one-line why the plan prints. */ -const STAY_REASONS = Object.freeze({ - 'no-section': 'declared above the first section banner, and the class head maps to no module', - 'section-kept': 'its section maps to no module', - 'static-this': 'a static method whose body reads `this` (the class; a facet static has its own)', - 'static-name-shared': 'a static method whose name an instance member also takes (one facet cannot hold both)', - 'no-body': 'an overload signature or abstract member', - 'generator': 'a generator', - 'overloaded': 'an overloaded method', - 'decorated': 'a decorated method', - 'not-identifier-name': 'a computed, string or #private name', - 'inferred-return-type': 'a non-private method whose return type is inferred (the .d.ts would infer it through the module)', - 'parameter-shape': 'a destructured or `this` parameter (the stub cannot forward it unchanged)', - 'path-reader': 'a reader takes its text out of sql-driver.ts by path (PATH_READER_PINS / PATH_READER_NEEDLES / CLASS_PATH_READER_NEEDLES)', - 'arguments': 'its body reads `arguments`', - 'super': 'its body reads `super`', - 'new-target': 'its body reads `new.target`', - 'this-type': 'it names the polymorphic `this` type', - 'bare-this': 'it uses `this` other than as `this.member`', - 'unknown-member': 'it reads a `this.member` the class does not declare', - 'this-write': 'it assigns a `this.member` that is not a field, or deletes one (the host carries a setter for a field only)', - 'method-as-value': 'it reads a method as a value instead of calling it', - 'field-call': 'it calls a field or accessor as a function (the host would change its receiver)', - 'overloaded-host-method': 'it calls an overloaded method (the host closure cannot be typed)', - 'static-write': 'its static reads go through SqlDriverStatics and it assigns a static (the forwarder is read-only)', - 'static-as-value': 'its static reads go through SqlDriverStatics and it reads a static method as a value (a forwarder is another function)', - 'static-field-call': 'its static reads go through SqlDriverStatics and it calls a static field or accessor (the receiver would change)', - 'overloaded-static': 'its static reads go through SqlDriverStatics and it calls an overloaded static (one forwarder cannot carry the overloads)', - 'static-route-conflict': 'its facet module reads the statics through SqlDriverStatics, imported AS `SqlDriver`, and it names `SqlDriver` other than as `SqlDriver.`', - 'module-write': 'it assigns a module-scope binding of sql-driver.ts (an import is read-only)', - 'already-moved': 'its body is already a hand-series seam stub', - 'parameter-shadows': 'a parameter shadows a name its one-call stub reads (its facet class or its facet\'s host)', -}); - -/** Every reason a top-level declaration ahead of the class stays in sql-driver.ts. */ -const TOP_STAY_REASONS = Object.freeze({ - 'top-kind': 'not a const / function / interface / type declaration of plain names', - 'merged-declaration': 'its name is declared by more than one statement (an overload set or a merged declaration)', - 'path-reader': 'a reader takes its text out of sql-driver.ts by path (PATH_READER_PINS / PATH_READER_NEEDLES)', - 'class-reference': 'it names a class sql-driver.ts declares (the leaf would import sql-driver.ts back)', - 'seam-import': 'it uses an import from a sql-driver-* module (the leaf would reach sql-driver.ts back through it)', - 'needs-stayer': 'it names a declaration that stays (the leaf would import sql-driver.ts back)', -}); - -// ── Loading ts-morph ───────────────────────────────────────────────────────── - -let tsMorph = null; - -/** ts-morph from the root manifest's devDependencies; a missing install is exit 2, never a stack trace. */ -async function loadTsMorph() { - if (tsMorph) return tsMorph; - const manifest = join(ROOT, 'package.json'); - try { - const resolved = createRequire(manifest).resolve('ts-morph'); - const mod = await import(pathToFileURL(resolved).href); - tsMorph = mod.default ?? mod; - return tsMorph; - } catch (error) { - console.error( - `✗ codemod-split-sql-driver: PREREQUISITE NOT MET — ts-morph does not resolve from ${manifest} ` + - `(${error && error.code ? error.code : 'error'}). Run \`pnpm install\` in this worktree.`, - ); - process.exit(2); - } -} - -/** - * One in-memory project per parse: no file system, no lib, no build output. - * The text goes through `ts-parse.mjs`'s checked parse first, which refuses a - * source with parse errors (its exit 3) instead of handing back a recovered - * partial tree; ts-morph then reads the same text, already vouched for. - */ -function parse(tm, fileName, text) { - parseSourceFile(fileName, text); - const project = new tm.Project({ - useInMemoryFileSystem: true, - compilerOptions: { target: tm.ts.ScriptTarget.ES2020, strict: true, noLib: true, allowJs: false }, - }); - project.getFileSystem().writeFileSync(fileName, text); - return project.addSourceFileAtPath(fileName); -} - -/** A reason the script cannot run at all (exit 2) — never a verdict on the split. */ -class CodemodRefusal extends Error {} - -function refuse(message) { - throw new CodemodRefusal(message); -} - -// ── Reading the sections ───────────────────────────────────────────────────── - -/** Banner lines inside the class body: `{ line, title }`, 1-based, in order. */ -function readBanners(lines, fromLine, toLine) { - const banners = []; - for (let i = fromLine; i < toLine; i += 1) { - const line = lines[i - 1]; - const rule = /^ {2}\/\/ ={3,}$/; - if (rule.test(line) && i + 2 <= toLine && rule.test(lines[i + 1])) { - const m = /^ {2}\/\/ (\S.*)$/.exec(lines[i]); - if (m) { - banners.push({ line: i, title: m[1].trim() }); - i += 2; - continue; - } - } - const dash = /^ {2}\/\/ ── (.+?) ─+$/.exec(line); - if (dash) banners.push({ line: i, title: dash[1].trim() }); - } - return banners; -} - -/** - * Each member's section: the last banner above it, or the class head above - * the first banner. Refuses a banner `sections` does not name. Returns a - * function from a member node to its `[title, module]` row (the module `null` - * when the section stays on the class), or null when `head` is null and the - * member is above the first banner. - */ -function readSections(text, cls, sections, head) { - const banners = readBanners(text.split('\n'), cls.getStartLineNumber(), cls.getEndLineNumber()); - const unknown = banners.filter((b) => !Object.prototype.hasOwnProperty.call(sections, b.title)); - if (unknown.length > 0) { - refuse(`banner(s) the section table does not name: ${unknown.map((b) => `"${b.title}" (line ${b.line})`).join(', ')}. ` + - 'Add each to SECTION_MODULES (a module name, or null to keep the section on the class).'); - } - return (member) => { - const startLine = member.getStartLineNumber(true); - let banner = null; - for (const b of banners) if (b.line < startLine) banner = b; - if (!banner) return head; - return [banner.title, sections[banner.title]]; - }; -} - -// ── Analysis ───────────────────────────────────────────────────────────────── - -/** The names sql-driver.ts binds at module scope, and which of them it exports. */ -function moduleScope(tm, sf) { - const { Node } = tm; - const bindings = new Map(); // name -> { kind: 'import' | 'local', specifier?, form?, imported?, typeOnly? } - const exported = new Set(); - const importOrder = new Map(); // specifier -> first position among the import declarations - for (const st of sf.getStatements()) { - if (Node.isImportDeclaration(st)) { - const specifier = st.getModuleSpecifierValue(); - const order = importOrder.has(specifier) ? importOrder.get(specifier) : importOrder.size; - importOrder.set(specifier, order); - const declTypeOnly = st.isTypeOnly(); - const def = st.getDefaultImport(); - if (def) bindings.set(def.getText(), { kind: 'import', specifier, form: 'default', typeOnly: declTypeOnly }); - const ns = st.getNamespaceImport(); - if (ns) bindings.set(ns.getText(), { kind: 'import', specifier, form: 'namespace', typeOnly: declTypeOnly }); - for (const spec of st.getNamedImports()) { - bindings.set((spec.getAliasNode() ?? spec.getNameNode()).getText(), { - kind: 'import', specifier, form: 'named', imported: spec.getNameNode().getText(), - typeOnly: declTypeOnly || spec.isTypeOnly(), - }); - } - continue; - } - if (Node.isExportDeclaration(st)) { - if (!st.getModuleSpecifier()) for (const spec of st.getNamedExports()) exported.add(spec.getNameNode().getText()); - continue; - } - const isExported = Node.isExportable(st) && st.isExported(); - const names = []; - if (Node.isVariableStatement(st)) { - for (const decl of st.getDeclarations()) { - for (const id of [decl.getNameNode(), ...decl.getNameNode().getDescendantsOfKind(tm.SyntaxKind.Identifier)]) { - if (Node.isIdentifier(id)) names.push(id.getText()); - } - } - } else if (typeof st.getName === 'function' && st.getName()) { - names.push(st.getName()); - } - for (const name of names) { - bindings.set(name, { kind: 'local' }); - if (isExported) exported.add(name); - } - } - return { bindings, exported, importOrder }; -} - -/** Is `node` inside a type node, below `stop`? */ -function inTypePosition(tm, node, stop) { - for (let n = node.getParent(); n && n !== stop; n = n.getParent()) { - if (tm.ts.isTypeNode(n.compilerNode)) return true; - } - return false; -} - -/** The node that binds the `this` a `this` keyword at `node` reads. */ -function thisContainer(tm, node) { - const { Node } = tm; - for (let n = node.getParent(); n; n = n.getParent()) { - if ( - Node.isFunctionDeclaration(n) || Node.isFunctionExpression(n) || Node.isMethodDeclaration(n) || - Node.isConstructorDeclaration(n) || Node.isGetAccessorDeclaration(n) || Node.isSetAccessorDeclaration(n) || - Node.isClassDeclaration(n) || Node.isClassExpression(n) || Node.isClassStaticBlockDeclaration(n) - ) return n; - } - return null; -} - -/** Is the property access `pa` written (assigned, updated, deleted, destructured into)? */ -function isWritten(tm, pa) { - const { Node, SyntaxKind } = tm; - let target = pa; - for (let p = target.getParent(); p; target = p, p = p.getParent()) { - if ( - Node.isParenthesizedExpression(p) || Node.isArrayLiteralExpression(p) || Node.isObjectLiteralExpression(p) || - Node.isPropertyAssignment(p) || Node.isShorthandPropertyAssignment(p) || Node.isSpreadElement(p) || - Node.isSpreadAssignment(p) - ) continue; - break; - } - const parent = target.getParent(); - if (!parent) return false; - if (Node.isBinaryExpression(parent) && parent.getLeft() === target) { - const op = parent.getOperatorToken().getKind(); - return op >= SyntaxKind.FirstAssignment && op <= SyntaxKind.LastAssignment; - } - if (target === pa && (Node.isPrefixUnaryExpression(parent) || Node.isPostfixUnaryExpression(parent))) { - const op = parent.getOperatorToken(); - return op === SyntaxKind.PlusPlusToken || op === SyntaxKind.MinusMinusToken; - } - if (target === pa && Node.isDeleteExpression(parent)) return true; - if ((Node.isForOfStatement(parent) || Node.isForInStatement(parent)) && parent.getInitializer() === target) return true; - return false; -} - -/** The class's instance members by name: `{ kind: 'method' | 'field' | 'getter' | 'setter', overloaded }`. */ -function instanceMembers(tm, cls) { - const { Node } = tm; - const members = new Map(); - const note = (name, kind, extra = {}) => { - const prev = members.get(name); - if (prev && prev.kind === 'setter' && kind === 'getter') { members.set(name, { kind: 'getter', ...extra }); return; } - if (prev && prev.kind === 'getter' && kind === 'setter') return; - members.set(name, { kind, ...extra }); - }; - for (const m of cls.getMembers()) { - if (Node.isConstructorDeclaration(m)) { - for (const p of m.getParameters()) if (p.isParameterProperty()) note(p.getName(), 'field'); - continue; - } - if (typeof m.isStatic === 'function' && m.isStatic()) continue; - const nameNode = typeof m.getNameNode === 'function' ? m.getNameNode() : null; - if (!nameNode || !Node.isIdentifier(nameNode)) continue; - const name = nameNode.getText(); - if (Node.isMethodDeclaration(m)) note(name, 'method', { overloaded: m.getOverloads().length > 0 }); - else if (Node.isPropertyDeclaration(m)) note(name, 'field'); - else if (Node.isGetAccessorDeclaration(m)) note(name, 'getter'); - else if (Node.isSetAccessorDeclaration(m)) note(name, 'setter'); - } - return members; -} - -/** - * Read one method: why it must stay (empty = it moves), what its body reads - * through the host, and which imports its module needs. - */ -function readMethod(tm, ctx, m) { - const { Node, SyntaxKind } = tm; - const reasons = []; - const add = (code, detail) => { - const tag = detail ? `${code}: ${detail}` : code; - if (!reasons.includes(tag)) reasons.push(tag); - }; - const host = new Map(); // member -> 'method' | 'getter' - const writes = new Set(); // fields the body assigns: the host carries a setter for each - const imports = new Map(); // local -> { value } - const moduleRefs = new Map(); // sql-driver.ts top-level name -> { value } - // The private-static-through-host rule: the statics the body reads as - // `SqlDriver.x`, whether one is non-public (that takes the route), what the - // route cannot carry, and whether the body names `SqlDriver` any other way. - const classStatics = new Map(); // static -> 'method' | 'getter' - const routeBlockers = []; - let readsNonPublicStatic = false; - let classOther = false; - let rawParams = null; - const result = () => ({ reasons, host, writes, imports, moduleRefs, classStatics, routeBlockers, readsNonPublicStatic, classOther, rawParams }); - - if (m.isStatic() && ctx.members.has(m.getName())) add('static-name-shared'); - if (!m.getBody()) add('no-body'); - if (m.isAbstract && m.isAbstract()) add('no-body'); - if (typeof m.isGenerator === 'function' && m.isGenerator()) add('generator'); - if (typeof m.getOverloads === 'function' && m.getOverloads().length > 0) add('overloaded'); - if (m.getDecorators().length > 0) add('decorated'); - const nameNode = m.getNameNode(); - if (!Node.isIdentifier(nameNode)) { add('not-identifier-name'); return result(); } - const name = nameNode.getText(); - if (!m.getReturnTypeNode() && m.getScope() !== 'private' && !Object.hasOwn(ctx.returnTypes, name)) add('inferred-return-type'); - for (const p of m.getParameters()) { - // A defaulted identifier forwards as it is: the stub keeps the default and - // hands the body the value it produced. - if (!Node.isIdentifier(p.getNameNode()) || p.getName() === 'this') add('parameter-shape', p.getName()); - } - const body = m.getBody(); - if (!body) return result(); - - // A comment between the parentheses that no parameter's own text carries: - // the facet member then takes the base's parameter list verbatim, comments - // and line breaks included (#30147), instead of one parameter after another. - const params = m.getParameters(); - rawParams = commentInParameters(tm, m) ? parameterListText(tm, m) : null; - - const methodText = m.getText(); - for (const needle of Object.keys(ctx.needles)) if (methodText.includes(needle)) add('path-reader', JSON.stringify(needle)); - for (const needle of Object.keys(ctx.classNeedles)) if (methodText.includes(needle)) add('path-reader', JSON.stringify(needle)); - if (Object.prototype.hasOwnProperty.call(ctx.pins, name)) add('path-reader', name); - - const regions = [...typeParamsOf(m), ...params, m.getReturnTypeNode(), body].filter(Boolean); - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - for (const region of regions) { - const nodes = [region, ...region.getDescendants()]; - for (const node of nodes) { - const kind = node.getKind(); - if (kind === SyntaxKind.SuperKeyword) add('super'); - if (kind === SyntaxKind.ThisType) add('this-type'); - if (Node.isMetaProperty(node) && node.getKeywordToken() === SyntaxKind.NewKeyword) add('new-target'); - if (kind === SyntaxKind.ThisKeyword) { - if (thisContainer(tm, node) !== m) continue; - if (m.isStatic()) { add('static-this'); continue; } - const parent = node.getParent(); - if (!Node.isPropertyAccessExpression(parent) || parent.getExpression() !== node) { add('bare-this'); continue; } - const memberNameNode = parent.getNameNode(); - if (!Node.isIdentifier(memberNameNode)) { add('bare-this'); continue; } - const member = memberNameNode.getText(); - const info = ctx.members.get(member); - if (!info) { add('unknown-member', member); continue; } - if (isWritten(tm, parent)) { - // A field is written through a host setter; a method, an accessor or - // a `delete` cannot be. - if (info.kind === 'field' && !Node.isDeleteExpression(parent.getParent())) writes.add(member); - else add('this-write', member); - } - const outer = parent.getParent(); - const called = Node.isCallExpression(outer) && outer.getExpression() === parent; - if (info.kind === 'method') { - if (!called) add('method-as-value', member); - if (info.overloaded) add('overloaded-host-method', member); - host.set(member, 'method'); - } else if (info.kind === 'setter') { - add('this-write', member); - } else { - if (called && !Object.hasOwn(ctx.receiverFree, member)) add('field-call', member); - host.set(member, 'getter'); - } - continue; - } - if (kind !== SyntaxKind.Identifier) continue; - if (node.getText() === 'arguments') { - const parent = node.getParent(); - const isName = Node.isPropertyAccessExpression(parent) && parent.getNameNode() === node; - if (!isName) add('arguments'); - } - const parent = node.getParent(); - let symbol; - if (Node.isShorthandPropertyAssignment(parent) && parent.getNameNode() === node) { - symbol = checker.getShorthandAssignmentValueSymbol(parent.compilerNode); - } else { - symbol = checker.getSymbolAtLocation(node.compilerNode); - } - if (!symbol || !symbol.declarations) continue; - for (const decl of symbol.declarations) { - if (decl.getSourceFile() !== ctx.sf.compilerNode) continue; - const ts = tm.ts; - const typePos = inTypePosition(tm, node, m); - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const local = node.getText(); - const prev = imports.get(local); - imports.set(local, { value: Boolean(prev && prev.value) || !typePos }); - continue; - } - if (!isModuleScopeDecl(ts, decl)) continue; - // Lever (a) of ruling 6591753301: a module-scope name is imported — - // from the leaf when it moved there, from `sql-driver.ts` (exported - // for it) when it stayed. Two things a module function cannot do: - // reach a non-public static of the class, and assign an import. - const declName = decl.name && ts.isIdentifier(decl.name) ? decl.name.text : node.getText(); - if (ts.isClassDeclaration(decl) && declName === CLASS_NAME) { - const access = node.getParent(); - const info = !typePos && Node.isPropertyAccessExpression(access) && access.getExpression() === node - ? ctx.statics.get(access.getName()) : null; - if (info) { - const member = access.getName(); - if (info.scope !== 'public') readsNonPublicStatic = true; - const outer = access.getParent(); - const called = Node.isCallExpression(outer) && outer.getExpression() === access; - const block = (tag) => { if (!routeBlockers.includes(tag)) routeBlockers.push(tag); }; - if (isWritten(tm, access) || info.kind === 'setter') block(`static-write: ${member}`); - if (info.kind === 'method' && !called) block(`static-as-value: ${member}`); - if (info.kind === 'method' && info.overloaded) block(`overloaded-static: ${member}`); - if (info.kind !== 'method' && called) block(`static-field-call: ${member}`); - classStatics.set(member, info.kind === 'method' ? 'method' : 'getter'); - } else { - classOther = true; - } - } - if (!typePos && isWritten(tm, node)) add('module-write', declName); - const prev = moduleRefs.get(declName); - moduleRefs.set(declName, { value: Boolean(prev && prev.value) || !typePos }); - } - } - } - - const binding = ctx.scope.bindings.get(name); - if (binding && binding.kind === 'import' && SEAM_SPECIFIER.test(binding.specifier)) add('already-moved', binding.specifier); - // A body that reads a non-public static takes the route; what the route - // cannot carry keeps it on the class. (A module another mover routes - // applies the same to every mover in it: `plan`.) - if (readsNonPublicStatic) { - for (const tag of routeBlockers) add(tag); - if (classOther) add('static-route-conflict'); - } - return result(); -} - -function isModuleScopeDecl(ts, decl) { - if (ts.isVariableDeclaration(decl)) { - const statement = decl.parent && decl.parent.parent; - return Boolean(statement && ts.isVariableStatement(statement) && ts.isSourceFile(statement.parent)); - } - if (ts.isBindingElement(decl)) { - let n = decl; - while (n && !ts.isVariableDeclaration(n)) n = n.parent; - return Boolean(n && isModuleScopeDecl(ts, n)); - } - return Boolean(decl.parent && ts.isSourceFile(decl.parent)) && - (ts.isFunctionDeclaration(decl) || ts.isClassDeclaration(decl) || ts.isInterfaceDeclaration(decl) || - ts.isTypeAliasDeclaration(decl) || ts.isEnumDeclaration(decl) || ts.isModuleDeclaration(decl)); -} - -// ── The plan ───────────────────────────────────────────────────────────────── - -/** `sql-driver-transactions-section.ts` -> `TransactionsSectionHost`. */ -function hostNameOf(moduleFile) { - const slug = moduleFile.replace(/^sql-driver-/, '').replace(/\.ts$/, ''); - return `${slug.split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join('')}Host`; -} - -/** `sql-driver-transactions-section.ts` -> `TransactionsSectionFacet`: the stateless class the bodies move into. */ -function facetNameOf(moduleFile) { - return hostNameOf(moduleFile).replace(/Host$/, 'Facet'); -} - -/** `sql-driver-transactions-section.ts` -> `transactionsSectionHost`: the module's `FacetHost` in `HOSTS_MODULE`. */ -function hostVarOf(moduleFile) { - const name = hostNameOf(moduleFile); - return `${name[0].toLowerCase()}${name.slice(1)}`; -} - -/** The object the class fills with forwarders to the statics the facets read, and its type. */ -const STATICS_NAME = `${CLASS_NAME}Statics`; -const STATICS_HOST_NAME = `${CLASS_NAME}StaticsHost`; -/** How a routed facet module names the class as a type: `SqlDriver` there is `SqlDriverStatics`. */ -const CLASS_TYPE_ALIAS = `${CLASS_NAME}Class`; - -/** The placeholder above a moved public or protected body: its docblock stays on the class. */ -const placeholderDoc = (name) => `/** The body of \`${CLASS_NAME}#${name}\`; the method's docblock there is its contract. */`; -const fieldDefaultDoc = (name) => `/** The initializer of \`${CLASS_NAME}#${name}\`; the field's declaration there is its contract. */`; -/** A member's type parameters; an accessor has none. */ -const typeParamsOf = (m) => (typeof m.getTypeParameters === 'function' ? m.getTypeParameters() : []); - -/** - * The statics block `sql-driver.ts` carries for the routed facets: the type and - * the object ahead of the class, and the static block at the end of the class - * that fills the object. `kinds` maps each routed static to `method` (a - * forwarder that calls it on the class) or `getter` (read when read). Pure: - * `verify` rebuilds both texts from the base class and compares them. - */ -function staticsTexts(kinds) { - const members = [...kinds.keys()].sort(); - const ahead = [ - `// ${MARK} The statics of \`${CLASS_NAME}\` its facet modules read, private ones included, as`, - `// the class declares them (an indexed access on the class). The static block at the end of`, - `// the class fills \`${STATICS_NAME}\` with forwarders: a method is called on the class at`, - '// call time, a field or accessor is read when the body reads it. A facet module imports', - `// \`${STATICS_NAME}\` AS \`${CLASS_NAME}\`, so each moved body reads \`${CLASS_NAME}.x\` unedited;`, - '// `index.ts` re-exports neither, so neither reaches the package.', - `export interface ${STATICS_HOST_NAME} {`, - ...members.map((n) => ` readonly ${n}: (typeof ${CLASS_NAME})['${n}'];`), - '}', - `export const ${STATICS_NAME} = {} as ${STATICS_HOST_NAME};`, - ].join('\n'); - const block = [ - ` // ${MARK} Fills \`${STATICS_NAME}\` (declared above the class) for the facet modules.`, - ' static {', - ` Object.defineProperties(${STATICS_NAME}, {`, - ...members.map((n) => (kinds.get(n) === 'method' - ? ` ${n}: { value: (...args: Parameters) => ${CLASS_NAME}.${n}(...args) },` - : ` ${n}: { get: () => ${CLASS_NAME}.${n} },`)), - ' });', - ' }', - ].join('\n'); - return { ahead, block }; -} - -/** - * The facet hosts (#30105): `HOSTS_MODULE`'s text, and the static block at the - * end of the class that installs one host factory per facet into it. `facets` - * lists each facet module whose bodies read the class, with `members` (member - * -> `method` | `getter`, the union over its bodies) and `written` (the fields - * a body assigns). The host is the module's whole `
Host`, so every - * stub of the facet hands its body the same object, which carries every - * member any body of the facet reads (a `Pick` of it is what each body's - * `this` names). Each member forwards as the per-call literal did: a method - * as a closure that calls it on the driver at call time, a field or accessor - * as a getter read when the body reads it, a written field with a setter that - * assigns it on the driver. So a spy or subclass override installed after the - * host was built is still the one reached, and the only thing a body can tell - * apart is that two calls see the same host object, which no moved body can - * observe: a body that reads `this` bare stays on the class (`bare-this`). - * Pure: `verify` rebuilds both texts from the head's host interfaces and the - * base class, and compares them. - */ -function hostsTexts(facets) { - const sorted = [...facets].sort((a, b) => (a.moduleFile < b.moduleFile ? -1 : a.moduleFile > b.moduleFile ? 1 : 0)); - const module = [ - '// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.', - '', - '/**', - ` * ${MARK} The host of each facet of \`${CLASS_NAME}\`, built ONCE per driver (#30105):`, - ` * what every stub of a facet hands that facet's bodies as \`this\`, in place of`, - ' * a host literal built on every call. Each `FacetHost` below is filled by the', - ` * factory \`${CLASS_NAME}\`'s static block installs, the one place that can read`, - ' * the class\'s private members; the host is built on the first call that needs', - ' * it and kept for the driver\'s life. A method goes as a closure that calls it', - ' * on the driver at call time, a field or accessor as a getter (and a setter', - ' * when a body assigns it), so a body reads and writes the driver exactly as', - ' * the per-call literal let it.', - ' *', - ` * Written by \`${SCRIPT}\`; it imports types only, so it forms no`, - ' * evaluation cycle and is evaluated before the class whichever module loads', - ' * first. `index.ts` re-exports nothing from this module.', - ' */', - '', - `import type { ${CLASS_NAME} } from './sql-driver.js';`, - ...sorted.map((f) => `import type { ${hostNameOf(f.moduleFile)} } from './${f.moduleFile.replace(/\.ts$/, '.js')}';`), - '', - `/** One facet's host for each driver: built on first use, kept for the driver's life. */`, - `export class ${HOSTS_CLASS} {`, - ` private readonly hosts = new WeakMap<${CLASS_NAME}, H>();`, - ` private build: ((driver: ${CLASS_NAME}) => H) | undefined;`, - '', - ' constructor(private readonly facet: string) {}', - '', - ` /** Called once, from \`${CLASS_NAME}\`'s static block. */`, - ` install(build: (driver: ${CLASS_NAME}) => H): void {`, - ' this.build = build;', - ' }', - '', - ' /** The host of `driver`, built on first use. */', - ` of(driver: ${CLASS_NAME}): H {`, - ' let host = this.hosts.get(driver);', - ' if (host === undefined) {', - ' if (this.build === undefined) {', - ` throw new Error(\`\${this.facet}: ${CLASS_NAME} has not installed its host factory\`);`, - ' }', - ' host = this.build(driver);', - ' this.hosts.set(driver, host);', - ' }', - ' return host;', - ' }', - '}', - '', - ...sorted.map((f) => `export const ${hostVarOf(f.moduleFile)} = new ${HOSTS_CLASS}<${hostNameOf(f.moduleFile)}>('${facetNameOf(f.moduleFile)}');`), - '', - ].join('\n'); - const block = [ - ` // ${MARK} Installs each facet's host factory (\`${HOSTS_MODULE}\`): a static block adds`, - ' // no member to the class, so the published `.d.ts` does not move.', - ' static {', - ...sorted.flatMap((f) => [ - ` ${hostVarOf(f.moduleFile)}.install((driver) => ({`, - ...[...f.members.keys()].sort().flatMap((member) => { - if (f.members.get(member) === 'getter') { - return [` get ${member}() { return driver.${member}; },`, - ...(f.written.has(member) ? [` set ${member}(v) { driver.${member} = v; },`] : [])]; - } - if (BOUND_HOST_METHODS.has(member)) return [` get ${member}() { return driver.${member}.bind(driver); },`]; - return [` ${member}: (...a) => driver.${member}(...a),`]; - }), - ' }));', - ]), - ' }', - ].join('\n'); - return { module, block }; -} - -/** Is `node` inside a JSDoc comment? A `{@link X}` there is prose, not a use. */ -function inJsDoc(tm, node) { - for (let n = node.compilerNode; n; n = n.parent) { - if (n.kind >= tm.SyntaxKind.FirstJSDocNode && n.kind <= tm.SyntaxKind.LastJSDocNode) return true; - } - return false; -} - -/** The statement of `sf` (a direct child of the source file) a declaration belongs to. */ -function topStatementOf(ts, decl) { - let n = decl; - while (n.parent && !ts.isSourceFile(n.parent)) n = n.parent; - return n.parent ? n : null; -} - -/** The names a top-level statement declares, or null when one is not a plain identifier. */ -function declaredNames(tm, st) { - const { Node } = tm; - if (Node.isVariableStatement(st)) { - const names = []; - for (const d of st.getDeclarations()) { - if (!Node.isIdentifier(d.getNameNode())) return null; - names.push(d.getName()); - } - return names; - } - if (Node.isFunctionDeclaration(st) || Node.isInterfaceDeclaration(st) || Node.isTypeAliasDeclaration(st)) { - return st.getName() ? [st.getName()] : null; - } - return null; -} - -/** - * Lever (b): read every top-level statement between the last import and the - * class, and decide which move whole into the leaf. A mover never names the - * class, an `sql-driver-*` module's import, or a statement that stays — so the - * leaf it lands in never imports `sql-driver.ts` back. Pure. - */ -function planTopLevel(tm, ctx) { - const { Node, SyntaxKind } = tm; - const ts = tm.ts; - const stmts = ctx.sf.getStatements(); - const clsIndex = stmts.indexOf(ctx.cls); - let lastImport = -1; - stmts.forEach((st, i) => { if (Node.isImportDeclaration(st)) lastImport = i; }); - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - const nameCount = new Map(); - for (const st of stmts) { - for (const n of declaredNames(tm, st) ?? []) nameCount.set(n, (nameCount.get(n) ?? 0) + 1); - } - const records = []; - const byStatement = new Map(); - for (let i = lastImport + 1; i < clsIndex; i += 1) { - const st = stmts[i]; - const names = declaredNames(tm, st); - const record = { - node: st, names: names ?? [], label: names ? names.join(', ') : `(${st.getKindName()})`, - exported: Node.isExportable(st) && st.isExported(), reasons: [], - deps: new Set(), imports: new Map(), - startLine: st.getStartLineNumber(true), lines: st.getEndLineNumber() - st.getStartLineNumber(true) + 1, - typeOnly: Node.isInterfaceDeclaration(st) || Node.isTypeAliasDeclaration(st), - }; - const add = (code, detail) => { - const tag = detail ? `${code}: ${detail}` : code; - if (!record.reasons.includes(tag)) record.reasons.push(tag); - }; - if (!names || (Node.isVariableStatement(st) && st.hasDeclareKeyword()) || - (Node.isFunctionDeclaration(st) && (!st.getBody() || st.hasDeclareKeyword()))) add('top-kind'); - for (const n of record.names) if ((nameCount.get(n) ?? 0) > 1) add('merged-declaration', n); - for (const n of record.names) if (Object.prototype.hasOwnProperty.call(ctx.pins, n)) add('path-reader', n); - const fullText = st.getFullText(); - for (const needle of Object.keys(ctx.needles)) if (fullText.includes(needle)) add('path-reader', JSON.stringify(needle)); - for (const node of st.getDescendantsOfKind(SyntaxKind.Identifier)) { - if (inJsDoc(tm, node)) continue; - const parent = node.getParent(); - const symbol = Node.isShorthandPropertyAssignment(parent) && parent.getNameNode() === node - ? checker.getShorthandAssignmentValueSymbol(parent.compilerNode) - : checker.getSymbolAtLocation(node.compilerNode); - if (!symbol || !symbol.declarations) continue; - for (const decl of symbol.declarations) { - if (decl.getSourceFile() !== ctx.sf.compilerNode) continue; - const typePos = inTypePosition(tm, node, st); - if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) { - const local = node.getText(); - const binding = ctx.scope.bindings.get(local); - if (binding && (SEAM_SPECIFIER.test(binding.specifier) || binding.specifier === './sql-driver.js')) add('seam-import', local); - const prev = record.imports.get(local); - record.imports.set(local, { value: Boolean(prev && prev.value) || !typePos }); - continue; - } - if (!isModuleScopeDecl(ts, decl)) continue; - const owner = topStatementOf(ts, decl); - if (!owner || owner === st.compilerNode) continue; - if (owner === ctx.cls.compilerNode) { add('class-reference'); continue; } - record.deps.add(owner); - } - } - records.push(record); - byStatement.set(st.compilerNode, record); - } - // A mover may not name a statement that stays: close over the stayers until stable. - for (let changed = true; changed;) { - changed = false; - for (const r of records) { - if (r.reasons.length > 0) continue; - for (const owner of r.deps) { - const dep = byStatement.get(owner); - if (!dep || dep.reasons.length > 0) { - const depName = dep ? dep.label : (declaredNames(tm, ctx.sf.getStatements().find((s) => s.compilerNode === owner)) ?? ['?']).join(', '); - r.reasons.push(`needs-stayer: ${depName}`); - changed = true; - break; - } - } - } - } - const movers = records.filter((r) => r.reasons.length === 0); - const moverNames = new Map(); - for (const r of movers) for (const n of r.names) moverNames.set(n, r); - return { records, movers, moverNames }; -} - -/** - * Which moved top-level names the text that STAYS in `sql-driver.ts` still - * reads, value or type: everything outside the moved statements and the moved - * method bodies, JSDoc excepted. Those are what `sql-driver.ts` imports back - * from the leaf. - */ -function hostUsesOfMovers(tm, ctx, top, methodRecords) { - const { SyntaxKind } = tm; - const ts = tm.ts; - const checker = ctx.sf.getProject().getTypeChecker().compilerObject; - const skip = []; - for (const r of top.movers) skip.push([r.node.getFullStart(), r.node.getEnd()]); - for (const r of methodRecords) { - if (r.reasons.length > 0) continue; - const moved = r.kind === 'field-default' ? r.node.getInitializer() : r.node.getBody(); - skip.push([moved.getStart(), moved.getEnd()]); - } - const uses = new Map(); - for (const node of ctx.sf.getDescendantsOfKind(SyntaxKind.Identifier)) { - const at = node.getStart(); - if (skip.some(([a, b]) => at >= a && at < b)) continue; - if (inJsDoc(tm, node)) continue; - const name = node.getText(); - if (!top.moverNames.has(name)) continue; - const symbol = checker.getSymbolAtLocation(node.compilerNode); - if (!symbol || !symbol.declarations) continue; - const mover = top.moverNames.get(name); - if (!symbol.declarations.some((d) => topStatementOf(ts, d) === mover.node.compilerNode)) continue; - const typePos = inTypePosition(tm, node, ctx.sf); - const prev = uses.get(name); - uses.set(name, { value: Boolean(prev && prev.value) || !typePos }); - } - return uses; -} - -/** - * Read `text` (an `sql-driver.ts`) and decide, per method, where its body goes, - * and per top-level declaration ahead of the class, whether it moves to the - * leaf. Pure: the same text gives the same plan. - */ -function plan(tm, text, { - sections = SECTION_MODULES, head = CLASS_HEAD_SECTION, pins = PATH_READER_PINS, needles = PATH_READER_NEEDLES, classNeedles = CLASS_PATH_READER_NEEDLES, - receiverFree = RECEIVER_FREE_FIELDS, returnTypes = EXPLICIT_RETURN_TYPES, accessors = MOVED_ACCESSORS, fieldDefaults = MOVED_FIELD_DEFAULTS, -} = {}) { - const sf = parse(tm, HOST_PATH, text); - const cls = sf.getClass(CLASS_NAME); - if (!cls) refuse(`no class ${CLASS_NAME} in ${HOST_BASENAME}`); - const sectionOf = readSections(text, cls, sections, head); - // The class's statics: scope, and what a forwarder in `SqlDriverStatics` - // would be (a method forwards as a function; a field or accessor as a getter). - const statics = new Map(); - for (const m of cls.getMembers()) { - if (typeof m.isStatic === 'function' && m.isStatic() && typeof m.getName === 'function') { - const { Node } = tm; - const prev = statics.get(m.getName()); - const kind = Node.isMethodDeclaration(m) ? 'method' : Node.isSetAccessorDeclaration(m) ? (prev ? prev.kind : 'setter') - : Node.isGetAccessorDeclaration(m) ? 'getter' : 'field'; - statics.set(m.getName(), { - scope: typeof m.getScope === 'function' ? m.getScope() : 'public', kind, - overloaded: Node.isMethodDeclaration(m) && m.getOverloads().length > 0, - }); - } - } - const ctx = { text, sf, cls, members: instanceMembers(tm, cls), scope: moduleScope(tm, sf), statics, pins, needles, classNeedles, receiverFree, returnTypes }; - for (const n of [STATICS_NAME, STATICS_HOST_NAME, ...[...Object.values(sections), head && head[1]].filter(Boolean).map((file) => facetNameOf(file))]) { - if (ctx.scope.bindings.has(n)) refuse(`${HOST_BASENAME} already binds ${n}, a name this script generates`); - } - const methodNames = new Set(cls.getMethods().map((m) => m.getName())); - const stalePins = Object.keys(pins).filter((n) => !methodNames.has(n) && !ctx.scope.bindings.has(n)); - if (stalePins.length > 0) refuse(`PATH_READER_PINS names what ${HOST_BASENAME} no longer declares: ${stalePins.join(', ')}`); - const staleNeedles = Object.keys(needles).filter((n) => !text.includes(n)); - if (staleNeedles.length > 0) refuse(`PATH_READER_NEEDLES names text ${HOST_BASENAME} no longer carries: ${staleNeedles.map((n) => JSON.stringify(n)).join(', ')}`); - const staleClassNeedles = Object.keys(classNeedles).filter((n) => !text.includes(n)); - if (staleClassNeedles.length > 0) refuse(`CLASS_PATH_READER_NEEDLES names text ${HOST_BASENAME} no longer carries: ${staleClassNeedles.map((n) => JSON.stringify(n)).join(', ')}`); - - // The #30147 tables: every row names what the class declares, as it says. - for (const n of Object.keys(receiverFree)) { - if (ctx.members.get(n)?.kind !== 'field') refuse(`RECEIVER_FREE_FIELDS names ${n}, which is no instance field of ${CLASS_NAME}`); - } - for (const n of Object.keys(returnTypes)) { - const ms = cls.getMethods().filter((m) => m.getName() === n && !m.isStatic()); - if (ms.length !== 1) refuse(`EXPLICIT_RETURN_TYPES names ${n}, which is not one instance method of ${CLASS_NAME}`); - if (ms[0].getReturnTypeNode()) refuse(`EXPLICIT_RETURN_TYPES names ${n}, whose return type the base already writes`); - } - const getters = new Map(); - for (const n of Object.keys(accessors)) { - const gs = cls.getGetAccessors().filter((g) => g.getName() === n && !g.isStatic()); - if (gs.length !== 1) refuse(`MOVED_ACCESSORS names ${n}, which is not one instance get accessor of ${CLASS_NAME}`); - getters.set(n, gs[0]); - } - const defaultFields = new Map(); - for (const n of Object.keys(fieldDefaults)) { - const fs = cls.getProperties().filter((f) => f.getName() === n && !f.isStatic()); - if (fs.length !== 1 || !fs[0].getInitializer() || !fs[0].getTypeNode()) { - refuse(`MOVED_FIELD_DEFAULTS names ${n}, which is not one typed instance field of ${CLASS_NAME} with an initializer`); - } - defaultFields.set(n, fs[0]); - } - - const top = planTopLevel(tm, ctx); - - const records = []; - for (const m of cls.getMethods()) { - const startLine = m.getStartLineNumber(true); - const section = sectionOf(m); - const read = readMethod(tm, ctx, m); - const name = m.getName(); - if (!section) read.reasons.unshift('no-section'); - else if (section[1] === null) read.reasons.unshift('section-kept'); - const lineCount = m.getEndLineNumber() - startLine + 1; - const body = m.getBody(); - const bodyLines = body ? body.getEndLineNumber() - body.getStartLineNumber() + 1 : 0; - // Docblock ownership (ruling 6624345766 item 1): a PRIVATE method's - // docblock moves with its body; a public or protected one stays on the - // facade, where the published surface prints it. - const docStart = m.getStart(true); - const doc = m.getScope() === 'private' && docStart < m.getStart() ? text.slice(docStart, m.getStart()) : null; - const record = { - name, node: m, section: section ? section[0] : null, module: section ? section[1] : null, - startLine, lineCount, bodyLines, doc, docLines: doc ? doc.split('\n').length - 1 : 0, ...read, - }; - if (section && section[1]) { - for (const p of m.getParameters()) { - if (p.getName() === facetNameOf(section[1]) || p.getName() === hostVarOf(section[1])) read.reasons.push(`parameter-shadows: ${p.getName()}`); - } - } - if (record.reasons.length === 0) record.stubLines = stubBody(record, record.module, ' ').split('\n').length; - record.kind = 'method'; - record.optionalized = optionalizedParams(tm, m); - records.push(record); - } - // The get accessors MOVED_ACCESSORS names move as methods do (#30147). - for (const g of getters.values()) { - const section = sectionOf(g); - const read = readMethod(tm, ctx, g); - if (!section) read.reasons.unshift('no-section'); - else if (section[1] === null) read.reasons.unshift('section-kept'); - if (!g.getReturnTypeNode()) read.reasons.push('inferred-return-type'); - const startLine = g.getStartLineNumber(true); - const body = g.getBody(); - const record = { - name: g.getName(), node: g, section: section ? section[0] : null, module: section ? section[1] : null, startLine, - lineCount: g.getEndLineNumber() - startLine + 1, bodyLines: body.getEndLineNumber() - body.getStartLineNumber() + 1, - doc: null, docLines: 0, ...read, kind: 'accessor', optionalized: [], - }; - if (record.reasons.length === 0) record.stubLines = stubBody(record, record.module, ' ').split('\n').length; - records.push(record); - } - // The field initializers MOVED_FIELD_DEFAULTS names (#30147): one that - // reads `this`, or a name of this file (an import or a top-level binding), - // is refused, since the facet member would carry it unedited. - for (const f of defaultFields.values()) { - const section = sectionOf(f); - const init = f.getInitializer(); - const checker = sf.getProject().getTypeChecker().compilerObject; - for (const node of [init, ...init.getDescendants()]) { - if (node.getKind() === tm.SyntaxKind.ThisKeyword) refuse(`MOVED_FIELD_DEFAULTS: the initializer of ${f.getName()} reads \`this\``); - if (node.getKind() !== tm.SyntaxKind.Identifier) continue; - const symbol = checker.getSymbolAtLocation(node.compilerNode); - for (const decl of symbol?.declarations ?? []) { - if (decl.getSourceFile() !== sf.compilerNode) continue; - if (decl.getStart() >= init.getStart() && decl.getEnd() <= init.getEnd()) continue; - refuse(`MOVED_FIELD_DEFAULTS: the initializer of ${f.getName()} reads ${node.getText()}, a name of ${HOST_BASENAME}`); - } - } - const reasons = !section ? ['no-section'] : section[1] === null ? ['section-kept'] : []; - const startLine = f.getStartLineNumber(true); - records.push({ - name: f.getName(), node: f, section: section ? section[0] : null, module: section ? section[1] : null, startLine, - lineCount: f.getEndLineNumber() - startLine + 1, bodyLines: init.getEndLineNumber() - init.getStartLineNumber() + 1, - doc: null, docLines: 0, reasons, host: new Map(), writes: new Set(), imports: new Map(), moduleRefs: new Map(), - classStatics: new Map(), routeBlockers: [], readsNonPublicStatic: false, classOther: false, rawParams: null, - kind: 'field-default', optionalized: [], stubLines: 1, - }); - } - // Facet member order is the class's: methods, accessors and fields by position. - records.sort((a, b) => a.node.getStart() - b.node.getStart()); - - // The private-static-through-host rule, per facet module: once one mover - // reads the statics through `SqlDriverStatics` (imported AS `SqlDriver`), - // every mover in that module does, so what the route cannot carry keeps a - // mover on the class. A router itself never carries a blocker (readMethod - // already kept it), so the set of routed modules is stable. - for (let changed = true; changed;) { - changed = false; - for (const movers of groupMovers(records).values()) { - if (!movers.some((r) => r.readsNonPublicStatic)) continue; - for (const r of movers) { - const extra = [...r.routeBlockers, ...(r.classOther ? ['static-route-conflict'] : [])].filter((t) => !r.reasons.includes(t)); - if (extra.length > 0) { r.reasons.push(...extra); changed = true; } - } - } - } - const modules = groupMovers(records); - const routedModules = new Set(); - const routedStatics = new Map(); - for (const [moduleFile, movers] of modules) { - if (!movers.some((r) => r.readsNonPublicStatic)) continue; - routedModules.add(moduleFile); - for (const r of movers) for (const [member, kind] of r.classStatics) routedStatics.set(member, kind); - } - for (const [moduleFile, movers] of modules) { - const facet = facetNameOf(moduleFile); - for (const r of movers) { - for (const local of [...r.imports.keys(), ...r.moduleRefs.keys()]) { - if (local === facet || local === hostNameOf(moduleFile) || local === CLASS_TYPE_ALIAS) { - refuse(`${moduleFile}: ${r.name} reads ${local}, a name this script generates in that module`); - } - } - } - } - const hostUses = hostUsesOfMovers(tm, ctx, top, records); - - // What each side imports across the cut: the section modules read moved - // names from the leaf and staying names from sql-driver.ts (lever (a)); - // sql-driver.ts reads moved names from the leaf. - const sectionLeafNames = new Set(); - const hostExportsForSections = new Map(); // staying name -> { value } - for (const movers of modules.values()) { - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - if (top.moverNames.has(n)) { sectionLeafNames.add(n); continue; } - if (n === CLASS_NAME || ctx.scope.exported.has(n)) continue; - const prev = hostExportsForSections.get(n); - hostExportsForSections.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - } - const leafExports = []; - for (const r of top.movers) { - if (r.exported) continue; - for (const n of r.names) if (hostUses.has(n) || sectionLeafNames.has(n)) leafExports.push(n); - } - return { sf, cls, ctx, records, modules, top, hostUses, leafExports, hostExportsForSections, routedModules, routedStatics }; -} - -/** Movers grouped by module, modules in the order their first member appears. */ -function groupMovers(records) { - const byModule = new Map(); - for (const r of records) { - if (r.reasons.length > 0 || !r.module) continue; - if (!byModule.has(r.module)) byModule.set(r.module, []); - byModule.get(r.module).push(r); - } - return byModule; -} - -// ── Generation ─────────────────────────────────────────────────────────────── - - -const byName = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0); -const leafSpecifier = () => `./${LEAF_MODULE.replace(/\.ts$/, '.js')}`; - -/** - * One `import` / `export` statement over `names`: on one line when it fits in - * 120 columns, else one name per wrapped run, two-space indented. - */ -function namedStatement(head, names, tail) { - const one = `${head} { ${names.join(', ')} }${tail}`; - if (one.length <= 120) return one; - const out = [`${head} {`]; - let line = ' '; - for (const n of names) { - if (line.length + n.length + 2 > 118 && line !== ' ') { out.push(line); line = ' '; } - line += ` ${n},`; - } - out.push(line); - out.push(`}${tail}`); - return out.join('\n'); -} - -/** `import { … }` and `import type { … }` from one specifier, values first. */ -function importPair(specifier, uses) { - const out = []; - const entries = [...uses.entries()].sort(byName); - const values = entries.filter(([, u]) => u.value).map(([n]) => n); - const types = entries.filter(([, u]) => !u.value).map(([n]) => n); - if (values.length > 0) out.push(namedStatement('import', values, ` from '${specifier}';`)); - if (types.length > 0) out.push(namedStatement('import type', types, ` from '${specifier}';`)); - return out; -} - -/** - * The import lines a module needs: sql-driver.ts's own imports it uses, in - * sql-driver.ts's import order; then the moved top-level names, from the leaf; - * then what stayed in sql-driver.ts (lever (a)), including the class. - */ -function importLines(scope, users, { needsHost = false, moduleRefs = new Map(), leafNames = new Map(), routed = false } = {}) { - const bySpecifier = new Map(); - for (const r of users) { - for (const [local, use] of r.imports) { - const b = scope.bindings.get(local); - if (!b || b.kind !== 'import') refuse(`import binding ${local} not found`); - if (!bySpecifier.has(b.specifier)) bySpecifier.set(b.specifier, new Map()); - const slot = bySpecifier.get(b.specifier); - const prev = slot.get(local); - slot.set(local, { ...b, value: Boolean(prev && prev.value) || (use.value && !b.typeOnly) }); - } - } - const out = []; - const specifiers = [...bySpecifier.keys()].sort((a, b) => scope.importOrder.get(a) - scope.importOrder.get(b)); - for (const specifier of specifiers) { - const entries = [...bySpecifier.get(specifier).entries()].sort(byName); - const named = (value) => entries - .filter(([, e]) => e.form === 'named' && e.value === value) - .map(([local, e]) => (e.imported === local ? local : `${e.imported} as ${local}`)); - const def = entries.find(([, e]) => e.form === 'default'); - const ns = entries.find(([, e]) => e.form === 'namespace'); - const valueNamed = named(true); - const defValue = def && def[1].value ? def[0] : null; - if (defValue || valueNamed.length > 0) { - const parts = [defValue, valueNamed.length > 0 ? `{ ${valueNamed.join(', ')} }` : null].filter(Boolean); - out.push(`import ${parts.join(', ')} from '${specifier}';`); - } - if (def && !def[1].value) out.push(`import type ${def[0]} from '${specifier}';`); - if (ns) out.push(`import ${ns[1].value ? '' : 'type '}* as ${ns[0]} from '${specifier}';`); - const typeNamed = named(false); - if (typeNamed.length > 0) out.push(`import type { ${typeNamed.join(', ')} } from '${specifier}';`); - } - const fromLeaf = new Map(); - const fromHost = new Map(); - for (const [n, use] of moduleRefs) (leafNames.has(n) ? fromLeaf : fromHost).set(n, use); - if (routed) { - // The private-static-through-host rule: `SqlDriver.x` in a moved body reads - // the forwarder object; the host interface names the class by an alias. - fromHost.delete(CLASS_NAME); - fromHost.set(`${STATICS_NAME} as ${CLASS_NAME}`, { value: true }); - if (needsHost) fromHost.set(`${CLASS_NAME} as ${CLASS_TYPE_ALIAS}`, { value: false }); - } else if (needsHost && !fromHost.has(CLASS_NAME)) fromHost.set(CLASS_NAME, { value: false }); - out.push(...importPair(leafSpecifier(), fromLeaf)); - out.push(...importPair('./sql-driver.js', fromHost)); - return out; -} - -/** `text` wrapped into ` * ` comment lines no wider than `width`. */ -function wrapComment(words, width = 80) { - const lines = []; - let line = ' *'; - for (const w of words) { - if (line.length + 1 + w.length > width && line !== ' *') { lines.push(line); line = ' *'; } - line += ` ${w}`; - } - if (line !== ' *') lines.push(line); - return lines; -} - -function paramsText(m) { - return m.getParameters().map((p) => p.getText()); -} - -/** The text between a member's parentheses, exactly. */ -function parameterListText(tm, m) { - const { SyntaxKind } = tm; - const open = m.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken); - const close = m.getFirstChildByKindOrThrow(SyntaxKind.CloseParenToken); - return m.getSourceFile().getFullText().slice(open.getEnd(), close.getStart()); -} - -/** Whether a comment stands between a member's parentheses that no parameter's own text carries. */ -function commentInParameters(tm, m) { - const { SyntaxKind } = tm; - const open = m.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken); - let between = parameterListText(tm, m); - for (const p of [...m.getParameters()].reverse()) { - between = between.slice(0, p.getStart() - open.getEnd()) + between.slice(p.getEnd() - open.getEnd()); - } - return /\/\/|\/\*/.test(between); -} - -/** - * A facet member's parameter list: its host parameter (when it has one), - * then the base's parameters. One after another, unless a comment stands - * between the base's parentheses: then the base's list verbatim, so the - * comment moves with it (#30147). - */ -function facetParamsText(thisParam, m, raw) { - if (raw === null) return [...(thisParam ? [thisParam] : []), ...paramsText(m)].join(', '); - if (!thisParam) return raw; - return `${thisParam},${/^\s/.test(raw) ? '' : ' '}${raw}`; -} - -function forwardList(m) { - return m.getParameters().map((p) => (p.isRestParameter() ? `...${p.getName()}` : p.getName())); -} - -function moduleText(moduleFile, title, movers, scope, leafNames, routed = false) { - const hostName = hostNameOf(moduleFile); - const facet = facetNameOf(moduleFile); - const classType = routed ? CLASS_TYPE_ALIAS : CLASS_NAME; - const hostMembers = new Map(); - const written = new Set(); - for (const r of movers) for (const [member, kind] of r.host) hostMembers.set(member, kind); - for (const r of movers) for (const member of r.writes) written.add(member); - const needsHost = hostMembers.size > 0; - const moduleRefs = new Map(); - for (const r of movers) { - for (const [n, use] of r.moduleRefs) { - const prev = moduleRefs.get(n); - moduleRefs.set(n, { value: Boolean(prev && prev.value) || use.value }); - } - } - const readsHostValues = [...moduleRefs].some(([n, use]) => use.value && !leafNames.has(n)); - const names = movers.map((r) => `\`${r.name}\`${r === movers[movers.length - 1] ? '' : ','}`); - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push('/**'); - out.push(...wrapComment([MARK, 'The', `"${title}"`, 'section', 'of', '`SqlDriver`:', 'the', 'bodies', 'of', - ...names, 'moved', 'out', 'of', '`sql-driver.ts`', 'whole', 'by', `\`${SCRIPT}\`.`])); - out.push(' *'); - out.push(` * A MOVE, not a redesign. {@link ${facet}} is a stateless facet of \`SqlDriver\``); - out.push(' * (ruling 6624345766): each static method of it is the body of the `SqlDriver`'); - out.push(' * method of the same name exactly as it stood: not re-indented, not'); - out.push(' * formatted, not edited. The method stays on the class as a one-call stub with'); - out.push(' * its signature, so the published surface, an instance spy and a subclass'); - out.push(' * override are what they were. A public or protected method keeps its'); - out.push(' * docblock on the class, the contract; a private method\'s docblock moved here'); - out.push(' * with its body. The state stays on `SqlDriver`.'); - out.push(' *'); - if (needsHost) { - out.push(...wrapComment((`The bodies reach the class through {@link ${hostName}}: exactly the \`SqlDriver\` ` + - 'members they read, private ones included. Every stub hands its body, by a `.call`, the same host: ' + - `\`${hostVarOf(moduleFile)}\` in \`${HOSTS_MODULE}\`, built once per driver by the class's static block. ` + - 'Methods go as closures that call them on the driver at call time, so a subclass override or an ' + - 'instance spy is still the one reached; fields and accessors go as GETTERS, read when the body reads ' + - 'them, as they were on the class, and a field a body assigns goes with a SETTER that assigns it on ' + - 'the driver.').split(' '))); - } else { - out.push(' * No body reads an `SqlDriver` member, so each stub calls its body directly.'); - } - if (routed) { - out.push(' *'); - out.push(` * \`SqlDriver\` here is \`${STATICS_NAME}\` (imported AS \`SqlDriver\`): forwarders to the`); - out.push(' * statics the bodies read, private ones included, which the class fills in a'); - out.push(` * static block; the class as a type is \`${CLASS_TYPE_ALIAS}\`.`); - } - out.push(' *'); - if (readsHostValues) { - out.push(' * Values that stayed in `sql-driver.ts` are imported from it (lever (a) of'); - out.push(' * ruling 6591753301); every use is inside a function body, so the import'); - out.push(' * cycle is never read at evaluation time. `index.ts` re-exports nothing from'); - out.push(' * this module.'); - } else { - out.push(' * The module imports `sql-driver.ts` for types only, so the two modules form no'); - out.push(' * evaluation cycle. `index.ts` re-exports nothing from this module.'); - } - out.push(' */'); - out.push(''); - out.push(...importLines(scope, movers, { needsHost: needsHost || movers.some((r) => r.kind === 'field-default'), moduleRefs, leafNames, routed })); - if (needsHost) { - out.push(''); - out.push('/**'); - out.push(` * The \`SqlDriver\` members the bodies of {@link ${facet}} read — every one of`); - out.push(' * them, and no other. Each is typed AS the class member (an indexed access on'); - out.push(' * the class), so a change to a member\'s signature on the class is a change'); - out.push(' * here too. `readonly` members are the getters; the others are fields a body'); - out.push(' * assigns.'); - out.push(' */'); - out.push(`export interface ${hostName} {`); - for (const member of [...hostMembers.keys()].sort()) { - const ro = hostMembers.get(member) === 'getter' && !written.has(member); - out.push(` ${ro ? 'readonly ' : ''}${member}: ${classType}['${member}'];`); - } - out.push('}'); - } - out.push(''); - out.push(`/** The bodies of the "${title}" section of \`SqlDriver\`: a stateless facet, called by the class's stubs. */`); - out.push(`export class ${facet} {`); - movers.forEach((r, i) => { - const m = r.node; - const picks = [...r.host.keys()].sort().map((k) => `'${k}'`).join(' | '); - if (i > 0) out.push(''); - if (r.kind === 'field-default') { - // The field's initializer, returned exactly, typed as the field. - out.push(` ${fieldDefaultDoc(r.name)}\n static ${r.name}(): ${classType}['${r.name}'] {\n return ${m.getInitializer().getText()};\n }`); - return; - } - const thisParam = r.host.size > 0 ? `this: Pick<${hostName}, ${picks}>` : null; - const ret = m.getReturnTypeNode() ? `: ${m.getReturnTypeNode().getText()}` : ''; - const typeParams = typeParamsOf(m).length > 0 ? `<${typeParamsOf(m).map((t) => t.getText()).join(', ')}>` : ''; - const isAsync = typeof m.isAsync === 'function' && m.isAsync(); - out.push(` ${r.doc ?? `${placeholderDoc(r.name)}\n `}static ${isAsync ? 'async ' : ''}${r.name}${typeParams}(${facetParamsText(thisParam, m, r.rawParams)})${ret} ${m.getBody().getText()}`); - }); - out.push('}'); - out.push(''); - return out.join('\n'); -} - -/** - * The leaf: the moved top-level statements, each its base text exactly (its - * leading comments and blank lines included), in base order, after the - * imports they use; then one `export { … }` of the moved names base did not - * export and something outside the leaf now imports. - */ -function leafText(scope, top, leafExports) { - // The header is `//` lines, not a `/** */` docblock: the bundled `.d.ts` - // keeps a JSDoc block that leads a module's first statement, and a leaf - // bundled first would publish text the base did not carry (the pilot's - // measurement: 14 added lines in dist/index.d.ts). - const out = []; - out.push('// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.'); - out.push(''); - out.push(...wrapComment([MARK, 'The', 'top-level', 'declarations', 'ahead', 'of', '`SqlDriver`', 'in', '`sql-driver.ts`', - 'that', 'moved', 'out', 'whole', 'by', `\`${SCRIPT}\``, '(lever', '(b)', 'of', 'ruling', - '6591753301).']).map((l) => l.replace(/^ \*/, '//'))); - out.push('//'); - out.push('// A MOVE, not a redesign: each declaration below is its `sql-driver.ts` text'); - out.push('// exactly, with the comments above it, in the order it stood there. A LEAF:'); - out.push('// it imports neither `sql-driver.ts` nor any `sql-driver-*` module, so it is'); - out.push('// evaluated before the class and forms no cycle with it. `sql-driver.ts`'); - out.push('// re-exports, by name, every declaration here it exported before, so every'); - out.push('// importer of `./sql-driver.js` reads what it read.'); - out.push(''); - out.push(...importLines(scope, top.movers)); - let text = out.join('\n'); - for (const r of top.movers) text += r.node.getFullText(); - if (leafExports.length > 0) { - text += `\n\n// ${MARK} Declared above without \`export\`, and read by \`sql-driver.ts\` or a section module.\n`; - text += `${namedStatement('export', [...leafExports].sort(), ';')}`; - } - return `${text}\n`; -} - -const DOC_MOVED = 'its docblock with it'; - -/** A moved field initializer's replacement: one call of its facet member. */ -const fieldDefaultCall = (moduleFile, name) => `${facetNameOf(moduleFile)}.${name}()`; - -/** - * A stub's body: the marker line, then ONE call of the facet member of the - * same name. A body that reads the class is called with its facet's host, the - * one object per driver `HOSTS_MODULE` keeps (#30105), not a literal built per - * call. `node` is the method (base or head: the stub keeps its signature). - * Pure: `verify` rebuilds every stub with it and compares. - */ -function stubBody({ node, name, usesHost, docMoved }, moduleFile, closeIndent) { - const ind = `${closeIndent} `; - const hostName = hostNameOf(moduleFile); - // A generic method calls its body INSTANTIATED with its own type - // parameters (`Function#call` alone would erase them). - const typeArgs = typeParamsOf(node).map((t) => t.getName()); - const fn = typeArgs.length > 0 ? `(${facetNameOf(moduleFile)}.${name}<${typeArgs.join(', ')}>)` : `${facetNameOf(moduleFile)}.${name}`; - const out = ['{']; - const args = forwardList(node).join(', '); - const doc = docMoved ? `, ${DOC_MOVED}` : ''; - if (!usesHost) { - out.push(`${ind}// ${MARK} The body moved to \`${moduleFile}\`${doc}.`); - out.push(`${ind}return ${fn}(${args});`); - } else { - out.push(`${ind}// ${MARK} The body moved to \`${moduleFile}\`${doc} (see \`${hostName}\`).`); - out.push(`${ind}return ${fn}.call(${hostVarOf(moduleFile)}.of(this)${args ? `, ${args}` : ''});`); - } - out.push(`${closeIndent}}`); - return out.join('\n'); -} - -/** The facets whose bodies read the class, as `hostsTexts` takes them, from the movers of each module. */ -function facetsOf(modules) { - const facets = []; - for (const [moduleFile, movers] of modules) { - const members = new Map(); - const written = new Set(); - for (const r of movers) for (const [member, kind] of r.host) members.set(member, kind); - for (const r of movers) for (const member of r.writes) written.add(member); - if (members.size > 0) facets.push({ moduleFile, members, written }); - } - return facets; -} - -/** - * Apply a plan to `text`. Returns `{ host, modules }`: the new - * `sql-driver.ts` and a Map of module basename -> text (the leaf and the host - * module among them). Pure. - */ -function generate(tm, text, planned) { - const { sf, ctx, modules, top, hostUses, leafExports, hostExportsForSections, routedModules, routedStatics } = planned; - const edits = []; - const importBlock = []; - if (top.movers.length > 0) { - const leafUses = new Map([...hostUses].filter(([n]) => top.moverNames.has(n))); - const lines = importPair(leafSpecifier(), leafUses); - if (lines.length > 0) { - importBlock.push(`\n// ${MARK} The top-level declarations that moved whole to \`${LEAF_MODULE}\`, as this file still reads them.`); - for (const l of lines) importBlock.push(`\n${l}`); - } - const reexports = top.movers.filter((r) => r.exported) - .flatMap((r) => r.names.map((n) => [n, r.typeOnly ? `type ${n}` : n])) - .sort(byName).map(([, spelled]) => spelled); - if (reexports.length > 0) { - importBlock.push(`\n// ${MARK} Re-exported by name, so every importer of \`./sql-driver.js\` reads what it read.`); - importBlock.push(`\n${namedStatement('export', reexports, ` from '${leafSpecifier()}';`)}`); - } - for (const r of top.movers) edits.push({ start: r.node.getFullStart(), end: r.node.getEnd(), text: '' }); - } - for (const [moduleFile, movers] of modules) { - const title = movers[0].section; - const hostName = hostNameOf(moduleFile); - const anyHost = movers.some((r) => r.host.size > 0); - importBlock.push(`\n// ${MARK} ${title}: the methods of the same names below hand the bodies` + - `${anyHost ? ` what they read (\`${hostName}\`)` : ' their arguments'}.`); - importBlock.push(`\nimport { ${facetNameOf(moduleFile)} } from './${moduleFile.replace(/\.ts$/, '.js')}';`); - for (const r of movers) { - if (r.kind === 'field-default') { - // The initializer becomes one call of the facet member that returns it. - const init = r.node.getInitializer(); - edits.push({ start: init.getStart(), end: init.getEnd(), text: fieldDefaultCall(moduleFile, r.name) }); - continue; - } - const body = r.node.getBody(); - const lineStart = text.lastIndexOf('\n', body.getEnd() - 1) + 1; - const closeIndent = text.slice(lineStart, body.getEnd() - 1); - if (!/^ *$/.test(closeIndent)) refuse(`${r.name}: the body's closing brace does not open its own line`); - if (r.host.size > 0 && r.node.getParameters().some((p) => p.getName() === hostVarOf(moduleFile))) { - refuse(`${r.name}: a parameter is named ${hostVarOf(moduleFile)}, which its stub reads as the facet's host`); - } - const stub = stubBody({ node: r.node, name: r.name, usesHost: r.host.size > 0, docMoved: Boolean(r.doc) }, moduleFile, closeIndent); - edits.push({ start: body.getStart(), end: body.getEnd(), text: stub }); - const asyncKw = r.node.getModifiers().find((x) => x.getKind() === tm.SyntaxKind.AsyncKeyword); - if (asyncKw) edits.push({ start: asyncKw.getStart(), end: r.node.getNameNode().getStart(), text: '' }); - if (r.doc) edits.push({ start: r.node.getStart(true), end: r.node.getStart(), text: '' }); - // An inferred return type the base's declaration output prints, written out (#30147). - if (r.kind === 'method' && !r.node.getReturnTypeNode() && Object.hasOwn(ctx.returnTypes, r.name)) { - const close = r.node.getFirstChildByKindOrThrow(tm.SyntaxKind.CloseParenToken); - edits.push({ start: close.getEnd(), end: close.getEnd(), text: `: ${ctx.returnTypes[r.name]}` }); - } - for (const o of r.optionalized) edits.push({ start: o.param.getStart(), end: o.param.getEnd(), text: o.text }); - } - } - // A hand-series stub (its body already a seam call) whose parameter - // computes its default takes the same optional spelling; the seam function - // keeps the default (`verify` reads it there) (#30147). - for (const r of planned.records) { - if (r.kind !== 'method' || r.reasons.length === 0 || !r.reasons.every((x) => x.startsWith('already-moved'))) continue; - for (const o of r.optionalized) edits.push({ start: o.param.getStart(), end: o.param.getEnd(), text: o.text }); - } - // After the class's last member: the static block that fills the statics - // forwarders, then the one that installs the facet hosts (one edit, so the - // two keep this order). - const tail = []; - if (routedStatics.size > 0) { - // The private-static-through-host rule: the forwarder object ahead of the - // class (ahead of its leading comments), the static block that fills it - // after the class's last member. - const { ahead, block } = staticsTexts(routedStatics); - edits.push({ start: ctx.cls.getFullStart(), end: ctx.cls.getFullStart(), text: `\n\n${ahead}` }); - tail.push(`\n\n${block}`); - } - const facets = facetsOf(modules); - const hosts = facets.length > 0 ? hostsTexts(facets) : null; - if (hosts) { - for (const f of facets) { - if (ctx.scope.bindings.has(hostVarOf(f.moduleFile))) refuse(`sql-driver.ts already binds ${hostVarOf(f.moduleFile)}, the name of ${f.moduleFile}'s host`); - } - tail.push(`\n\n${hosts.block}`); - importBlock.push(`\n// ${MARK} The facets' hosts, one per driver, which the static block at the end of the class builds.`); - importBlock.push(`\n${namedStatement('import', facets.map((f) => hostVarOf(f.moduleFile)).sort(), ` from './${HOSTS_MODULE.replace(/\.ts$/, '.js')}';`)}`); - } - if (tail.length > 0) { - const last = ctx.cls.getMembers().at(-1); - edits.push({ start: last.getEnd(), end: last.getEnd(), text: tail.join('') }); - } - if (hostExportsForSections.size > 0) { - const spelled = [...hostExportsForSections.keys()].sort().map((n) => { - const st = ctx.sf.getStatements().find((s) => (declaredNames(tm, s) ?? []).includes(n)); - return st && (tm.Node.isInterfaceDeclaration(st) || tm.Node.isTypeAliasDeclaration(st)) ? `type ${n}` : n; - }); - importBlock.push(`\n// ${MARK} Exported for the section modules above, which import them (lever (a)); \`index.ts\` re-exports by name, so none reaches the package.`); - importBlock.push(`\n${namedStatement('export', spelled, ';')}`); - } - const lastImport = sf.getImportDeclarations().at(-1); - if (!lastImport) refuse('sql-driver.ts has no import declaration to place the generated imports after'); - if (importBlock.length > 0) edits.push({ start: lastImport.getEnd(), end: lastImport.getEnd(), text: importBlock.join('') }); - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let out = text; - let floor = Infinity; - for (const e of edits) { - if (e.end > floor) refuse('overlapping edits'); - out = out.slice(0, e.start) + e.text + out.slice(e.end); - floor = e.start; - } - const moduleTexts = new Map(); - const leafNames = top.moverNames; - if (top.movers.length > 0) moduleTexts.set(LEAF_MODULE, leafText(ctx.scope, top, leafExports)); - for (const [moduleFile, movers] of modules) { - moduleTexts.set(moduleFile, moduleText(moduleFile, movers[0].section, movers, ctx.scope, leafNames, routedModules.has(moduleFile))); - } - if (hosts) moduleTexts.set(HOSTS_MODULE, hosts.module); - return { host: out, modules: moduleTexts }; -} - -// ── Proof 1: byte-identity ─────────────────────────────────────────────────── - -const sha256 = (text) => createHash('sha256').update(text).digest('hex'); - -/** - * Prove a split against its base, from the texts alone (it shares no state with - * `generate`): every generated function is its base method's text, every leaf - * declaration is its base statement's text, and undoing the split rebuilds the - * base `sql-driver.ts` byte-for-byte. - * - * Undoing is: put each body back on its stub (and `async` back, and a moved - * docblock back above it), drop the generated statics forwarders and the two - * generated static blocks once each is proved to be exactly what the generator - * writes for what it names, drop the generated import / export statements, - * then splice the leaf's statements back between the statements that stayed — - * the interleaving read off the base by NAME only, so every byte of the result - * comes from the head, a facet module or the leaf. - * - * Returns `{ failures, moved, movedTop, linesBefore, linesAfter, routedStatics }`; no failure = proved. - */ -function verify(tm, baseText, headText, moduleTexts, { readSibling = null, returnTypes = EXPLICIT_RETURN_TYPES } = {}) { - const { Node } = tm; - const failures = []; - const moved = []; - const movedTop = []; - const baseSf = parse(tm, HOST_PATH, baseText); - const baseCls = baseSf.getClass(CLASS_NAME); - const headSf = parse(tm, HOST_PATH, headText); - const headCls = headSf.getClass(CLASS_NAME); - const none = { failures: [`no class ${CLASS_NAME} at base or head`], moved, movedTop, linesBefore: 0, linesAfter: 0 }; - if (!baseCls || !headCls) return none; - const target = baseText; - - const modules = new Map(); - let leaf = null; - let hostsOnDisk = null; - for (const [file, text] of moduleTexts) { - if (!text.includes(MARK)) continue; - if (file === HOSTS_MODULE) { hostsOnDisk = text; continue; } - const sf = parse(tm, join(SRC_DIR, file), text); - if (file === LEAF_MODULE) { - const statements = []; - const stmts = sf.getStatements(); - // The generated header is leading trivia of the first statement when no - // import precedes it; a moved statement's text starts after it. - const headerEnd = text.indexOf('\n\n', text.indexOf(MARK)) + 1; - stmts.forEach((st, i) => { - if (Node.isImportDeclaration(st)) { - if (st.getModuleSpecifierValue() === './sql-driver.js' || SEAM_SPECIFIER.test(st.getModuleSpecifierValue())) { - failures.push(`${file}: imports ${st.getModuleSpecifierValue()} — a leaf never imports sql-driver.ts or a sql-driver-* module`); - } - return; - } - if (i === stmts.length - 1 && Node.isExportDeclaration(st) && !st.getModuleSpecifier() && st.getFullText().includes(MARK)) return; - const names = declaredNames(tm, st); - if (!names) { failures.push(`${file}: a statement that is not a moved declaration: ${st.getText().slice(0, 60)}`); return; } - statements.push({ names, text: text.slice(Math.max(st.getFullStart(), headerEnd), st.getEnd()), node: st }); - }); - leaf = { file, sf, statements }; - if (readSibling) { - // The leaf's relative VALUE imports, followed on disk: none may reach - // sql-driver.ts or a sql-driver-* module. A type-only import is erased, so it - // forms no evaluation cycle and is not followed. - const seen = new Set(); - const queue = valueSpecifiers(text).map((spec) => [file, spec]); - while (queue.length > 0) { - const [from, spec] = queue.shift(); - let rel = relative(SRC_DIR, resolve(dirname(join(SRC_DIR, from)), spec.replace(/\.js$/, '.ts'))); - if (seen.has(rel)) continue; - seen.add(rel); - if (rel === HOST_BASENAME || /^sql-driver-[a-z0-9-]+\.ts$/.test(rel)) { - failures.push(`${file}: reaches ${rel} through its value imports (from ${from}) — not a leaf`); - continue; - } - let sibling = readSibling(rel); - if (sibling === null) { - const index = rel.replace(/\.ts$/, '/index.ts'); - sibling = readSibling(index); - if (sibling !== null) rel = index; - } - if (sibling === null) continue; - for (const next of valueSpecifiers(sibling)) queue.push([rel, next]); - } - } - continue; - } - // A facet module: imports, the host interface, and ONE class, the facet, - // whose every member is a static method that is a moved body. - const fns = new Map(); - const facet = facetNameOf(file); - for (const st of sf.getStatements()) { - if (Node.isImportDeclaration(st)) continue; - if (Node.isInterfaceDeclaration(st) && st.getName() === hostNameOf(file)) continue; - if (Node.isClassDeclaration(st) && st.getName() === facet && !fns.size) { - for (const member of st.getMembers()) { - if (Node.isMethodDeclaration(member) && member.isStatic() && member.getBody() && !fns.has(member.getName())) fns.set(member.getName(), member); - else failures.push(`${file}: ${facet} has a member that is not a moved body: ${member.getText().slice(0, 60)}`); - } - continue; - } - failures.push(`${file}: a top-level statement that is neither an import, the host interface nor the facet class ${facet}: ${st.getText().slice(0, 60)}`); - } - modules.set(file, { sf, text, fns, claimed: new Set() }); - } - - const marker = new RegExp(`^\\{\\s*// ${MARK.replace(/[[\]]/g, '\\$&')} The body moved to \`(sql-driver-[a-z0-9-]+\\.ts)\`(, ${DOC_MOVED})?`); - const edits = []; - // A base member of the head member's kind and name: a method, or a get accessor (#30147). - const baseOf = (m) => (Node.isGetAccessorDeclaration(m) ? baseCls.getGetAccessors() : baseCls.getMethods()) - .find((x) => x.getName() === m.getName() && x.isStatic() === m.isStatic()); - for (const m of [...headCls.getMethods(), ...headCls.getGetAccessors()]) { - const body = m.getBody(); - if (!body) continue; - const hit = marker.exec(body.getText()); - if (!hit) { - // A stub that is not generated (a hand-series one) may still write a - // parameter optional whose default computes; the seam keeps the default. - const base = baseOf(m); - if (base && Node.isMethodDeclaration(m)) undoOptionalized(m, base, null); - continue; - } - const name = m.getName(); - const mod = modules.get(hit[1]); - const fn = mod && mod.fns.get(name); - if (!fn) { failures.push(`${name}: its stub names ${hit[1]}, which has no function ${name}`); continue; } - mod.claimed.add(name); - // The stub itself is exactly what `stubBody` writes for this method: one - // call of the facet member of the same name, with the facet's own host - // when the body reads the class (#30105). - { - const lineStart = headText.lastIndexOf('\n', body.getEnd() - 1) + 1; - const closeIndent = headText.slice(lineStart, body.getEnd() - 1); - const usesHost = fn.getParameters().some((p) => p.getName() === 'this'); - const want = stubBody({ node: m, name, usesHost, docMoved: Boolean(hit[2]) }, hit[1], closeIndent); - if (body.getText() !== want) failures.push(`${name}: its stub is not the generated one-call stub (want ${JSON.stringify(want.split('\n').at(-2).trim())})`); - } - const base = baseOf(m); - if (!base || !base.getBody()) { failures.push(`${name}: no method of that name with a body at base`); continue; } - const fnParams = fn.getParameters().filter((p) => p.getName() !== 'this').map((p) => p.getText()); - const baseParams = base.getParameters().map((p) => p.getText()); - // With a comment between the base's parentheses, the facet member carries - // the base's list verbatim after its host parameter (#30147). - const rawSame = !commentInParameters(tm, base) || (() => { - const thisParam = fn.getParameters().find((p) => p.getName() === 'this'); - return facetParamsText(thisParam ? thisParam.getText() : null, base, parameterListText(tm, base)) === parameterListText(tm, fn); - })(); - const asyncOf = (x) => typeof x.isAsync === 'function' && x.isAsync(); - const same = { - body: fn.getBody().getText() === base.getBody().getText(), - params: JSON.stringify(fnParams) === JSON.stringify(baseParams) && rawSame, - returnType: (fn.getReturnTypeNode()?.getText() ?? null) === (base.getReturnTypeNode()?.getText() ?? null), - async: asyncOf(fn) === asyncOf(base), - typeParameters: JSON.stringify(typeParamsOf(fn).map((t) => t.getText())) === JSON.stringify(typeParamsOf(base).map((t) => t.getText())), - static: m.isStatic() === base.isStatic(), - }; - // Docblock ownership: the facet member's leading text is the base - // method's docblock (the stub says so, and only a private method's), else - // exactly the placeholder; the undo puts a moved docblock back. - const lead = mod.text.slice(fn.getStart(true), fn.getStart()); - const docMoved = Boolean(hit[2]); - if (docMoved) { - if (m.getStart(true) !== m.getStart()) failures.push(`${name}: its stub says the docblock moved, but the class still carries one`); - if (m.getScope() !== 'private') failures.push(`${name}: a ${m.getScope()} method's docblock moved off the class (only a private one may)`); - edits.push({ start: m.getStart(), end: m.getStart(), text: lead }); - } else if (lead !== `${placeholderDoc(name)}\n `) { - failures.push(`${name}: the facet member's leading text is neither its moved docblock nor the placeholder`); - } - for (const [what, ok] of Object.entries(same)) if (!ok) failures.push(`${name}: the generated function's ${what} is not the base method's`); - moved.push({ - name, module: hit[1], bodySha: sha256(fn.getBody().getText()), baseBodySha: sha256(base.getBody().getText()), - lines: base.getBody().getEndLineNumber() - base.getBody().getStartLineNumber() + 1, text: fn.getText(), docMoved, ...same, - }); - edits.push({ start: body.getStart(), end: body.getEnd(), text: fn.getBody().getText() }); - if (asyncOf(fn)) edits.push({ start: m.getNameNode().getStart(), end: m.getNameNode().getStart(), text: 'async ' }); - // A return type the stub writes and the base leaves inferred: only the - // one EXPLICIT_RETURN_TYPES names, undone by deleting it (#30147). - if (Node.isMethodDeclaration(m) && m.getReturnTypeNode() && !base.getReturnTypeNode()) { - if (returnTypes[name] !== m.getReturnTypeNode().getText()) failures.push(`${name}: its stub writes a return type the base leaves inferred and EXPLICIT_RETURN_TYPES does not name`); - const close = m.getFirstChildByKindOrThrow(tm.SyntaxKind.CloseParenToken); - edits.push({ start: close.getEnd(), end: m.getReturnTypeNode().getEnd(), text: '' }); - } - if (Node.isMethodDeclaration(m)) undoOptionalized(m, base, fn); - } - - // A parameter a stub writes optional (`x?: T`) where the base computes its - // default (`x: T = f()`): exactly that spelling, of a computed default, and - // the default kept where the body is: in the facet member (`fn`) or, for a - // hand-series stub, in the seam function its import names. The undo puts the - // callee's parameter text back (#30147). - function undoOptionalized(m, base, fn) { - const hp = m.getParameters(); - const bp = base.getParameters(); - if (hp.length !== bp.length) return; - let seam; - hp.forEach((p, i) => { - const b = bp[i]; - if (p.getText() === b.getText()) return; - const init = b.getInitializer(); - if (!init || isDataDefault(tm, init) || !b.getTypeNode() || p.getInitializer() || !p.hasQuestionToken() - || p.getText() !== `${b.getName()}?: ${b.getTypeNode().getText()}`) return; - let callee = null; - if (fn) { - callee = fn.getParameters().filter((x) => x.getName() !== 'this')[i] ?? null; - } else { - if (seam === undefined) { - seam = null; - const binding = headSf.getImportDeclarations().flatMap((d) => d.getNamedImports().map((s) => [d, s])) - .find(([, s]) => (s.getAliasNode()?.getText() ?? s.getName()) === m.getName()); - const spec = binding ? binding[0].getModuleSpecifierValue() : null; - const src = spec && SEAM_SPECIFIER.test(spec) && readSibling ? readSibling(spec.replace(/^\.\//, '').replace(/\.js$/, '.ts')) : null; - const fnDecl = src ? parse(tm, join(SRC_DIR, spec.replace(/\.js$/, '.ts')), src).getFunction(binding[0].getNamedImports().find((s) => (s.getAliasNode()?.getText() ?? s.getName()) === m.getName()).getName()) : null; - seam = fnDecl ? fnDecl.getParameters().filter((x) => x.getName() !== 'this') : null; - if (!seam) failures.push(`${m.getName()}: its stub writes a parameter optional, and the seam function that keeps the default cannot be read`); - } - callee = seam ? seam[i] ?? null : null; - } - if (!callee) return; - if (callee.getText() !== b.getText()) { failures.push(`${m.getName()}: parameter ${b.getName()} is optional on the stub, but its callee does not keep the base default`); return; } - edits.push({ start: p.getStart(), end: p.getEnd(), text: callee.getText() }); - }); - } - - // A field whose initializer moved (#30147): the head initializer is one call - // of the facet member of the field's name, and that member returns the - // initializer exactly, typed as the field. The undo puts the text back. - for (const f of headCls.getProperties()) { - const init = f.getInitializer(); - const hit = init ? /^([A-Z]\w*Facet)\.(\w+)\(\)$/.exec(init.getText()) : null; - if (!hit || hit[2] !== f.getName() || f.isStatic()) continue; - const name = f.getName(); - const entry = [...modules].find(([file]) => facetNameOf(file) === hit[1]); - const fn = entry && entry[1].fns.get(name); - if (!fn) { failures.push(`${name}: its initializer calls ${hit[1]}.${name}, which no facet module declares`); continue; } - const [file, mod] = entry; - mod.claimed.add(name); - const lead = mod.text.slice(fn.getStart(true), fn.getStart()); - const bodyText = fn.getBody().getText(); - const want = /^\{\n {4}return ([\s\S]*);\n {2}\}$/.exec(bodyText); - const retType = fn.getReturnTypeNode()?.getText() ?? null; - const typeOk = retType === `${CLASS_NAME}['${name}']` || retType === `${CLASS_TYPE_ALIAS}['${name}']`; - const baseField = baseCls.getProperties().find((x) => x.getName() === name && !x.isStatic()); - const ok = Boolean(want) && typeOk && fn.getParameters().length === 0 && !fn.isAsync() && lead === `${fieldDefaultDoc(name)}\n ` - && init.getText() === fieldDefaultCall(file, name) && baseField && baseField.getInitializer(); - if (!ok) { failures.push(`${name}: its moved initializer is not the generated one (a returning member typed as the field, called with no arguments)`); continue; } - const same = want[1] === baseField.getInitializer().getText(); - if (!same) failures.push(`${name}: the facet member does not return the base initializer exactly`); - moved.push({ name, module: file, bodySha: sha256(want[1]), baseBodySha: sha256(baseField.getInitializer().getText()), - lines: baseField.getInitializer().getEndLineNumber() - baseField.getInitializer().getStartLineNumber() + 1, text: fn.getText(), - docMoved: false, body: same, params: true, returnType: true, async: true, typeParameters: true, static: true }); - edits.push({ start: init.getStart(), end: init.getEnd(), text: want[1] }); - } - - // The statics route: the forwarder type and object ahead of the class and - // the static block that fills them must be exactly what `staticsTexts` - // writes for the statics the type names, each forwarded as the BASE class - // declares it (a method called, anything else read). Then the undo drops - // them. - const staticsHost = headSf.getInterface(STATICS_HOST_NAME); - const staticsVar = headSf.getVariableStatement(STATICS_NAME); - const markedBlocks = headCls.getMembers().filter((x) => Node.isClassStaticBlockDeclaration(x) && x.getFullText().includes(MARK)); - const hostsBlocks = markedBlocks.filter((x) => x.getFullText().includes(`// ${MARK} Installs`)); - const staticBlocks = markedBlocks.filter((x) => !hostsBlocks.includes(x)); - if (staticsHost || staticsVar || staticBlocks.length > 0) { - const kinds = new Map(); - for (const member of staticsHost ? staticsHost.getProperties() : []) { - const n = member.getName(); - const declared = baseCls.getMembers().filter((x) => typeof x.isStatic === 'function' && x.isStatic() && typeof x.getName === 'function' && x.getName() === n); - if (declared.length === 0) failures.push(`${STATICS_HOST_NAME}.${n}: the base class declares no static of that name`); - kinds.set(n, declared.some((x) => Node.isMethodDeclaration(x)) ? 'method' : 'getter'); - } - const { ahead, block } = staticsTexts(kinds); - const aheadAt = staticsHost ? headText.lastIndexOf(`// ${MARK} The statics of`, staticsHost.getStart()) : -1; - const aheadEnd = staticsVar ? staticsVar.getEnd() : -1; - if (!staticsHost || !staticsVar || aheadAt < 0 || headText.slice(aheadAt, aheadEnd) !== ahead) { - failures.push(`${STATICS_HOST_NAME} / ${STATICS_NAME} are not the generated forwarder declarations for the statics they name`); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', aheadAt), end: aheadEnd, text: '' }); - } - const blockAt = staticBlocks.length === 1 ? headText.lastIndexOf(` // ${MARK} Fills`, staticBlocks[0].getStart()) : -1; - if (staticBlocks.length !== 1 || blockAt < 0 || headText.slice(blockAt, staticBlocks[0].getEnd()) !== block) { - failures.push(`the class's static block is not the generated filler of ${STATICS_NAME} for the statics it names`); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', blockAt), end: staticBlocks[0].getEnd(), text: '' }); - } - } - for (const [file, mod] of modules) { - for (const name of mod.fns.keys()) if (!mod.claimed.has(name)) failures.push(`${file}: function ${name} has no stub on the class`); - } - - // The facet hosts (#30105): `HOSTS_MODULE` and the static block that - // installs the factories must be exactly what `hostsTexts` writes for the - // facets on disk, each member forwarded as the BASE class declares it (a - // method as a closure, anything else as a getter, a member the interface - // does not mark `readonly` with a setter too). Then the undo drops both. - const baseMembers = instanceMembers(tm, baseCls); - const facets = []; - for (const [file, mod] of modules) { - const iface = mod.sf.getInterface(hostNameOf(file)); - if (!iface) continue; - const members = new Map(); - const written = new Set(); - for (const p of iface.getProperties()) { - const n = p.getName(); - const info = baseMembers.get(n); - if (!info) { failures.push(`${file}: ${hostNameOf(file)}.${n} names no instance member of the base class`); continue; } - members.set(n, info.kind === 'method' ? 'method' : 'getter'); - if (info.kind !== 'method' && !p.isReadonly()) written.add(n); - } - facets.push({ moduleFile: file, members, written }); - } - if (facets.length > 0 || hostsOnDisk !== null || hostsBlocks.length > 0) { - const want = hostsTexts(facets); - if (hostsOnDisk !== want.module) failures.push(`${HOSTS_MODULE} is not the generated host module for the facets on disk`); - const blockAt = hostsBlocks.length === 1 ? headText.lastIndexOf(` // ${MARK} Installs`, hostsBlocks[0].getStart()) : -1; - if (hostsBlocks.length !== 1 || blockAt < 0 || headText.slice(blockAt, hostsBlocks[0].getEnd()) !== want.block) { - failures.push('the class\'s host static block is not the generated installer of the facet hosts'); - } else { - edits.push({ start: headText.lastIndexOf('\n\n', blockAt), end: hostsBlocks[0].getEnd(), text: '' }); - } - } - const generatedSpecifier = (spec) => { - const hit = /^\.\/(sql-driver-[a-z0-9-]+)\.js$/.exec(spec ?? ''); - return Boolean(hit && (modules.has(`${hit[1]}.ts`) || `${hit[1]}.ts` === HOSTS_MODULE || (leaf && `${hit[1]}.ts` === leaf.file))); - }; - for (const st of headSf.getStatements()) { - const drop = (Node.isImportDeclaration(st) && generatedSpecifier(st.getModuleSpecifierValue())) || - (Node.isExportDeclaration(st) && (st.getModuleSpecifier() - ? generatedSpecifier(st.getModuleSpecifierValue()) - : st.getFullText().includes(MARK))); - if (drop) edits.push({ start: st.getFullStart(), end: st.getEnd(), text: '' }); - } - edits.sort((a, b) => b.start - a.start || b.end - a.end); - let rebuilt = headText; - for (const e of edits) rebuilt = rebuilt.slice(0, e.start) + e.text + rebuilt.slice(e.end); - - if (leaf) { - // Splice the leaf back, in the order the base interleaves it by NAME. - const restSf = parse(tm, HOST_PATH, rebuilt); - const rest = restSf.getStatements(); - const queue = [...leaf.statements]; - const baseStmts = parse(tm, HOST_PATH, target).getStatements(); - let j = 0; - let assembled = rest.length > 0 ? rebuilt.slice(0, rest[0].getFullStart()) : ''; - for (const b of baseStmts) { - const names = declaredNames(tm, b); - const key = names ? names.join(',') : null; - if (queue.length > 0 && key !== null && queue[0].names.join(',') === key) { - const l = queue.shift(); - assembled += l.text; - const same = l.text === b.getFullText(); - if (!same) failures.push(`${leaf.file}: ${key} is not its base text (leading comments included)`); - movedTop.push({ - name: key, lines: b.getEndLineNumber() - b.getStartLineNumber(true) + 1, - sha: sha256(l.text), baseSha: sha256(b.getFullText()), same, exported: Node.isExportable(b) && b.isExported(), - }); - continue; - } - if (j >= rest.length) { failures.push(`undoing the split runs out of head statements at base ${key ?? b.getKindName()}`); break; } - assembled += rest[j].getFullText(); - j += 1; - } - if (queue.length > 0) failures.push(`${leaf.file}: ${queue.map((q) => q.names.join(',')).join('; ')} not placed — out of base order or not in the base`); - if (rest.length > 0) assembled += rebuilt.slice(rest[rest.length - 1].getEnd()); - rebuilt = assembled; - } - - if (rebuilt !== target) { - const a = rebuilt.split('\n'); - const b = target.split('\n'); - let i = 0; - while (i < Math.max(a.length, b.length) && a[i] === b[i]) i += 1; - failures.push(`undoing the split does not rebuild the base sql-driver.ts: first difference at line ${i + 1}` + - `\n rebuilt: ${JSON.stringify(a[i] ?? '')}\n base: ${JSON.stringify(b[i] ?? '')}`); - } - if (moved.length === 0 && movedTop.length === 0) failures.push('no moved method or declaration found: a proof over nothing is not a proof'); - return { failures, moved, movedTop, linesBefore: lineCount(baseText), linesAfter: lineCount(headText), - routedStatics: staticsHost ? staticsHost.getProperties().length : 0 }; -} - -/** Lines as `wc -l` counts them: newline characters. */ -function lineCount(text) { - return text.split('\n').length - 1; -} - -// ── Reports ────────────────────────────────────────────────────────────────── - -function planReport(planned) { - const out = []; - const bySection = new Map(); - for (const r of planned.records) { - const key = r.section ?? '(above the first banner)'; - if (!bySection.has(key)) bySection.set(key, []); - bySection.get(key).push(r); - } - let movedMethods = 0; - let movedLines = 0; - let movedSaved = 0; - const reasonCounts = new Map(); - for (const [section, rs] of bySection) { - const movers = rs.filter((r) => r.reasons.length === 0); - const lines = movers.reduce((n, r) => n + r.bodyLines, 0); - const saved = movers.reduce((n, r) => n + r.bodyLines - r.stubLines, 0); - movedMethods += movers.length; - movedLines += lines; - movedSaved += saved; - out.push(`§ ${section} -> ${rs[0].module ?? '(stays)'}: ${movers.length}/${rs.length} methods move ` + - `(${lines} body lines out, ${lines - saved} stub lines in)`); - for (const r of rs) { - if (r.reasons.length === 0) out.push(` move ${r.name} (body ${r.bodyLines} -> stub ${r.stubLines})`); - else out.push(` stay ${r.name} (${r.lineCount}) — ${r.reasons.join('; ')}`); - for (const reason of r.reasons) { - const code = reason.split(':')[0]; - reasonCounts.set(code, (reasonCounts.get(code) ?? 0) + 1); - } - } - } - out.push(''); - out.push(`total: ${movedMethods}/${planned.records.length} methods move into ${planned.modules.size} module(s): ` + - `${movedLines} body lines out, ${movedLines - movedSaved} stub lines in, plus ${2 * planned.modules.size} import lines`); - out.push(`stay reasons (a method may carry several): ${[...reasonCounts].sort((a, b) => b[1] - a[1]).map(([c, n]) => `${c} ${n}`).join(', ')}`); - const top = planned.top; - out.push(''); - out.push(`§ top-level declarations ahead of the class -> ${LEAF_MODULE}: ${top.movers.length}/${top.records.length} move`); - const topReasons = new Map(); - for (const r of top.records) { - if (r.reasons.length === 0) out.push(` move ${r.label} (${r.lines})${r.exported ? ' [exported, re-exported]' : ''}`); - else out.push(` stay ${r.label} (${r.lines}) — ${r.reasons.join('; ')}`); - for (const reason of r.reasons) { - const code = reason.split(':')[0]; - topReasons.set(code, (topReasons.get(code) ?? 0) + 1); - } - } - const topLines = top.movers.reduce((n, r) => n + r.lines, 0); - out.push(`top-level total: ${top.movers.length}/${top.records.length} declarations move (${topLines} lines with their docblocks); ` + - `stay reasons: ${[...topReasons].sort((a, b) => b[1] - a[1]).map(([c, n]) => `${c} ${n}`).join(', ') || 'none'}`); - out.push(`lever (a): ${planned.hostExportsForSections.size} staying name(s) exported for the section modules` + - `${planned.hostExportsForSections.size ? ` (${[...planned.hostExportsForSections.keys()].sort().join(', ')})` : ''}; ` + - `${planned.leafExports.length} leaf name(s) exported beside the base exports`); - return out.join('\n'); -} - -function treeHash(files) { - const h = createHash('sha256'); - for (const [name, text] of [...files].sort(([a], [b]) => (a < b ? -1 : 1))) h.update(`${name}\0${sha256(text)}\n`); - return h.digest('hex'); -} - -function printVerify(v) { - for (const f of v.failures) console.error(` ✗ ${f}`); - const identical = v.moved.filter((m) => m.body && m.params && m.returnType && m.async).length; - const identicalTop = v.movedTop.filter((m) => m.same).length; - console.log(`byte-identity: ${identical}/${v.moved.length} moved bodies identical to base (body, parameters, return type, async); ` + - `${identicalTop}/${v.movedTop.length} moved top-level declarations identical to base (leading comments included); ` + - `sql-driver.ts ${v.linesBefore} -> ${v.linesAfter} lines; undoing the split ${v.failures.some((f) => f.startsWith('undoing')) ? 'does NOT' : 'does'} rebuild the base byte-for-byte`); -} - -function gitShow(ref, path) { - return execFileSync('git', ['show', `${ref}:${path}`], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28 }); -} - -/** A file under `sql-driver.ts`'s directory by its relative path, or null when there is none. */ -function readSibling(rel) { - const p = join(SRC_DIR, rel); - return existsSync(p) ? readFileSync(p, 'utf8') : null; -} - -function generatedModulesOnDisk() { - const out = new Map(); - for (const file of [LEAF_MODULE, HOSTS_MODULE, CLASS_HEAD_SECTION[1], ...Object.values(SECTION_MODULES)]) { - if (!file) continue; - const p = join(SRC_DIR, file); - if (existsSync(p)) out.set(file, readFileSync(p, 'utf8')); - } - return out; -} - -// ── Entry ──────────────────────────────────────────────────────────────────── - -const USAGE = [ - 'usage: node scripts/codemod-split-sql-driver.mjs [--write] plan (or apply) the split of an UNSPLIT sql-driver.ts', - ' node scripts/codemod-split-sql-driver.mjs --verify --base REF re-prove a split on disk against sql-driver.ts at REF', - ' node scripts/codemod-split-sql-driver.mjs --self-test', - ' node scripts/codemod-split-sql-driver.mjs --help', -].join('\n'); - -async function main(argv) { - // Answered before any guard: `--help` reads no tree, so the "already split" - // refusal below must never be what a reader asking for usage gets. - if (argv.includes('--help') || argv.includes('-h')) { - console.log(USAGE); - return 0; - } - if (argv.includes('--self-test')) { - await selfTest(); - if (process.exitCode === 1) return 1; - if (!selfTestReachedVerdict) { - console.error('\n✗ codemod-split-sql-driver self-test: selfTest() returned without reaching its verdict,\n' + - 'so no success line was printed. Exiting 0 here would report a self-test that never\n' + - 'finished as a self-test that passed.'); - return 1; - } - return 0; - } - const tm = await loadTsMorph(); - if (argv.includes('--verify')) { - const i = argv.indexOf('--base'); - const ref = i >= 0 ? argv[i + 1] : null; - if (!ref) refuse('--verify needs --base '); - const v = verify(tm, gitShow(ref, `${SRC_REL}/${HOST_BASENAME}`), readFileSync(HOST_PATH, 'utf8'), generatedModulesOnDisk(), { readSibling }); - printVerify(v); - return v.failures.length === 0 ? 0 : 1; - } - const input = readFileSync(HOST_PATH, 'utf8'); - if (input.includes(MARK)) refuse(`${HOST_BASENAME} already carries ${MARK} stubs: run the script on an unsplit file (re-run on the latest main, never on its own output)`); - const planned = plan(tm, input); - console.log(planReport(planned)); - const out = generate(tm, input, planned); - const files = new Map([[HOST_BASENAME, out.host], ...out.modules]); - console.log(`output tree sha256: ${treeHash(files)} (input sha256 ${sha256(input)})`); - const v = verify(tm, input, out.host, out.modules, { readSibling }); - printVerify(v); - if (v.failures.length > 0) { - console.error('✗ the generated split fails byte-identity: nothing written. Report the fork; never hand-edit the split.'); - return 1; - } - if (!argv.includes('--write')) { - console.log('plan only: nothing written (pass --write to apply).'); - return 0; - } - for (const [file] of out.modules) { - const p = join(SRC_DIR, file); - if (existsSync(p) && !readFileSync(p, 'utf8').includes(MARK)) refuse(`${file} exists and was not written by this script`); - } - writeFileSync(HOST_PATH, out.host); - for (const [file, text] of out.modules) writeFileSync(join(SRC_DIR, file), text); - console.log(`✓ wrote ${HOST_BASENAME} and ${out.modules.size} module(s) under ${SRC_REL}`); - return 0; -} - - -/** - * The relative specifiers a module's VALUE imports and re-exports name: an - * `import type` / `export type` declaration, or a named list whose every - * member is `type`-marked, is erased by the compiler and is left out. - */ -function valueSpecifiers(src) { - const out = []; - for (const m of src.matchAll(/^[ \t]*(?:import|export)\s+(type\s+)?([^;'"]*?)\s*from\s*'(\.{1,2}\/[^']+)'/gm)) { - if (m[1]) continue; - const inner = /^\{([^}]*)\}$/.exec(m[2].trim()); - if (inner && inner[1].split(',').map((s) => s.trim()).filter(Boolean).every((s) => s.startsWith('type '))) continue; - out.push(m[3]); - } - for (const m of src.matchAll(/^[ \t]*import\s*'(\.{1,2}\/[^']+)'/gm)) out.push(m[1]); - return out; -} - -// ── Self-test ──────────────────────────────────────────────────────────────── -// -// The proofs above are this script's whole value, and a proof that cannot fail -// proves nothing, so the self-test feeds each one an input it must REFUSE. The -// roster pins battery NAMES with a floor each, the roster's own size is pinned, -// and the verdict sets a flag the dispatch reads (AGENTS.md, "Writing a -// `--self-test`"), so a battery that stops running, or a `return` above the -// verdict, cannot read as a pass. - -let selfTestReachedVerdict = false; - -const SELF_TEST_BATTERIES = Object.freeze({ - 'stay rules': 22, - 'facets, statics and docblocks': 18, - 'top-level moves': 11, - 'byte-identity proof': 10, - 'refusals': 6, - 'codemod-limit retirements (#30147)': 31, - 'split readers (#30147)': 8, -}); -const SELF_TEST_BATTERY_FLOOR = 7; - -const FIXTURE_SECTIONS = Object.freeze({ 'Lifecycle': 'sql-driver-lifecycle.ts', 'Kept': null }); -const FIXTURE_HEAD = Object.freeze(['Head', 'sql-driver-head.ts']); -const FIXTURE_NEEDLES = Object.freeze({ 'PINNED_TEXT': 'a fixture reader', 'needleInMethod(': 'a fixture reader' }); -const FIXTURE_CLASS_NEEDLES = Object.freeze({ 'classReaderText(': 'a fixture reader that also reads the leaf' }); -const FIXTURE_PINS = Object.freeze({ pinnedMethod: 'a fixture reader' }); -const NO_RETIREMENT_TABLES = Object.freeze({ receiverFree: {}, returnTypes: {}, accessors: {}, fieldDefaults: {} }); -const fixturePlan = (tm, text, head = null, tables = NO_RETIREMENT_TABLES) => plan(tm, text, - { sections: FIXTURE_SECTIONS, head, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES, ...tables }); - -function fixtureSource(extraMethods = '') { - const pad = Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - return `import type { Knex } from 'knex'; -import { helperImported } from './other.js'; -import { seamHelper } from './sql-driver-seam.js'; - -/** A value the leaf takes, read by a moved body. */ -const LOCAL_VALUE = 1; -type LocalType = { n: number }; -export interface ExportedShape { a: number } - -// A reader takes this one out of the file by path. -const PINNED = 'PINNED_TEXT'; -function dependsOnPinned(): string { - return PINNED; -} -function namesClass(d: SqlDriver): SqlDriver { - return d; -} -const VIA_SEAM = seamHelper(); -export const DERIVED = LOCAL_VALUE + 1; -function classReaderText(n: number): number { - return n; -} - -export class SqlDriver { - private count = 0; - private knex: any = null; - protected logger: { warn(m: string): void } = console; - private readonly fn = (x: string): string => x; - private static readonly SECRET = 1; - private static bump = 0; - - protected headMethod(): number { -${pad} - return this.count; - } - - // =================================== - // Lifecycle - // =================================== - - /** A private docblock: it moves with the body. */ - private async movable(object: string, trx?: Knex.Transaction): Promise { -${pad} - const a = helperImported(object) as ExportedShape | string; - this.logger.warn(String(a)); - return this.other(String(a)) + String(trx ? this.count : 0); - } - - /** A protected docblock: it stays on the facade. */ - protected other(x: string): string { - return x; - } - - protected writes(): void { -${pad} - this.count = 1; - } - - protected asValue(): string[] { -${pad} - return ['a'].map(this.other); - } - - protected readsLocal(): number { -${pad} - return LOCAL_VALUE + dependsOnPinned().length; - } - - protected namesLocalType(): LocalType | null { -${pad} - return null; - } - - public inferred() { -${pad} - return 1; - } - - protected scoped(object: string): string { -${pad} - return this.getBuilder(object); - } - - protected getBuilder(object: string): string { - return object; - } - - protected defaulted(x: string = 'a'): string { -${pad} - return x; - } - - protected callsField(): string { -${pad} - return this.fn('a'); - } - - protected readsStatic(): number { -${pad} - return SqlDriver.SECRET; - } - - protected bumpsStatic(): number { -${pad} - SqlDriver.bump += 1; - return SqlDriver.SECRET; - } - - protected namesClassType(): SqlDriver | null { -${pad} - return null; - } - - protected delete(): number { -${pad} - return 4; - } - - protected deletesField(): void { -${pad} - delete this.knex; - } - - protected destructured({ a }: { a: number }): number { -${pad} - return a; - } - - protected generic(x: T): T { -${pad} - return this.other(x) as T; - } - - static staticHelper(n: number): number { -${pad} - return n + SqlDriver.SECRET; - } - - static usesThis(): number { -${pad} - return this.SECRET; - } - - protected pinnedMethod(): number { -${pad} - return 3; - } - - protected carriesNeedle(): number { -${pad} - return needleInMethod(1); - } - - protected carriesClassNeedle(): number { -${pad} - return classReaderText(1); - } -${extraMethods} - // =================================== - // Kept - // =================================== - - protected keptSection(): number { -${pad} - return 2 + VIA_SEAM + namesClass(this).count; - } -} - -function needleInMethod(n: number): number { - return n; -} -`; -} - -async function selfTest() { - const tm = await loadTsMorph(); - const batterySeen = new Map(); - let battery = null; - let failed = 0; - let cases = 0; - const open = (name) => { battery = name; }; - const check = (label, ok, detail = '') => { - batterySeen.set(battery, (batterySeen.get(battery) ?? 0) + 1); - cases += 1; - if (ok) console.log(` ✓ [${battery}] ${label}`); - else { failed += 1; console.error(` ✗ [${battery}] ${label}${detail ? ` — ${detail}` : ''}`); } - }; - const refused = (fn) => { try { fn(); return false; } catch (e) { return e instanceof CodemodRefusal; } }; - - open('stay rules'); - { - const planned = fixturePlan(tm, fixtureSource()); - const why = (name) => (planned.records.find((r) => r.name === name)?.reasons ?? ['']).join('; '); - const stays = (name, code) => check(`${name} stays (${code})`, why(name).split('; ').some((r) => r.startsWith(code)), why(name)); - const moves = (name, because) => check(`${name} moves (${because})`, why(name) === '', why(name)); - moves('movable', 'the canonical body, private members read through the host'); - moves('readsLocal', 'lever (a)/(b): it imports the leaf value and the staying function'); - moves('namesLocalType', 'a non-exported type it names moves to the leaf'); - moves('scoped', 'a method it calls goes as a closure'); - moves('other', 'a body no longer than its stub moves too: the facade gate counts bodies, not lines'); - moves('writes', 'a field it assigns goes through a host setter'); - stays('deletesField', 'this-write'); - moves('delete', 'a reserved word is a valid facet member name'); - stays('asValue', 'method-as-value'); - stays('inferred', 'inferred-return-type'); - moves('defaulted', 'the stub keeps the default and forwards the value'); - stays('destructured', 'parameter-shape'); - moves('generic', 'the stub calls the body instantiated with its type parameters'); - moves('staticHelper', 'a static whose body reads no `this`'); - stays('usesThis', 'static-this'); - moves('readsStatic', 'a private static it reads goes through SqlDriverStatics'); - stays('bumpsStatic', 'static-write'); - stays('namesClassType', 'static-route-conflict'); - check('a pinned method and a method carrying a needle stay (path-reader)', - why('pinnedMethod').startsWith('path-reader') && why('carriesNeedle').startsWith('path-reader'), - `${why('pinnedMethod')} | ${why('carriesNeedle')}`); - check('a method in a section that maps to no module stays (section-kept)', why('keptSection').startsWith('section-kept'), why('keptSection')); - stays('headMethod', 'no-section'); - const withHead = fixturePlan(tm, fixtureSource(), FIXTURE_HEAD); - const headRecord = withHead.records.find((r) => r.name === 'headMethod'); - check('with a class-head section, a method above the first banner moves into its module', - headRecord && headRecord.reasons.length === 0 && headRecord.module === 'sql-driver-head.ts', headRecord ? headRecord.reasons.join('; ') : ''); - } - - open('top-level moves'); - { - const input = fixtureSource(); - const planned = fixturePlan(tm, input); - const top = (label) => planned.top.records.find((r) => r.label === label); - const why = (label) => (top(label)?.reasons ?? ['']).join('; '); - check('a value, a local type and an exported interface move', ['LOCAL_VALUE', 'LocalType', 'ExportedShape', 'DERIVED'] - .every((n) => why(n) === ''), ['LOCAL_VALUE', 'LocalType', 'ExportedShape', 'DERIVED'].map(why).join(' | ')); - check('a declaration carrying a reader\'s needle stays (path-reader)', why('PINNED').startsWith('path-reader'), why('PINNED')); - check('a declaration carrying a class-scoped needle moves: its reader reads the leaf', why('classReaderText') === '', why('classReaderText')); - check('a declaration naming a stayer stays (needs-stayer)', why('dependsOnPinned').startsWith('needs-stayer'), why('dependsOnPinned')); - check('a declaration naming the class stays (class-reference)', why('namesClass').startsWith('class-reference'), why('namesClass')); - check('a declaration using a sql-driver-* import stays (seam-import)', why('VIA_SEAM').startsWith('seam-import'), why('VIA_SEAM')); - check('a declaration after the class is not in the region', !top('needleInMethod')); - const out = generate(tm, input, planned); - const leaf = out.modules.get(LEAF_MODULE) ?? ''; - check('the leaf header is line comments, never a docblock the bundled .d.ts would publish', - leaf.includes(MARK) && !leaf.slice(0, leaf.indexOf('\n\n', leaf.indexOf(MARK))).includes('/*')); - check('the leaf imports neither sql-driver.ts nor a sql-driver-* module', leaf.length > 0 && !/from '\.\/sql-driver[.-]/.test(leaf), leaf.slice(0, 200)); - check('sql-driver.ts re-exports the exported movers by name, the interface as a type', - /export \{ DERIVED, type ExportedShape \} from '\.\/sql-driver-top-level\.js';/.test(out.host)); - check('lever (a): the staying function a moved body reads is exported for its module, and the module imports it', - /export \{ dependsOnPinned \};/.test(out.host) && - /import \{ SqlDriverStatics as SqlDriver, dependsOnPinned \} from '\.\/sql-driver\.js';/.test(out.modules.get('sql-driver-lifecycle.ts') ?? '')); - } - - open('byte-identity proof'); - { - const input = fixtureSource(); - const planned = fixturePlan(tm, input); - const out = generate(tm, input, planned); - const again = generate(tm, input, fixturePlan(tm, input)); - const v = verify(tm, input, out.host, out.modules); - check('the generated split proves against its base', v.failures.length === 0 && v.moved.length === 12 && v.movedTop.length === 5, - [...v.failures, `moved: ${v.moved.map((m) => m.name).join()}`, `top: ${v.movedTop.map((m) => m.name).join()}`].join(' | ')); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const mod = out.modules.get('sql-driver-lifecycle.ts'); - const edited = new Map([...out.modules, ['sql-driver-lifecycle.ts', mod.replace('const p3 = 3;', 'const p3 = 4;')]]); - check('one edited character in a moved body fails', verify(tm, input, out.host, edited).failures.length > 0); - check('an edited stub signature fails', - verify(tm, input, out.host.replace('trx?: Knex.Transaction): Promise', 'trx?: Knex.Transaction): Promise'), out.modules).failures.length > 0); - check('an extra top-level statement in a module fails', - verify(tm, input, out.host, new Map([...out.modules, ['sql-driver-lifecycle.ts', `${mod}\nexport const extra = 1;\n`]])).failures.length > 0); - check('a proof over no moved method fails', verify(tm, input, input, new Map()).failures.length > 0); - const leaf = out.modules.get(LEAF_MODULE); - const leafWith = (text) => new Map([...out.modules, [LEAF_MODULE, text]]); - check('one edited character in a moved declaration fails', - verify(tm, input, out.host, leafWith(leaf.replace('const LOCAL_VALUE = 1;', 'const LOCAL_VALUE = 2;'))).failures.length > 0); - check('an edited comment above a moved declaration fails', - verify(tm, input, out.host, leafWith(leaf.replace('/** A value the leaf takes', '/** A value the leaf holds'))).failures.length > 0); - check('a leaf that imports sql-driver.ts back fails', - verify(tm, input, out.host, leafWith(leaf.replace('\nconst LOCAL_VALUE', "\nimport { SqlDriver } from './sql-driver.js';\nconst LOCAL_VALUE"))).failures.length > 0); - const swapped = leaf.replace('type LocalType = { n: number };\nexport interface ExportedShape { a: number }', - 'export interface ExportedShape { a: number }\ntype LocalType = { n: number };'); - check('two moved declarations out of base order fail', swapped !== leaf && verify(tm, input, out.host, leafWith(swapped)).failures.length > 0); - } - - open('facets, statics and docblocks'); - { - const input = fixtureSource(); - const out = generate(tm, input, fixturePlan(tm, input)); - const mod = out.modules.get('sql-driver-lifecycle.ts') ?? ''; - check('the bodies move into one stateless facet class of static methods', /\nexport class LifecycleFacet \{\n/.test(mod) && - /\n static async movable\(this: Pick SqlDriver.SECRET },\n });\n }\n\n // ${MARK} Installs`) && !out.host.includes('bump:')); - check('a written field gets a host setter that assigns it on the driver', - out.host.includes(' get count() { return driver.count; },\n set count(v) { driver.count = v; },')); - check('a generic method calls its body instantiated with its own type parameters', - out.host.includes('return (LifecycleFacet.generic).call(lifecycleHost.of(this), x);') && mod.includes(' static generic(this: Pick= 3 && - out.host.includes("import { lifecycleHost } from './sql-driver-facet-hosts.js';")); - check('the host module keeps one FacetHost per facet and imports types only', - hostsMod.includes("export const lifecycleHost = new FacetHost('LifecycleFacet');") && - !/^import (?!type )/m.test(hostsMod) && hostsMod.includes("import type { LifecycleHost } from './sql-driver-lifecycle.js';")); - check('the builder factory goes into the host as a bound reference, never a forwarding closure', - out.host.includes(' get getBuilder() { return driver.getBuilder.bind(driver); },') && !out.host.includes('getBuilder: (...a)')); - check('a method goes into the host as a closure called on the driver at call time', - /\n [a-z]\w*: \(\.\.\.a\) => driver\.[a-z]\w*\(\.\.\.a\),\n/.test(out.host), out.host.slice(out.host.indexOf('Installs'))); - check('a stub handing another facet\'s host fails', verify(tm, input, - out.host.replace('.call(lifecycleHost.of(this), x)', '.call(otherHost.of(this), x)'), out.modules).failures.length > 0); - check('an edited host module fails', verify(tm, input, out.host, - new Map([...out.modules, [HOSTS_MODULE, hostsMod.replace('this.hosts.set(driver, host);', '')]])).failures.length > 0); - check('a written field\'s setter left out of the host fails', verify(tm, input, - out.host.replace(' set count(v) { driver.count = v; },\n', ''), out.modules).failures.length > 0); - check('a static method keeps its static stub and calls its facet body directly', - out.host.includes(' static staticHelper(n: number): number {\n // [#29520 codemod] The body moved to `sql-driver-lifecycle.ts`.\n return LifecycleFacet.staticHelper(n);\n }')); - const withMod = (text) => new Map([...out.modules, ['sql-driver-lifecycle.ts', text]]); - check('an edited moved docblock fails', verify(tm, input, out.host, - withMod(mod.replace('it moves with the body', 'it moved with the body'))).failures.length > 0); - check('an edited placeholder fails', verify(tm, input, out.host, - withMod(mod.replace(placeholderDoc('other'), placeholderDoc('other').replace('contract', 'promise')))).failures.length > 0); - check('a static forwarded as the wrong kind fails', verify(tm, input, - out.host.replace('SECRET: { get: () => SqlDriver.SECRET },', 'SECRET: { value: SqlDriver.SECRET },'), out.modules).failures.length > 0); - } - - open('codemod-limit retirements (#30147)'); - { - const pad = Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n'); - const extra = ` - protected knexCall(object: string): string { -${pad} - return this.knex(object); - } - - public spelled(object: string) { -${pad} - return this.other(object); - } - - protected commented(object: string /* the table */, n: number): string { -${pad} - return object + n; - } - - public get movedGetter(): string { -${pad} - return this.count > 0 ? 'a' : 'b'; - } - - protected computedDefault(name: string, nowMs: number = Date.now()): number { -${pad} - return nowMs + name.length; - } - - protected seamed(name: string, nowMs: number = Date.now()): number { - return seamed(name, nowMs); - } -`; - const input = fixtureSource(extra).replace("import { seamHelper } from './sql-driver-seam.js';", - "import { seamHelper, seamed } from './sql-driver-seam.js';"); - const SEAM = 'export function seamed(name: string, nowMs: number = Date.now()): number {\n return nowMs + name.length;\n}\n'; - const sibling = (text) => (rel) => (rel === 'sql-driver-seam.ts' ? text : null); - const TABLES = { receiverFree: { knex: 'a fixture closure' }, returnTypes: { spelled: 'string' }, - accessors: { movedGetter: 'a fixture branch' }, fieldDefaults: { logger: 'a fixture sink' } }; - const without = fixturePlan(tm, input, FIXTURE_HEAD); - const planned = fixturePlan(tm, input, FIXTURE_HEAD, TABLES); - const rec = (p, name) => p.records.find((r) => r.name === name); - const why = (p, name) => (rec(p, name)?.reasons ?? ['']).join('; '); - check('with no table, the knex call and the inferred return type stay (field-call, inferred-return-type)', - why(without, 'knexCall').startsWith('field-call') && why(without, 'spelled').startsWith('inferred-return-type') && !rec(without, 'movedGetter'), - `${why(without, 'knexCall')} | ${why(without, 'spelled')}`); - check('a call of a receiver-free field moves', why(planned, 'knexCall') === '', why(planned, 'knexCall')); - check('a method EXPLICIT_RETURN_TYPES names moves', why(planned, 'spelled') === '', why(planned, 'spelled')); - check('a comment between the parentheses no longer keeps a method on the class', why(planned, 'commented') === '' && why(without, 'commented') === '', why(planned, 'commented')); - check('a named get accessor moves as an accessor', why(planned, 'movedGetter') === '' && rec(planned, 'movedGetter').kind === 'accessor', why(planned, 'movedGetter')); - check('a named field default moves into the class-head module', why(planned, 'logger') === '' && rec(planned, 'logger').kind === 'field-default' - && rec(planned, 'logger').module === 'sql-driver-head.ts', why(planned, 'logger')); - check('a computed default is written optional on the stub, a data default is not', - rec(planned, 'computedDefault').optionalized.map((o) => o.text).join() === 'nowMs?: number' && rec(planned, 'defaulted').optionalized.length === 0); - check('a hand-series stub stays (already-moved) and takes the optional spelling too', - why(planned, 'seamed').startsWith('already-moved') && rec(planned, 'seamed').optionalized.map((o) => o.text).join() === 'nowMs?: number', why(planned, 'seamed')); - - const out = generate(tm, input, planned); - const mod = out.modules.get('sql-driver-lifecycle.ts') ?? ''; - const head = out.modules.get('sql-driver-head.ts') ?? ''; - check('the stub writes the named return type; the facet member keeps the base text', - /\n public spelled\(object: string\): string \{\n/.test(out.host) && /\n static spelled\(this: Pick]*>, object: string\) \{\n/.test(mod)); - check('the facet member carries the base parameter list verbatim, comment and all', - /\n static commented\(this: Pick'])[0]); - check('the getter keeps its signature and its body becomes the one-call stub', - /\n public get movedGetter\(\): string \{\n \/\/ \[#29520 codemod\] The body moved to `sql-driver-lifecycle\.ts`[^\n]*\n return LifecycleFacet\.movedGetter\.call\(lifecycleHost\.of\(this\)\);\n \}\n/.test(out.host), - (out.host.match(/get movedGetter[\s\S]{0,200}/) ?? [''])[0]); - check('the stub writes the computed default optional and the facet member keeps the default', - /\n protected computedDefault\(name: string, nowMs\?: number\): number \{\n/.test(out.host) && /\n static computedDefault\(name: string, nowMs: number = Date\.now\(\)\): number \{\n/.test(mod)); - check('the hand-series stub writes the parameter optional and keeps its seam call', - out.host.includes(' protected seamed(name: string, nowMs?: number): number {\n return seamed(name, nowMs);\n }')); - check('the field keeps its type and calls the facet member; the member returns the initializer typed as the field', - out.host.includes(" protected logger: { warn(m: string): void } = HeadFacet.logger();") && - head.includes(` ${fieldDefaultDoc('logger')}\n static logger(): SqlDriver['logger'] {\n return console;\n }`), head.slice(0, 600)); - check('the knex call moves as written, through the host', mod.includes(' return this.knex(object);')); - - const again = generate(tm, input, fixturePlan(tm, input, FIXTURE_HEAD, TABLES)); - check('two runs on one input write byte-identical trees', - treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); - const opts = { readSibling: sibling(SEAM), returnTypes: TABLES.returnTypes }; - const v = verify(tm, input, out.host, out.modules, opts); - const names = v.moved.map((m) => m.name); - check('the generated split proves against its base, each retired mechanism among the moved', - v.failures.length === 0 && ['knexCall', 'spelled', 'commented', 'movedGetter', 'computedDefault', 'logger'].every((n) => names.includes(n)), - [...v.failures, `moved: ${names.join()}`].join(' | ')); - const failsWith = (host, modules = out.modules, o = opts) => verify(tm, input, host, modules, o).failures.length > 0; - const withMod = (file, text) => new Map([...out.modules, [file, text]]); - check('a return type EXPLICIT_RETURN_TYPES does not name fails', failsWith(out.host, out.modules, { ...opts, returnTypes: {} })); - check('an edited written return type fails', failsWith(out.host.replace('public spelled(object: string): string {', 'public spelled(object: string): String {'))); - check('an edited comment in the moved parameter list fails', - failsWith(out.host, withMod('sql-driver-lifecycle.ts', mod.replace('/* the table */', '/* a table */')))); - check('an edited getter body fails', failsWith(out.host, withMod('sql-driver-lifecycle.ts', mod.replace("this.count > 0 ? 'a' : 'b'", "this.count > 1 ? 'a' : 'b'")))); - check('an optional parameter spelled with another type fails', failsWith(out.host.replace('nowMs?: number): number {\n // [#29520', 'nowMs?: any): number {\n // [#29520'))); - check('a facet member that drops the computed default fails', - failsWith(out.host, withMod('sql-driver-lifecycle.ts', mod.replace('static computedDefault(name: string, nowMs: number = Date.now()): number {', 'static computedDefault(name: string, nowMs: number = 0): number {')))); - check('a hand-series stub whose seam drops the default fails', failsWith(out.host, out.modules, { ...opts, readSibling: sibling(SEAM.replace(' = Date.now()', '?')) })); - check('a hand-series optional parameter with no seam to read fails', failsWith(out.host, out.modules, { ...opts, readSibling: null })); - check('an edited moved initializer fails', failsWith(out.host, withMod('sql-driver-head.ts', head.replace(' return console;', ' return globalThis.console;')))); - check('a field calling a member of another name fails', failsWith(out.host.replace('= HeadFacet.logger();', '= HeadFacet.other();'))); - - const refusedWith = (tables) => refused(() => fixturePlan(tm, input, FIXTURE_HEAD, { ...TABLES, ...tables })); - check('RECEIVER_FREE_FIELDS naming a method or no member refuses', - refusedWith({ receiverFree: { other: 'x' } }) && refusedWith({ receiverFree: { gone: 'x' } })); - check('EXPLICIT_RETURN_TYPES naming an annotated or absent method refuses', - refusedWith({ returnTypes: { other: 'string' } }) && refusedWith({ returnTypes: { gone: 'string' } })); - check('MOVED_ACCESSORS naming no get accessor refuses', refusedWith({ accessors: { other: 'x' } }) && refusedWith({ accessors: { gone: 'x' } })); - check('MOVED_FIELD_DEFAULTS naming an untyped field, an initializer reading `this` or a name of the file refuses', - refusedWith({ fieldDefaults: { fn: 'x' } }) && refusedWith({ fieldDefaults: { gone: 'x' } }) && - refused(() => fixturePlan(tm, input.replace(' private count = 0;', ' private count = 0;\n private self: number = this.count;'), FIXTURE_HEAD, { ...TABLES, fieldDefaults: { self: 'x' } })) && - refused(() => fixturePlan(tm, input.replace(' private count = 0;', ' private count = 0;\n private local: number = LOCAL_VALUE;'), FIXTURE_HEAD, { ...TABLES, fieldDefaults: { local: 'x' } }))); - } - - open('refusals'); - { - const unknownBanner = fixtureSource('\n // ── Unnamed section ──────────\n\n protected z(): number {\n return 1;\n }\n'); - check('a banner the section table does not name refuses', refused(() => fixturePlan(tm, unknownBanner))); - const named = fixtureSource('\n // ── Lifecycle ──────────\n\n protected z(): number {\n return 1;\n }\n'); - check('a banner in the dash spelling the table names is read, not refused', !refused(() => fixturePlan(tm, named))); - check('a pin naming what the file lacks refuses', refused(() => plan(tm, fixtureSource(), { ...NO_RETIREMENT_TABLES, sections: FIXTURE_SECTIONS, head: null, pins: { gone: 'x' }, needles: {}, classNeedles: {} }))); - check('a class-scoped needle the file no longer carries refuses', - refused(() => plan(tm, fixtureSource(), { ...NO_RETIREMENT_TABLES, sections: FIXTURE_SECTIONS, head: null, pins: {}, needles: {}, classNeedles: { 'gone text': 'x' } }))); - check('a needle the file no longer carries refuses', refused(() => plan(tm, fixtureSource(), { ...NO_RETIREMENT_TABLES, sections: FIXTURE_SECTIONS, head: null, pins: {}, needles: { 'gone text': 'x' }, classNeedles: {} }))); - // `--help` reads no tree: it answers before the "already split" guard, so - // it exits 0 whether sql-driver.ts on disk is split (as on a branch) or not. - check('--help is answered, never refused, whatever sql-driver.ts holds', (await main(['--help']).catch(() => 2)) === 0); - } - - open('split readers (#30147)'); - { - // `sql-driver-split-source.mjs` hands the by-path readers `SqlDriver` as - // one text again. Driven over a split this script generates, written to a - // directory the way `--write` lays it out. - const input = fixtureSource(); - const out = generate(tm, input, fixturePlan(tm, input)); - const dir = mkdtempSync(join(tmpdir(), 'codemod-split-reader-')); - const lay = (host, modules) => { - rmSync(dir, { recursive: true, force: true }); - mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, HOST_BASENAME), host); - for (const [name, text] of modules) writeFileSync(join(dir, name), text); - }; - const read = () => { try { return readSqlDriverSource(dir); } catch (e) { return { error: e.message }; } }; - try { - lay(out.host, out.modules); - const r = read(); - const base = parse(tm, HOST_BASENAME, input).getClassOrThrow(CLASS_NAME); - const baseBody = (name) => (base.getMethod(name) ?? base.getGetAccessor(name))?.getBody()?.getText(); - const stubs = (out.host.match(new RegExp(`// ${MARK.replace(/[[\]#]/g, '\\$&')} The body moved to`, 'g')) ?? []).length; - check('every stub the split writes is followed', !r.error && r.spliced.length === stubs && stubs > 0, - r.error ?? `${r.spliced.length} followed of ${stubs}`); - check('each followed stub reads its base body, byte for byte, after the signature the class keeps', - !r.error && r.spliced.every(({ member }) => baseBody(member) && r.text.includes(baseBody(member))), - r.error ?? r.spliced.filter(({ member }) => !r.text.includes(baseBody(member) ?? '\0')).map((x) => x.member).join()); - check('no stub text survives in the joined source', !r.error && !r.text.includes(`${MARK} The body moved to`)); - check('the leaf is read and stands ahead of the class', - !r.error && r.files.includes(LEAF_MODULE) && r.text.indexOf('const LOCAL_VALUE = 1;') >= 0 - && r.text.indexOf('const LOCAL_VALUE = 1;') < r.text.indexOf(`export class ${CLASS_NAME}`)); - lay(input, new Map()); - const unsplit = read(); - check('an unsplit sql-driver.ts is read as it stands', !unsplit.error && unsplit.text === input && unsplit.spliced.length === 0); - lay(out.host, new Map([...out.modules].filter(([name]) => name !== 'sql-driver-lifecycle.ts'))); - check('a stub naming a module that is not there refuses', /does not exist/.test(read().error ?? ''), read().error); - const mod = out.modules.get('sql-driver-lifecycle.ts'); - lay(out.host, new Map([...out.modules, ['sql-driver-lifecycle.ts', mod.replace('static async movable(', 'static async renamed(')]])); - check('a stub whose facet lacks the static refuses', /has no static `movable`/.test(read().error ?? ''), read().error); - lay(out.host.replace(/return LifecycleFacet\.movable\.call\(lifecycleHost\.of\(this\)/, 'return LifecycleFacet.movable.call(this'), out.modules); - check('a marked stub of another shape refuses rather than reading the stub', /is not one `return Facet/.test(read().error ?? ''), read().error); - } finally { - rmSync(dir, { recursive: true, force: true }); - } - } - - const declared = Object.keys(SELF_TEST_BATTERIES); - if (declared.length < SELF_TEST_BATTERY_FLOOR) { - failed += 1; - console.error(`✗ self-test floor: ${declared.length} batteries declared, below the pinned ${SELF_TEST_BATTERY_FLOOR}`); - } - for (const [name, count] of batterySeen) { - if (!declared.includes(name)) { failed += 1; console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s) but is not declared`); } - } - for (const name of declared) { - const count = batterySeen.get(name) ?? 0; - if (count < SELF_TEST_BATTERIES[name]) { - failed += 1; - console.error(`✗ self-test floor: battery "${name}" ran ${count} case(s), below its pinned ${SELF_TEST_BATTERIES[name]}`); - } - } - if (failed > 0) { - console.error(`\n✗ codemod-split-sql-driver self-test: ${failed} failure(s) (cases and floor).`); - process.exitCode = 1; - selfTestReachedVerdict = true; - return; - } - console.log(`\n✓ codemod-split-sql-driver self-test: ${cases} cases in ${declared.length} batteries pass.`); - selfTestReachedVerdict = true; -} - -if (isEntrypoint(import.meta.url)) { - main(process.argv.slice(2)).then( - (code) => process.exit(code), - (error) => { - if (error instanceof CodemodRefusal) { - console.error(`✗ codemod-split-sql-driver: ${error.message}`); - process.exit(2); - } - console.error(error); - process.exit(2); - }, - ); -} diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index d53503d6123..74f758d5a75 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -720,7 +720,7 @@ export const CROSS_PACKAGE_TEST_INPUTS = { 'packages/drivers/driver-sql/src/sql-driver.ts', 'packages/drivers/driver-sql/src/schema-drift.ts', // The facade form of that first file (#30147). The codemod - // (`scripts/codemod-split-sql-driver.mjs`) left `createColumn` and the + // (split by #30139 and #30363) left `createColumn` and the // other members those pins slice on the class as one-call stubs and moved // their bodies into `sql-driver-*.ts` facet modules, and the top-level // declarations into the leaf. The five generate-* pins read `SqlDriver` diff --git a/scripts/sql-driver-split-source.mjs b/scripts/sql-driver-split-source.mjs index aa9be57747c..8dc18c9f759 100644 --- a/scripts/sql-driver-split-source.mjs +++ b/scripts/sql-driver-split-source.mjs @@ -4,7 +4,7 @@ * sql-driver-split-source -- `SqlDriver`'s text read back as ONE source, for * the readers that take it by path (#30147). * - * `scripts/codemod-split-sql-driver.mjs` leaves each moved method on the class + * The sql-driver codemod (split by #30139) leaves each moved method on the class * as a one-call stub and puts its body, byte for byte, on a static method of a * facet class in a `sql-driver-*.ts` module; the top-level declarations ahead * of the class go whole to the leaf, `sql-driver-top-level.ts`. A reader that From 28b3b32ff30bba9329851027cb63f6c36ff89b8e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:51:15 +0000 Subject: [PATCH 2/2] chore(scripts): regen-artifacts NOT_DRIVER_MANAGED why cites #29993, not the deleted codemod The conversions-registry entry's `why` string still named scripts/codemod-split-conversions-registry.mjs, which this PR deletes. It now cites the PR that made the split. Text only, no behaviour change. Co-Authored-By: Claude --- scripts/regen-artifacts.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/regen-artifacts.mjs b/scripts/regen-artifacts.mjs index 7ab8561a479..86db416ccb9 100644 --- a/scripts/regen-artifacts.mjs +++ b/scripts/regen-artifacts.mjs @@ -434,7 +434,7 @@ export const NOT_DRIVER_MANAGED = Object.freeze([ + 'both is usually right, but "usually" is a human judgement, not a merge rule. Not split per-entry ' + 'alongside the migrations registry by #7297 (the #6957 ruling names two append registries and the ' + 'other one is `scripts/adr-anchors.json`, #7301); #29987 split it by a codemod ' - + '(`scripts/codemod-split-conversions-registry.mjs`): each conversion is now a module of its own ' + + '(split by #29993): each conversion is now a module of its own ' + 'under `conversions/entries/`, a new file that never conflicts, and what a retirement still edits ' + 'here is its import line and its list entry — hand-written text a human merges, never regenerated.', },